import { ref, reactive, computed, toRefs, nextTick } from "vue";
import { Table } from "@/hooks/interface";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { ALLOW_EDIT_STATE, sys_arry_formulatype } from "@/config/index";
import { SaveMtrlDef, DeleteMtrlDef, BanMtrlDef } from "@/api/modules/basicinfo";
import { ElMessage, ElMessageBox, ElPopconfirm, ElButton } from "element-plus";
import { useHooks as useHooks_mtrltype } from "@/views/baseinfo/mtrltype/hooks/index";
import { useUserStore } from "@/stores/modules/user";
import MtrldefSelect from "@/views/system/selector/mtrldefNoPrice/select.vue";
import { Minus, Plus, InfoFilled } from "@element-plus/icons-vue";
import { CommonDynamicSelect } from "@/api/modules/common";
import { fa } from "element-plus/es/locale";
interface defaultState {
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 列表Ref
   */
  VxeTableRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRef: any;
  /**
   * @description 详情页明细表格Ref
   */
  VxeTableMxRef: any;
  MtrldefDialogRef: any;
  MtrldefDialogProps: any;
  formulaKindEnum: any;
  /**
   * @description 物料分类取值
   */
  mtrltypeTabList: any[];
  fabricMxTabList: any[];
  fabricMxTab: any[];
  oriMxData: any;
}

/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  const state = reactive<defaultState>({
    orderStatus: "",
    VxeTableRef: null,
    LjDetailRef: null,
    VxeTableMxRef: null,
    formulaKindEnum: null,
    MtrldefDialogRef: null,
    MtrldefDialogProps: {},
    mtrltypeTabList: [
      {
        label: "选布料",
        formulakinds: [0, 1, 2, 3, 4, 101, 111],
        value: 3
      },
      {
        label: "喷胶绵",
        formulakinds: [40, 41, 42, 43, 44, 102, 112],
        value: 5
      },
      {
        label: "裥绵海绵",
        formulakinds: [50, 51, 52, 53, 54, 103, 113],
        value: 4
      },
      {
        label: "无纺布",
        formulakinds: [60, 61, 62, 63, 64, 104, 114],
        value: 30
      },
      {
        label: "裥花图案",
        formulakinds: [70, 71, 72, 73, 74, 105, 115],
        value: 26
      },
      {
        label: "布料-加工工艺",
        formulakinds: [80, 81, 82, 83, 84, 106, 116],
        value: 15
      },
      {
        label: "拉手",
        formulakinds: [5],
        value: 10
      },
      {
        label: "刺绣",
        formulakinds: [6],
        value: 11
      },
      {
        label: "大侧*压布",
        formulakinds: [7],
        value: 2
      },
      {
        label: "大侧*边带",
        formulakinds: [8, 9],
        value: 9
      },
      {
        label: "大侧*上下压线",
        formulakinds: [10],
        value: 12
      },
      {
        label: "垫层",
        formulakinds: [11, 32, 33],
        value: 6
      },
      {
        label: "顶布",
        formulakinds: [12],
        value: 3
      },
      {
        label: "毡类",
        formulakinds: [13],
        value: 7
      },
      {
        label: "打底无纺布",
        formulakinds: [14],
        value: 2
      },
      {
        label: "辅料",
        formulakinds: [15],
        value: 8
      },
      {
        label: "PE",
        formulakinds: [16],
        value: 16
      },
      {
        label: "外层PE",
        formulakinds: [17],
        value: 17
      },
      {
        label: "PVC",
        formulakinds: [18],
        value: 18
      },
      {
        label: "卷包包装",
        formulakinds: [19],
        value: 19
      },
      {
        label: "牛皮纸袋",
        formulakinds: [20],
        value: 20
      },
      {
        label: "蓝色PE护角",
        formulakinds: [21],
        value: 21
      },
      {
        label: "无纺布袋",
        formulakinds: [22],
        value: 22
      },
      {
        label: "牛皮袋护角",
        formulakinds: [23],
        value: 23
      },
      {
        label: "编织袋",
        formulakinds: [24],
        value: 24
      },
      {
        label: "外袋",
        formulakinds: [25],
        value: 13
      },
      {
        label: "内袋",
        formulakinds: [26],
        value: 14
      },
      {
        label: "无拉手脚轮",
        formulakinds: [27],
        value: -1
      },
      {
        label: "拉钮",
        formulakinds: [28],
        value: -1
      },
      {
        label: "网面布料",
        formulakinds: [29],
        value: -1
      },
      {
        label: "防火线",
        formulakinds: [30],
        value: -1
      },
      {
        label: "木托",
        formulakinds: [31],
        value: -1
      },
      {
        label: "床网",
        formulakinds: [99],
        value: -1
      }
    ],
    fabricMxTabList: [
      {
        label: "裥面",
        name: "tabpage_8",
        visible: () => Number(state.mattresstypeEnum?.if_top_side) == 1,
        type: [0, 80, 40, 50, 60, 70, 9000],
        billtype: 901
      },
      {
        label: "裥底",
        name: "tabpage_9",
        visible: () => Number(state.mattresstypeEnum?.if_button_sdie) == 1,
        type: [1, 81, 41, 51, 61, 71, 9001],
        billtype: 902
      },
      {
        label: "裥大恻",
        name: "tabpage_10",
        visible: () => Number(state.mattresstypeEnum?.if_big_side) == 1,
        type: [2, 82, 42, 52, 62, 72, 9002],
        billtype: 903
      },
      {
        label: "裥小恻",
        name: "tabpage_11",
        visible: () => Number(state.mattresstypeEnum?.if_small_side) == 1,
        type: [3, 83, 43, 53, 63, 73, 9003],
        billtype: 904
      },
      {
        label: "裥V恻",
        name: "tabpage_12",
        visible: () => Number(state.mattresstypeEnum?.if_v_side) == 1,
        type: [4, 84, 44, 54, 64, 74, 9004],
        billtype: 905
      }
    ],
    fabricMxTab: [],
    oriMxData: {}
  });
  // 表格配置项
  const columns: ColumnProps<any>[] = [
    { type: "checkbox", width: 50, fixed: "left" },
    { title: "#", field: "pid", fixed: "left", width: 80 },
    {
      field: "billcode",
      title: "报价唯一码",
      align: "left",
      table: "u_semi_finished_product",
      search: {
        el: "input",
        props: {
          placeholder: "自动生成,不需要填写"
        },
        order: 0
      },
      basicinfo: {
        el: "input",
        editable: (scope: any) => {
          return false;
        },
        group: "单据信息",
        span: 1,
        order: 1
      }
    },
    {
      field: "semi_finished_code",
      title: "半成品编码",
      align: "left",
      table: "u_semi_finished_product",
      search: {
        el: "input",
        props: {
          placeholder: "唯一码/编码/名称"
        },
        order: 5
      },
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        span: 2,
        order: 5
      }
    },
    {
      field: "semi_finished_name",
      title: "半成品名称",
      align: "left",
      table: "u_semi_finished_product",
      search: {
        el: "input",
        props: {
          placeholder: "唯一码/编码/名称"
        },
        order: 7
      },
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        span: 2,
        order: 7
      }
    },
    {
      field: "flag",
      title: "审核",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "opemp",
      title: "登记人",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "opdate",
      title: "登记时间",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "auditemp",
      title: "审核人",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "auditdate",
      title: "审核时间",
      basicinfo: {
        visible: false
      }
    },
    {
      field: "billdate",
      title: "单据日期",
      datatype: "date",
      basicinfo: {
        el: "date-picker",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 1,
        span: 1
      }
    },
    {
      field: "semi_finished_type",
      title: "半成品类别",
      enum: [
        {
          value: "901",
          label: "半成品裥面"
        },
        {
          value: "902",
          label: "半成品裥底"
        },
        {
          value: "903",
          label: "半成品裥大侧"
        },
        {
          value: "904",
          label: "半成品裥小侧"
        },
        {
          value: "905",
          label: "半成品裥V侧"
        }
      ],
      basicinfo: {
        el: "select",
        editable: ALLOW_EDIT_STATE,
        rules: [{ required: true }],
        props: {
          clearable: false,
          filterable: true,
          onChange: () => funcImportMx()
        },
        order: 3,
        span: 2
      }
    },
    {
      field: "production_size",
      title: "生产尺寸",
      basicinfo: {
        el: "input-number",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 2,
        span: 1
      }
    },
    {
      field: "hemming_process",
      title: "锁边工艺",
      basicinfo: {
        el: "input-number",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 4,
        span: 1
      }
    },
    {
      field: "hemmed_size",
      title: "锁边后尺寸",
      basicinfo: {
        el: "input-number",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 6,
        span: 1
      }
    },
    {
      field: "shrinkage_rate",
      title: "收缩率",
      basicinfo: {
        el: "input-number",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 8,
        span: 1
      }
    },
    {
      field: "elongation_rate",
      title: "拉伸率",
      basicinfo: {
        el: "input-number",
        editable: ALLOW_EDIT_STATE,
        order: 10,
        span: 1
      }
    },
    {
      field: "dscrp",
      title: "备注",
      basicinfo: {
        el: "input",
        span: 2,
        order: 9,
        editable: ALLOW_EDIT_STATE,
        props: { type: "textarea", rows: 5 },
        row: 3
      }
    }
  ];

  const columnsMx: ColumnProps<any>[] = [
    { title: "#", type: "seq", fixed: "left", width: 80 },
    {
      title: "+",
      field: "addmx",
      width: 80,
      render: (scope: any) => {
        let _if_mtrl = Number(scope.row.if_mtrl);
        if (_if_mtrl > 1) {
          if (state.orderStatus) {
            return (
              <>
                <ElPopconfirm
                  width="220"
                  icon={InfoFilled}
                  title={t("business.tips.mattress.addMx")}
                  confirm-button-text={t("common.addText")}
                  onConfirm={() => funcAddMtrlMx(scope)}
                >
                  {{
                    reference: () => {
                      return <ElButton type="primary" plain circle icon={Plus}></ElButton>;
                    }
                  }}
                </ElPopconfirm>
              </>
            );
            // return <ElButton type="primary" plain circle icon={Plus} onClick={() => funcAddMtrlMx(scope)}></ElButton>;
          } else {
            return <>+</>;
          }
        } else {
          return <></>;
        }
      }
    },
    {
      title: "-",
      field: "delmx",
      width: 80,
      render: (scope: any) => {
        let _if_mtrl = Number(scope.row.if_mtrl);
        if (_if_mtrl > 1) {
          if (state.orderStatus) {
            return (
              <>
                <ElPopconfirm
                  width="220"
                  icon={InfoFilled}
                  title={t("business.tips.mattress.delMx")}
                  confirm-button-text={t("common.delText")}
                  confirm-button-type="danger"
                  onConfirm={() => funcDelMtrlMx(scope)}
                >
                  {{
                    reference: () => {
                      return <ElButton type="danger" plain circle icon={Minus} />;
                    }
                  }}
                </ElPopconfirm>
              </>
            );
            // return <ElButton type="danger" plain circle icon={Minus} onClick={() => funcDelMtrlMx(scope)}></ElButton>;
          } else {
            return <>-</>;
          }
        } else {
          return <></>;
        }
      }
    },
    {
      title: "位置",
      field: "chastr"
    },
    {
      title: "公式名",
      field: "formulakind",
      table: "u_mattress_formula",
      align: "left",
      isFilterEnum: true,
      fieldNames: { value: "value", label: "label" },
      render: (scope: any) => {
        const { column, row, status } = scope;
        let itmName = state.formulaKindEnum.find(t => t.value == row.formulakind)?.label ?? "";
        return <>{itmName}</>;
      }
    },
    {
      title: "按物料？",
      field: "if_mtrl",
      table: "u_mattress_formula",
      enum: [
        {
          value: "0",
          label: "无物料"
        },
        {
          value: "1",
          label: "单物料"
        },
        {
          value: "2",
          label: "多物料"
        }
      ]
    },
    {
      title: "厚度cm",
      field: "thickness",
      datatype: "number",
      editRender: {
        name: "$input"
      }
    },
    {
      title: "核价物料",
      field: "mtrlname",
      editRender: {},
      editColRender: (scope: any) => {
        console.log("mtrlname hooks render scope :>> ", scope);
        console.log("mtrlname hooks render LjDetailRef.value._mainData :>> ", state.LjDetailRef);
        const { column, row, status } = scope;
        let field = column.field;
        let _label = column.title;
        // if (column?.format) {
        //   _label = handleRowAccordingToProp(searchParam, field, column?.format);
        // }
        let _deptid = state.LjDetailRef._mainData.deptid;
        let deptEnum = state.LjDetailRef.enumMap.get("deptid");
        let _pricelistid = 0;
        console.log("deptEnum :>> ", deptEnum);
        if (deptEnum) {
          let depItem = deptEnum.find((item: any) => item.value == _deptid);
          console.log("depItem :>> ", depItem);
          if (depItem) {
            _pricelistid = Number(depItem.pricelistid);
          }
        }
        console.log("_pricelistid :>> ", _pricelistid, row.formulakind);

        console.log("state.mtrltypeTabList :>> ", state.mtrltypeTabList);

        let _mtrltypeItem = state.mtrltypeTabList.find(t => t.formulakinds.includes(Number(row.formulakind)));
        !_mtrltypeItem && (_mtrltypeItem = { value: -1 });

        let params = {
          mtrltype: _mtrltypeItem.value,
          pricelistid: _pricelistid
        };

        return (
          <>
            <MtrldefSelect
              value={row.mtrlid}
              {...params}
              clearable
              placeholder={_label}
              onOpenModal={() => fModelChoseMtrl(row, params, _mtrltypeItem.label)}
              onSelect={(val: any) => rModelSetMtrl(row, val)}
              onClear={() => rModelClearMtrl(row)}
            />
          </>
        );
      }
    },
    {
      title: "数量/长度",
      field: "qty",
      datatype: "number",
      editRender: {
        name: "input"
      }
    },
    {
      title: "ERP物料编码",
      field: "erp_mtrlcode"
    },
    {
      title: "ERP物料名称",
      field: "erp_mtrlname"
    },
    {
      title: "用量分子",
      field: "usenum",
      datatype: "number",
      editRender: {
        name: "input"
      }
    },
    {
      title: "用量分母",
      field: "usedenom",
      datatype: "number",
      editRender: {
        name: "input"
      }
    }
  ];

  /**
   * @description 明细，新增
   */
  const funcAddMtrlMx = async (data: any) => {
    console.log("state.LjDetail. :>> ", state.LjDetailRef);
    console.log("funcAddMtrlMx data :>> ", data);
    let { tabsActive } = state.LjDetailRef;
    let { row, rowIndex, visibleData } = data;
    let nextRow = visibleData[rowIndex + 1];
    if (!nextRow) {
      nextRow = visibleData[visibleData.length - 1];
    }

    const $table = state.VxeTableMxRef.element;
    if ($table) {
      const records = {
        addmx: "+",
        delmx: "-",
        formulatype: row.formulatype,
        if_mtrl: row.if_mtrl,
        formulaid: row.formulaid,
        sortcode: row.sortcode,
        formulakind: row.formulakind,
        formula: row.formula,
        thickness: 0,
        mtrlid: 0,
        qty: 1,
        usedenom: 1
      };

      const { row: newRow } = await $table.insertAt(records, nextRow);
      await $table.setEditCell(newRow, "mtrlname");
      await $table.setCurrentRow(newRow);
    }
  };

  /**
   * @description 明细，删除
   */
  const funcDelMtrlMx = (data: any) => {
    let { row } = data;
    let { tabsActive } = state.LjDetailRef;

    const $table = state.VxeTableMxRef.element;
    if ($table) {
      $table.remove(row);
    }
  };

  const getFormulakindEnum = async () => {
    let _params = {
      dsname: "_Mapper_formulakind",
      queryparams: {}
    };
    let res = await CommonDynamicSelect(_params);
    let result = [];
    if (res?.datatable?.length > 0) {
      result = res?.datatable;
    }

    state.formulaKindEnum = result;
  };

  /**
   * @description 弹窗模块：客户选择
   * @param data 当前数据
   * @param status 当前订单状态
   * @returns Promise
   */
  const fModelChoseMtrl = (data: any, params: any, label?: string) => {
    return new Promise((resolve, reject) => {
      // if (!ALLOW_EDIT_STATE.includes(status)) return;

      let _params = {
        keyword: "",
        arg_mtrltype: params.mtrltype,
        arg_pricelistid: params.pricelistid
      };
      state.MtrldefDialogProps = {
        onSubmit: (res: any) => {
          // submit
          console.log("openCustDialog res", res);
          nextTick(() => {
            rModelSetMtrl(data, res.value[0]);
            resolve(1);
          });
        },
        onCancel: (error: any) => {
          // cancel 回调
          console.log("openCustDialog error", error);
        }
      };
      state.MtrldefDialogRef.show(_params, label);
    });
  };

  /**
   * @description 数据赋值：物料信息
   * @param data 当前数据
   * @param item 当前选择的数据
   */
  const rModelSetMtrl = (data: any, item: any) => {
    console.log("rModelSetMtrl data :>> ", data);
    console.log("rModelSetMtrl item :>> ", item);
    if (item) {
      data.billid = state.LjDetailRef._mainData.billid;
      data.printid = 0;
      data.mtrlid = item.mtrlid;
      data.price = item.pricelistprice;
      data.gram_weight = item.gram_weight;
      data.cloth_width = item.cloth_width;
      data.if_inputqty = Number(item.if_inputqty);
      data.if_areaprice = item.if_areaprice;
      data.mtrlname = item.mtrlname;
      data.priceunit = item.priceunit;
      data.shrinkage = item.price;
      Number(item.thickness) > 0 && (data.thickness = item.thickness);
      data.price_formula = item.price_formula;
    }
  };

  const rModelClearMtrl = (data: any) => {
    console.log("rModelClearMtrl data :>> ", data);
    data.billid = state.LjDetailRef._mainData.billid;
    data.printid = 0;
    data.mtrlid = 0;
    data.price = 0;
    data.gram_weight = 0;
    data.cloth_width = 0;
    data.if_inputqty = 0;
    data.if_areaprice = 0;
    data.mtrlname = "";
    data.priceunit = "";
    data.shrinkage = 0;
    data.thickness = 0;
    data.price_formula = "";
    data.qty = "";
  };

  /**
   * @description 重新获取明细数据
   * @author w_mattress_add wf_import_dw_2
   */
  const funcImportMx = async () => {
    let newMxData: any = [];
    const { _mainData, enumMap } = state.LjDetailRef;

    // 0 -导入通用类型的公式
    let _param_mf = {
      dsname: "web_mattress_formulalist",
      queryparams: {
        arrg_usetype: 0,
        arg_array_formulatype: sys_arry_formulatype
      }
    };
    let res_mf = await CommonDynamicSelect(_param_mf);
    if (res_mf?.datatable?.length) {
      res_mf?.datatable.map((item: any) => {
        if (![11, 12, 32, 33, 13, 14, 29, 999, 1201].includes(item.formulakind)) {
          // 非垫层
          let _data: any = {};
          if (Number(item.if_mtrl) > 1) {
            _data.addmx = "+";
            _data.delmx = "-";
          }
          _data.formulatype = item.formulatype;
          _data.if_mtrl = item.if_mtrl;
          _data.formulaid = item.formulaid;
          _data.sortcode = item.sortcode;
          _data.formulakind = item.formulakind;
          _data.formula = item.formula;
          _data.useformula = item.useformula;
          _data.gydscrp = item.gydscrp;
          _data.qty = 1;
          _data.usedenom = 1;

          newMxData.push(_data);
        }
      });
    }
    console.log("newMxData 0:>> ", newMxData);

    // 1
    _param_mf.queryparams.arrg_usetype = 1;
    res_mf = await CommonDynamicSelect(_param_mf);

    let notBcpFormulakinds = state.fabricMxTabList
      .filter(t => t.name != "tabpage_13")
      .flatMap(t => t.type)
      .filter(t => t < 9000);

    let tabpage_8 = state.fabricMxTabList.find(t => t.name == "tabpage_8");
    let tabpage_9 = state.fabricMxTabList.find(t => t.name == "tabpage_9");
    let tabpage_10 = state.fabricMxTabList.find(t => t.name == "tabpage_10");
    let tabpage_11 = state.fabricMxTabList.find(t => t.name == "tabpage_11");
    let tabpage_12 = state.fabricMxTabList.find(t => t.name == "tabpage_12");

    if (res_mf?.datatable?.length) {
      res_mf?.datatable.map((item: any) => {
        let ls_chastr = "";
        console.log("web_mattress_formulalist _mainData, item :>> ", _mainData, item, Number(_mainData.if_bcp_type));
        // 半成品
        if (Number(_mainData.if_bcp_type) == 1 && notBcpFormulakinds.includes(item.formulakind)) {
          return;
        }

        let _formulakind = Number(item.formulakind);

        if (tabpage_8.type.includes(_formulakind)) {
          ls_chastr = "面裥绵";
        }
        if (tabpage_9.type.includes(_formulakind)) {
          ls_chastr = "底裥绵";
        }
        if (tabpage_10.type.includes(_formulakind)) {
          ls_chastr = "普通大侧";
        }
        if (tabpage_11.type.includes(_formulakind)) {
          ls_chastr = "小侧1";
        }
        if (tabpage_12.type.includes(_formulakind)) {
          ls_chastr = "V侧1";
        }

        let _data: any = {};
        if (Number(item.if_mtrl) > 1) {
          _data.addmx = "+";
          _data.delmx = "-";
        }
        _data.formulatype = item.formulatype;
        _data.if_mtrl = item.if_mtrl;
        _data.formulaid = item.formulaid;
        _data.sortcode = item.sortcode;
        _data.formulakind = item.formulakind;
        _data.formula = item.formula;
        _data.chastr = ls_chastr;
        _data.useformula = item.useformula;
        _data.gydscrp = item.gydscrp;
        _data.qty = 1;
        _data.usedenom = 1;

        newMxData.push(_data);
      });
    }
    console.log("newMxData 1:>> ", newMxData);

    newMxData.sort((a: any, b: any) => {
      if (a.formulatype != b.formulatype) {
        return a.formulatype - b.formulatype;
      }
      if (a.xu != b.xu) {
        return a.xu - b.xu;
      }
      if (a.sortcode != b.sortcode) {
        return a.sortcode - b.sortcode;
      }
      return a.formulaid - b.formulaid;
    });

    state.oriMxData.list = newMxData;

    funcChaifenTab();
  };

  const funcChaifenTab = async () => {
    const { _mainData } = state.LjDetailRef;
    // 面料
    state.fabricMxData = state.oriMxData.list.filter(t => t.formulatype == "0");
    const billtype = Number(_mainData.semi_finished_type);
    let _mx = state.fabricMxTabList.find(t => t.billtype === billtype);
    state.fabricMxTab = state.fabricMxData.filter(t => _mx.type.includes(Number(t.formulakind)));
  };

  /**
   * @description 面料-裥大、小侧，增加物料
   */
  const funcAddMxSide = async (params: any, data: any, targetRef?: any) => {
    // arg_array_formulakind
    let newParams: any = {};
    newParams.queryParams = params;
    newParams.dsname = "web_mattress_formulalist";
    let res = await CommonDynamicSelect(newParams);
    console.log("funcAddBigSide res :>> ", res);

    if (res.datatable) {
      if (targetRef) {
        const $table = targetRef.element;
        if ($table) {
          res.datatable.map(itm => {
            let records: any = {
              formulatype: itm.formulatype,
              if_mtrl: Number(itm.if_mtrl),
              formulaid: itm.formulaid,
              sortcode: data.label,
              chastr: data.label,
              formulakind: Number(itm.formulakind),
              formula: itm.formula,
              useformula: itm.useformula,
              gydscrp: itm.gydscrp
            };

            if (records.if_mtrl > 1) {
              records.addmx = "+";
              records.delmx = "-";
            }

            $table.insertAt(records, -1);
          });
        }
      } else {
        let arr = [];
        res.datatable.map(itm => {
          let records: any = {
            formulatype: itm.formulatype,
            if_mtrl: Number(itm.if_mtrl),
            formulaid: itm.formulaid,
            sortcode: data.label,
            chastr: data.label,
            formulakind: Number(itm.formulakind),
            formula: itm.formula,
            useformula: itm.useformula,
            gydscrp: itm.gydscrp
          };

          if (records.if_mtrl > 1) {
            records.addmx = "+";
            records.delmx = "-";
          }

          arr.push(records);
        });
        return arr;
      }
    } else {
      return [];
    }
  };

  return {
    ...toRefs(state),
    columns,
    columnsMx,
    getFormulakindEnum,
    funcChaifenTab
  };
};
