<template>
  <div class="table-box">
    <LjVxeTable
      ref="VxeTableRef"
      row-key="areaid"
      :columns="columns"
      :request-api="getData"
      :data-callback="dataCallback"
      :dwname="dwname"
      :table-props="tableProps"
      :table-events="tableEvents"
      :auto-load-layout="false"
      pagination
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button-group>
          <el-button @click="handleOpenNewTable">{{ $t("common.add") }}</el-button>
          <el-button @click="fDelete">{{ $t("common.delText") }}</el-button>
        </el-button-group>
      </template>
    </LjVxeTable>
  </div>

  <LjDialog
    ref="LjDrawerRef"
    class="is-selector"
    v-bind="{
      ...drawerDefineProp
    }"
    :style="{ padding: 0 }"
  >
    <template #header>
      <div class="flx-1">
        <span class="text-h5-b">分区比例设置</span>
      </div>
    </template>
    <div class="flx-1 h-full">
      <LjHeaderMenu :action="orderStatus ? orderEditAction : orderDefaultAction">
        <template #rightBtn>
          <el-checkbox label="含包边" v-model="ifEdge" />
        </template>
      </LjHeaderMenu>
      <Detail class="flx-1" :data="mainData" :status="orderStatus" :enum="enumMap" />
    </div>
  </LjDialog>
</template>

<script setup lang="ts" name="baseinfo_bednetarealist">
import { ref, onMounted, provide } from "vue";
import { getBedNetAreaList } from "@/api/modules/basicinfo";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import LjDrawer from "@/components/LjDrawer/index.vue";
import Detail from "./detail.vue";
import { useHooks } from "./hooks/index";
import LjDialog from "@/components/LjDialog/index.vue";
import LjHeaderMenu from "@/components/LjHeaderMenu/index.vue";
import { useI18n } from "vue-i18n";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { cloneDeep } from "lodash-es";
import { ElButton, ElMessage } from "element-plus";

const dwname = "web_bednet_arealist";
const mainData = ref({});
const tableProps = {
  height: "auto",
  editConfig: { trigger: "click", mode: "cell" }
  // rowClassName: rowClsNameFunc
  // exportConfig: {
  //   filename: t("menu.saletaskmx") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
  // }
};

const { t } = useI18n();
const { VxeTableRef, LjDetailRef, columns, ifEdge, fDelete, fSave } = useHooks(t);
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const orderStatus = ref("");
const enumMap = ref(new Map());

const orderDefaultAction = [
  buttonDefault({
    label: t("common.cancelText"),
    icon: "iconchevron-left"
  }),
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    clickFunc: item => {
      const save_data = LjDetailRef.value?._mainData;

      fSave({ area: save_data }).then(() => {
        LjDrawerRef.value.hide();
      });
    }
  })
];
const orderEditAction = [
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    clickFunc: async item => {
      const save_data = LjDetailRef.value?._mainData;

      await LjDetailRef.value.toValidateForm();

      let arr = [];
      for (const key in save_data) {
        if (key.indexOf("area_") > -1) {
          arr.push(Number(save_data[key]));
        }
      }
      console.log("hasZerosBetweenNonZeroNumbers(arr) :>> ", hasZerosBetweenNonZeroNumbers(arr));

      // 判断数值连续填写，中间不能有0
      if (hasZerosBetweenNonZeroNumbers(arr)) {
        ElMessage.error(`分区比例应连续不间断填写`);
        return false;
      }

      fSave({ area: save_data }).then(() => {
        LjDrawerRef.value.hide();
      });
    }
  })
];

/**
 * @description 判断数值连续填写，中间不能有0
 * @param arr 数值数组
 * @param {number} 存在0的位置
 */
function hasZerosBetweenNonZeroNumbers(arr) {
  while (arr[arr.length - 1] === 0) {
    arr.pop();
  }

  let hasZeroBetweenNonZero = false;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== 0 && arr[i + 1] === 0) {
      hasZeroBetweenNonZero = true;
      break;
    }
  }
  return hasZeroBetweenNonZero;
}

/*
 * @description 抽屉默认属性
 */
const drawerDefineProp = {
  draggable: true,
  overflow: true,
  width: "40%"
  // modalClass: "lj-file-dialog"
};

const getData = (params: any) => {
  return getBedNetAreaList(params);
};

const dataCallback = (data: any) => {
  if (data.tableinfo?.columns) {
    data.tableinfo?.columns.map((item: any) => {
      if (item?.enum) {
        enumMap.value.set(item.field, item.enum);
      }
    });
  }
  return {
    list: data.datatable,
    tableinfo: data.tableinfo,
    total: data.totalcnt,
    pageNum: data.pageindex,
    pageSize: data.pagesize
  };
};

const LjDrawerRef = ref();
const handleDBlClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  // 弹窗
  mainData.value = cloneDeep(row);
  orderStatus.value = "edit";
  LjDrawerRef.value.show();
};

const handleOpenNewTable = () => {
  mainData.value = {};
  orderStatus.value = "new";
  LjDrawerRef.value.show();
};

// 返回绑定的事件
const tableEvents = {
  "cell-dblclick": handleDBlClickTable
  // "cell-click": handleClickTable
};
</script>
