<template>
  <LjFoldLayout ref="LjFoldLayoutRef" v-bind="layoutSetting">
    <div class="main-box flx-col">
      <LjVxeTable
        ref="VxeTableRef"
        row-key="varid"
        :columns="columns"
        :request-api="getData"
        :data-callback="dataCallback"
        :dwname="dwname"
        :table-props="tableProps"
        :table-events="tableEvents"
        :tool-button="['export', 'refresh', 'setting', 'search', 'location']"
        :init-param="initParams"
        :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 @click="handleClickFormula">编辑公式</el-button>
          </el-button-group>
          <el-tabs v-model="initParams.varkind" class="tableheader-tabs">
            <el-tab-pane label="床网" :name="0"></el-tab-pane>
            <el-tab-pane label="床垫" :name="1"></el-tab-pane>
          </el-tabs>
        </template>
      </LjVxeTable>
    </div>
    <template #right>
      <div class="main-box flx-col">
        <LjVxeTable
          row-key="varmxid"
          :columns="columns_mx"
          :init-param="initParams_mx"
          :request-api="getMxData"
          :data-callback="dataMxCallback"
          :dwname="dwname_mx"
          :table-props="tableMxProps"
          :auto-load-layout="false"
          :collapse-buttons="true"
          pagination
          :table-button="[]"
        >
        </LjVxeTable>
      </div>
    </template>
  </LjFoldLayout>

  <LjDialog
    ref="LjDrawerRef"
    class="is-selector"
    v-bind="{
      ...drawerDefineProp
    }"
    :style="{ padding: 0 }"
  >
    <template #header>
      <div class="flx-1">
        <span class="text-h5-b">变量名称: {{ varname }}</span>
      </div>
    </template>
    <div class="flx-1 h-full">
      <LjHeaderMenu :data="mainData" :action="orderStatus ? orderEditAction : orderDefaultAction" />
      <Detail class="flx-1" :data="mainData" :status="orderStatus" :enum="enumMap" />
    </div>
  </LjDialog>

  <FormulaEditorDialog ref="formulaEditorRef" @confirm="handleFormulaConfirm" />
</template>

<script setup lang="ts" name="baseinfo_bednetvarlist">
import { ref, onMounted, provide } from "vue";
import { getBedNetVarList, getBedNetVarMxList, GetFormulaVarList } 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 LjFoldLayout from "@/components/LjFoldLayout/index.vue";
import FormulaEditorDialog from "@/views/system/formula-editor/index.vue";

const dwname = "web_bednetvarlist";
const dwname_mx = "web_bednetvarmxlist";
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 tableMxProps = {
  // height: "",
  // minHeight: "300px"
  height: "auto"
  // editConfig: { trigger: "click", mode: "cell" }
  // rowClassName: rowClsNameFunc
  // exportConfig: {
  //   filename: t("menu.saletaskmx") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
  // }
};
const layoutSetting = {
  dwname: dwname,
  right: {
    hidden: false
  }
};
const showEditor = ref(false);
const formulaEditorRef = ref();

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

const orderStatus = ref("");
const varname = ref("");
const enumMap = ref(new Map());
const initParams = ref({ varkind: 0 });
const initParams_mx = ref({ varid: 0 });

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

      // fSave({ bednetvar: save_data }).then(() => {
      //   LjDrawerRef.value.hide();
      // });
    }
  })
];
const orderEditAction = [
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    clickFunc: item => {
      const save_data = LjDetailRef.value?._mainData;
      save_data.varkind = initParams.value.varkind;
      save_data.ifmxformula = Number(save_data?.ifmxformula ?? 0);

      save_data.mxlist = VxeTableMxRef.value?.tableData;
      fSave({ bednetvar: save_data }).then(() => {
        LjDrawerRef.value.hide();
      });
    }
  })
];

const handleClickFormula = () => {
  formulaEditorRef.value.show(true);
};

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

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

const getMxData = (params: any) => {
  return getBedNetVarMxList(params);
};

const dataMxCallback = (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 dataCallback = (data: any) => {
  if (data.tableinfo?.columns) {
    data.tableinfo?.columns.map((item: any) => {
      if (item?.enum) {
        enumMap.value.set(item.field, item.enum);
      }
    });
  }
  if (data.datatable && data.datatable.length) {
    let row = data.datatable[0];
    initParams_mx.value.varid = Number(row.varid);
    fChangeBedNetType(parseInt(row.varclass));
  }
  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);
  varname.value = row.varname;
  orderStatus.value = "edit";
  LjDrawerRef.value.show();
};

const handleOpenNewTable = () => {
  // mainData.value = [
  //   {
  //     varid: 0,
  //     varclass: "0"
  //   }
  // ];
  mainData.value = {
    varid: 0,
    varclass: "0"
  };
  varname.value = "";
  orderStatus.value = "new";
  LjDrawerRef.value.show();
};

/**
 * @description 单击表格单元格，非打开新窗口时，获取单据明细
 */
const handleClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  initParams_mx.value.varid = Number(row.varid);
  fChangeBedNetType(parseInt(row.varclass));
};

const handleFormulaConfirm = (formula: string) => {
  console.log(formula);
};

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