import { ref, reactive, computed, toRefs, nextTick } from "vue";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { GetSoftBedMxList, SaveSoftBedQuote, GetSoftBedConfigureList } from "@/api/modules/quote";
import { ALLOW_EDIT_STATE } from "@/config/index";
import { ElButton, ElMessage, ElMessageBox, ElRow, ElCol, ElNotification } from "element-plus";
import { AuditSoftBedQuote, DeleteSoftBedQuote } from "@/api/modules/quote";
import { getDeptList } from "@/api/modules/saleprice";
import { CommonDynamicSelect } from "@/api/modules/common";
import SoftBedSelect from "@/views/system/selector/softbedTemplate/select.vue";
import { cloneDeep } from "lodash-es";
import { getCurrentRecords } from "@/utils/index";
import MtrldefErpSelect from "@/views/system/selector/mtrldefErp/select.vue";
interface defaultState {
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 列表Ref
   */
  VxeTableRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRef: any;
  /**
   * @description 详情页明细表格Ref
   */
  VxeTableHeadBoardMxRef: any;
  /**
   * @description 详情页明细表格Ref
   */
  VxeTableNightStandMxRef: any;
  /**
   * @description 详情页明细表格Ref
   */
  VxeTableBedFrameMxRef: any;
  /**
   *
   */
  initParams: any;
  /**
   * @description 详情页主表数据
   */
  softBed: any;
  /**
   * @description 详情页主表明细数据
   */
  softBedMx: any[];
  /**
   * @description 详情页主表明细数据-床头
   */
  headBoardMx: any[];
  /**
   * @description 详情页主表明细数据-床头柜
   */
  nightStandMx: any[];
  /**
   * @description 详情页主表明细数据-床架
   */
  bedFrameMx: any[];
  /**
   * @description 详情页模板报价弹窗对象
   */
  SoftBedTemplateDialogRef: any;
  /**
   * @description 详情页模板报价弹窗入参
   */
  SoftBedTemplateDialogProps: any;
  /**
   * @description 详情页部件配置选择弹窗
   */
  isModalVisible: boolean;
  /**
   * @description 详情页部件配置选择弹窗
   */
  showHeadboard: boolean;
  /**
   * @description 详情页部件配置选择弹窗
   */
  showNightstand: boolean;
  /**
   * @description 详情页部件配置选择弹窗
   */
  showBedframe: boolean;
  partsConfig: any;
  headboardConfigOptions: any[];
  nightstandConfigOptions: any[];
  bedframeConfigOptions: any[];
  configValueOptionsMap: any;
  MtrldefDialogRef: any;
  MtrldefDialogProps: any;
}

/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  const state = reactive<defaultState>({
    orderStatus: "",
    VxeTableRef: null,
    LjDetailRef: null,
    VxeTableHeadBoardMxRef: null,
    VxeTableBedFrameMxRef: null,
    VxeTableNightStandMxRef: null,
    softBed: {},
    softBedMx: [],
    headBoardMx: [],
    nightStandMx: [],
    bedFrameMx: [],
    SoftBedTemplateDialogRef: null,
    SoftBedTemplateDialogProps: null,
    isModalVisible: false,
    showHeadboard: false,
    showNightstand: false,
    showBedframe: false,
    initParams: { arg_softbed_id: 0 },
    partsConfig: {
      headboard: [],
      nightstand: [],
      bedframe: []
    },
    headboardConfigOptions: [],
    nightstandConfigOptions: [],
    bedframeConfigOptions: [],
    configValueOptionsMap: {},
    MtrldefDialogRef: null,
    MtrldefDialogProps: {}
  });
  // 表格配置项
  const columns: ColumnProps<any>[] = [
    { type: "checkbox", width: 40, fixed: "left" },
    {
      field: "pid",
      title: "序",
      width: 40,
      basicinfo: {
        span: 1,
        row: 1
      }
    },
    {
      field: "softbed_code",
      title: "报价唯一码",
      basicinfo: {
        span: 1,
        row: 1,
        order: 1,
        group: "单据信息"
      }
    },
    {
      field: "deptid",
      title: "部门",
      enum: () =>
        getDeptList({}).then(res => {
          return res.datatable.map(t => {
            return { ...t, label: t.deptname, value: t.deptid };
          });
        }),
      // fieldNames: { label: "deptname", value: "deptid" },
      search: {
        el: "select",
        key: "arg_deptid",
        props: {
          filterable: true,
          onChange: val => {
            state.initParams.arg_deptid = val;
          }
        },
        order: 1
      },
      basicinfo: {
        el: "select",
        span: 1,
        row: 1,
        order: 1,
        group: "单据信息",
        editable: (scope: any) => {
          if (ALLOW_EDIT_STATE.includes(scope.status) && Number(scope.searchParam.softbed_id) <= 0) {
            return true;
          }
          return false;
        },
        rules: [{ required: true, message: "请先选择部门", trigger: "change" }],
        props: {
          filterable: true,
          clearable: false,
          onChange: val => {
            wf_get_moneyrate_discount(val);
          }
        }
      }
    },
    {
      field: "is_template",
      title: "模板报价",
      datatype: "checkbox",
      basicinfo: {
        el: "checkbox",
        props: {
          trueValue: 1,
          falseValue: 0
        },
        span: 1,
        row: 1,
        order: 2,
        group: "单据信息"
      }
    },
    {
      field: "create_date",
      title: "报价日期",
      format: "yyyy-MM-dd HH:mm",
      basicinfo: {
        span: 1,
        row: 1,
        order: 3,
        group: "单据信息"
      }
    },
    {
      field: "template_code",
      title: "模板编号",
      basicinfo: {
        el: "select",
        span: 1,
        row: 1,
        order: 4,
        group: "单据信息",
        render: (scope: any) => {
          const { column, searchParam: row, status } = scope;
          let params = {
            arg_template_id: row.template_id
          };
          let _disabled = !(ALLOW_EDIT_STATE.includes(state.orderStatus) && !Number(scope.searchParam.is_template));
          return (
            <>
              <SoftBedSelect
                value={row.template_code}
                {...params}
                clearable
                disabled={_disabled}
                placeholder={row.template_code}
                onOpenModal={() => fModelChoseTemplate(row, params)}
                onSelect={(val: any) => rModelSetTemplate(row, val)}
                onClear={() => rModelClearTemplate(row)}
              >
                {{
                  label: () => row.template_code
                }}
              </SoftBedSelect>
            </>
          );
        }
      }
    },
    {
      field: "softbed_name",
      title: "报价名称",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        span: 1,
        row: 1,
        order: 5,
        group: "单据信息"
      }
    },
    {
      field: "template_name",
      title: "模板名称",
      basicinfo: {
        el: "input",
        span: 1,
        row: 1,
        order: 6,
        group: "单据信息",
        editable: (scope: any) => {
          if (ALLOW_EDIT_STATE.includes(scope.status) && !Number(scope.searchParam.is_template)) {
            return true;
          }
          return false;
        }
      }
    },
    {
      field: "softbed_relcode",
      title: "报价编码",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        span: 1,
        row: 1,
        order: 7,
        group: "单据信息"
      }
    },
    {
      field: "mtrlmode",
      title: "物料规格",
      basicinfo: {
        span: 1,
        row: 1,
        order: 8,
        group: "单据信息"
      }
    },
    {
      field: "create_emp",
      title: "报价人",
      basicinfo: {
        span: 1,
        row: 1,
        order: 9,
        group: "单据信息"
      }
    },
    {
      field: "mtrltype",
      title: "物料类别",
      basicinfo: {
        span: 1,
        row: 1,
        order: 10,
        group: "单据信息"
      }
    },
    {
      field: "has_type",
      title: "类型",
      visible: false,
      basicinfo: {
        span: 2,
        row: 1,
        order: 10,
        group: "单据信息",
        labelHidden: true,
        render: (scope: any) => {
          let _disabled = !ALLOW_EDIT_STATE.includes(state.orderStatus);
          let _type = _disabled ? "info" : "primary";
          return (
            <>
              <ElRow>
                <ElCol span={16}>
                  <el-checkbox
                    v-model={scope.searchParam.has_headboard}
                    true-value={1}
                    false-value={0}
                    disabled={_disabled}
                    label="床头"
                    class="mr-8"
                    // onChange={val => autoLoadExtraData_chai(val, "if_m_chai")}
                  />
                  <el-checkbox
                    v-model={scope.searchParam.has_nightstand}
                    true-value={1}
                    false-value={0}
                    disabled={_disabled}
                    label="床头柜"
                    class="mr-8"
                    // onChange={val => autoLoadExtraData_chai(val, "if_z_chai")}
                  />
                  <el-checkbox
                    v-model={scope.searchParam.has_bedframe}
                    true-value={1}
                    false-value={0}
                    disabled={_disabled}
                    label="床架"
                    // onChange={val => autoLoadExtraData_chai(val, "if_d_chai")}
                  />
                </ElCol>
                <ElCol span={8}>
                  <ElButton type={_type} size="small" disabled={_disabled} onClick={onOpenConfigureDialog}>
                    选择部件配置
                  </ElButton>
                </ElCol>
              </ElRow>
            </>
          );
        }
      }
    },
    {
      field: "has_headboard",
      width: 44,
      align: "center",
      title: "床头",
      basicinfo: {
        span: 1,
        row: 1,
        order: 10,
        group: "单据信息",
        visible: false
      }
    },
    {
      field: "has_nightstand",
      width: 58,
      align: "center",
      title: "床头柜",
      basicinfo: {
        span: 1,
        row: 1,
        order: 11,
        group: "单据信息",
        visible: false
      }
    },
    {
      field: "has_bedframe",
      basicinfo: {
        span: 1,
        row: 1,
        order: 12,
        group: "单据信息",
        visible: false
      },
      width: 44,
      align: "center",
      title: "床架"
    },
    {
      field: "other_rate",
      format: "cutNumber",
      basicinfo: {
        el: "input-number",
        span: 1,
        row: 1,
        order: 19,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE
      },
      title: "额外点数"
    },
    {
      field: "taxes",
      title: "税金",
      format: "cutNumber",
      enum: [
        {
          label: "不含税",
          value: 1
        },
        {
          label: "含税",
          value: 1.07
        }
      ],
      basicinfo: {
        el: "select",
        span: 1,
        row: 1,
        order: 20,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE,
        render: (scope: any) => {
          let optionRender = [];
          let _disabled = !ALLOW_EDIT_STATE.includes(scope.status);
          scope.enum.map(item => {
            optionRender.push(<el-option label={item.label} value={item.value} />);
          });
          let slotprefix = {
            prefix: () => {
              return <>{scope.searchParam.taxrate}</>;
            }
          };

          let _taxrate = Number(scope.searchParam.taxrate);
          return (
            <el-select
              v-model={_taxrate}
              v-slots={slotprefix}
              class="select-text-right"
              disabled={_disabled}
              onChange={val => funcTaxrateChange(val, scope.searchParam)}
            >
              {optionRender}
            </el-select>
          );
        }
      }
    },
    {
      field: "extras_cost",
      format: "cutNumber",
      basicinfo: {
        el: "input-number",
        span: 1,
        row: 1,
        order: 21,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE
      },
      title: "额外费用"
    },
    {
      field: "moneyrate",
      title: "币种",
      enum: () => {
        return GetMoneyRateMapper().then(res => {
          return res.datatable;
        });
      },
      render: (scope: any) => {
        return (
          <>
            <div class="flx-justify-between">
              <span>
                <>{scope.row.moneyrate > 1 ? `美元` : "人民币"}</>
              </span>
              {scope.row.moneyrate > 1 && (
                <span>
                  <>{scope.row.moneyrate}</>
                </span>
              )}
            </div>
          </>
        );
      },
      basicinfo: {
        el: "select",
        span: 1,
        row: 1,
        order: 22,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE,
        render: (scope: any) => {
          let optionRender = [];
          let _disabled = !ALLOW_EDIT_STATE.includes(scope.status);
          scope.enum.map(item => {
            optionRender.push(<el-option label={item.label} value={item.value} />);
          });
          let slotprefix = {
            prefix: () => {
              return <>{scope.searchParam.moneyrate}</>;
            }
          };

          return (
            <el-select
              v-model={scope.searchParam.money_type}
              v-slots={slotprefix}
              class="select-text-right"
              disabled={_disabled}
              onChange={val => wf_get_moneyrate_discount(val)}
            >
              {optionRender}
            </el-select>
          );
        }
      }
    },
    {
      field: "commission",
      format: "cutNumber",
      basicinfo: {
        el: "input-number",
        span: 1,
        row: 1,
        order: 23,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE
      },
      title: "佣金"
    },
    {
      field: "dscrp",
      title: "备注",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        span: 1,
        row: 1,
        order: 24,
        group: "费用信息",
        props: {
          type: "textarea"
        }
      }
    },
    {
      field: "foreign_cost",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 25,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "外币价"
    },
    {
      field: "nottax_dept_cost",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 26,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "部门售价(不含税)"
    },
    {
      field: "dept_cost",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 27,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "部门含税价"
    },
    {
      field: "nottax_factory_cost",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 28,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "不含税出厂价"
    },
    {
      field: "costamt",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 29,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "报价金额"
    },
    {
      field: "bi_nottax_dept_cost",
      basicinfo: {
        span: 1,
        row: 1,
        order: 31,
        group: "成本信息",
        visible: true,
        ishidden: false
      },
      title: "财务底价"
    },
    {
      field: "total_material_cost",
      basicinfo: {
        span: 1,
        row: 1,
        order: 32,
        group: "成本信息",
        visible: true,
        ishidden: false
      },
      title: "总材料成本"
    },
    {
      field: "total_hr_cost",
      basicinfo: {
        span: 1,
        row: 1,
        order: 33,
        group: "成本信息",
        visible: true,
        ishidden: false
      },
      title: "总人力成本"
    },
    {
      field: "total_cost",
      basicinfo: {
        span: 1,
        row: 1,
        order: 34,
        group: "成本信息",
        visible: true,
        ishidden: false
      },
      title: "总成本"
    },
    {
      field: "flag",
      basicinfo: {
        span: 1,
        row: 1,
        order: 30,
        group: "其他",
        visible: true,
        ishidden: false
      },
      width: 44,
      align: "center",
      datatype: "checkbox",
      title: "审核"
    },
    {
      field: "audit_date",
      format: "yyyy-MM-dd HH:mm",
      width: 160,
      basicinfo: {
        span: 1,
        row: 1,
        order: 31,
        group: "其他",
        visible: true,
        ishidden: false
      },
      title: "审核日期",
      colorder: 26
    },
    {
      field: "audit_emp",
      basicinfo: {
        span: 1,
        row: 1,
        order: 32,
        group: "其他",
        visible: true,
        ishidden: false
      },
      title: "审核人"
    },
    {
      field: "update_date",
      format: "yyyy-MM-dd HH:mm",
      width: 160,
      basicinfo: {
        span: 1,
        row: 1,
        order: 33,
        group: "其他",
        visible: true,
        ishidden: false
      },
      title: "更新日期"
    },
    {
      field: "update_emp",
      basicinfo: {
        span: 1,
        row: 1,
        order: 34,
        group: "其他",
        visible: true,
        ishidden: false
      },
      title: "更新人"
    }
  ];
  // 明细表格配置项
  const columnsMx: ColumnProps<any>[] = [
    {
      field: "printid",
      title: "行号",
      width: 50
    },
    {
      field: "allow_edit",
      title: "业务修改",
      width: 80,
      align: "center",
      datatype: "checkbox",
      editRender: {},
      editColRender: (scope: any) => {
        const { column, row, status } = scope;
        if (Number(row.allow_edit) == 0) {
          row.allow_edit = 0;
        }

        return (
          <>
            <el-checkbox v-model={row.allow_edit} true-value={1} false-value={0} class="vxe-edit-col-middle"></el-checkbox>
          </>
        );
      }
    },
    {
      field: "pzname",
      title: "部件选配项",
      visible: false
    },
    {
      field: "pznamemx",
      title: "部件选配项值",
      editRender: {},
      editColRender: (scope: any) => {
        const { row } = scope;
        const { _mainData } = state.LjDetailRef;
        const _disabled = !row.allow_edit && !_mainData.is_template;

        const partTypes = {
          1: "headboardConfigOptions",
          2: "nightstandConfigOptions",
          8: "bedframeConfigOptions"
        };
        const targetArray = partTypes[row.has_type] || "headboardConfigOptions";

        const options = state[targetArray]?.map(item => <el-option key={item.pzid} label={item.pzname} value={item} />) || [];

        return (
          <el-select v-model={row.pzid} disabled={_disabled} valueKey={"pzid"} clearable={true}>
            {options}
          </el-select>
        );
      }
    },
    {
      field: "mtrlcode",
      title: "物料编码"
    },
    {
      field: "mtrlname",
      title: "物料名称规格",
      width: 400,
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        let field = column.field;
        let _label = column.title;
        let params = {
          keyword: row.mtrlcode
        };

        return (
          <MtrldefErpSelect
            value={row.mtrlid}
            {...params}
            clearable
            placeholder={_label}
            onOpenModal={() => fModelChoseMtrlErp(row, params)}
            onSelect={val => rModelSetMtrlErp(row, val)}
            onClear={() => rModelClearMtrlErp(row)}
          >
            {{
              label: () => `${row.mtrlname} ${row.mtrlmode}`
            }}
          </MtrldefErpSelect>
        );
      }
    },
    {
      field: "unit",
      title: "物料单位"
    },
    {
      field: "cutting_length",
      title: "下料长(mm)",
      datatype: "number",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        const { _mainData } = state.LjDetailRef;

        let _disabled = !Boolean(row.allow_edit) && !Boolean(_mainData.is_template);
        return <el-input v-model={scope.row.cutting_length} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "cutting_width",
      title: "下料宽(mm)",
      datatype: "number",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        const { _mainData } = state.LjDetailRef;

        let _disabled = !Boolean(row.allow_edit) && !Boolean(_mainData.is_template);
        return <el-input v-model={scope.row.cutting_width} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "cutting_qty",
      title: "下料数量",
      datatype: "number",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        const { _mainData } = state.LjDetailRef;

        let _disabled = !Boolean(row.allow_edit) && !Boolean(_mainData.is_template);
        return <el-input v-model={scope.row.cutting_qty} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "useqty",
      title: "理论用料量",
      datatype: "number"
    },
    {
      field: "use_formula",
      title: "用料量公式"
    },
    {
      field: "use_formula_str",
      title: "用料量文本公式"
    },
    {
      field: "actual_useqty",
      title: "实际用量",
      datatype: "number"
    },
    {
      field: "loss_rate",
      title: "损耗率",
      datatype: "number",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        const { _mainData } = state.LjDetailRef;

        let _disabled = !Boolean(row.allow_edit) && !Boolean(_mainData.is_template);
        return <el-input v-model={scope.row.loss_rate} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "price",
      title: "材料单价",
      datatype: "number",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        const { _mainData } = state.LjDetailRef;

        let _disabled = !Boolean(row.allow_edit) && !Boolean(_mainData.is_template);
        return <el-input v-model={scope.row.loss_rate} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "price_formula",
      title: "单价公式"
    },
    {
      field: "price_formula_str",
      title: "单价文本公式"
    },
    {
      field: "cost_price",
      title: "成本单价",
      datatype: "number"
    },
    {
      field: "cost_amt",
      title: "成本金额",
      datatype: "number"
    }
  ];
  /**
   * 详细页获取数据
   */
  const detail_getData = async (params: any) => {
    const result = await GetSoftBedMxList(params);
    if (state.orderStatus === "new") {
      result.softbed.taxrate = 1;
    }

    state.softBed = [result.softbed];
    state.softBedMx = result.mxList;
    state.headBoardMx = result.mxList.filter(item => item.has_type === 1);
    state.nightStandMx = result.mxList.filter(item => item.has_type === 2);
    state.bedFrameMx = result.mxList.filter(item => item.has_type === 4);
  };
  /**
   * 打开部件配置弹窗
   */
  const onOpenConfigureDialog = async () => {
    const { _mainData } = state.LjDetailRef;
    const result = await GetSoftBedConfigureList({ softbed: _mainData });

    state.nightstandConfigOptions = [];
    state.bedframeConfigOptions = [];
    state.headboardConfigOptions = [];

    if (result.typeList?.length > 0) {
      for (const item of result.typeList) {
        if (item.contfigtypename.includes("床头柜")) {
          handleConfigItem(item, state.nightstandConfigOptions);
        } else if (item.contfigtypename.includes("床架")) {
          handleConfigItem(item, state.bedframeConfigOptions);
        } else if (item.contfigtypename.includes("床头")) {
          handleConfigItem(item, state.headboardConfigOptions);
        }
      }
    }

    nextTick(() => {
      state.showHeadboard = Boolean(_mainData.has_headboard);
      state.showNightstand = Boolean(_mainData.has_nightstand);
      state.showBedframe = Boolean(_mainData.has_bedframe);
      state.isModalVisible = true;
    });
  };
  const handleConfigItem = (item: any, targetArray: any[]) => {
    if (item.codeList?.length > 0) {
      for (const code of item.codeList) {
        targetArray.push({ pzid: code.pzid, pzname: code.name });
        if (code.pzid && code.pzid > 0) {
          state.configValueOptionsMap[code.pzid] = [];
          if (code.codeMxList?.length > 0) {
            state.configValueOptionsMap[code.pzid].push(...code.codeMxList.filter(t => t.pzid === code.pzid));
          }
        }
      }
    }
  };
  /**
   * 确认部件配置项值
   * @param params 返回内容
   */
  const onConfirmConfigureDialog = (params: any) => {
    const { _mainData } = state.LjDetailRef;

    console.log("partsConfig :>>> ", state.partsConfig);
    nextTick(() => {
      _mainData.has_headboard = Number(state.showHeadboard);
      _mainData.has_nightstand = Number(state.showNightstand);
      _mainData.has_bedframe = Number(state.showBedframe);

      state.isModalVisible = false;
    });
  };
  /**
   * 保存报价
   */
  const onSave = async cb => {
    const { _mainData } = state.LjDetailRef;
    const headboard_table = state.VxeTableHeadBoardMxRef.element.getTableData();
    const nightstand_table = state.VxeTableNightStandMxRef.element.getTableData();
    const bedframe_table = state.VxeTableBedFrameMxRef.element.getTableData();

    const _softbed = cloneDeep(_mainData);
    const _mxList = [];
    _softbed.mxList = _mxList;

    if (headboard_table && headboard_table.length > 0) _mxList.push(headboard_table);
    if (nightstand_table && nightstand_table.length > 0) _mxList.push(nightstand_table);
    if (bedframe_table && bedframe_table.length > 0) _mxList.push(bedframe_table);

    transformData(_softbed);

    const params: any = {
      softbed: _softbed
    };

    try {
      await SaveSoftBedQuote(params)
        .then((res: any) => {
          ElNotification({
            title: "温馨提示",
            message: t("sys.api.sueccessToSave"),
            type: "success"
          });

          cb && cb(res);
        })
        .catch(error => {
          console.log("error !! :>> ", error);
        });
    } catch (error) {
      ElMessage.error(t("sys.api.operationFailed"));
    }
  };

  const transformData = (data: any) => {
    for (let key in data) {
      if (typeof data[key] === "boolean") data[key] = Number(data[key]);
    }
  };
  /**
   * 审核报价
   */
  const onAudit = (list: any) => {
    ElMessageBox.confirm("是否确定要审核单据吗?", "询问", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        AuditSoftBedQuote({ list, type: 1 }).then(() => {
          ElMessage.success(t("sys.api.operationSuccess"));
          state.VxeTableRef.refresh();
        });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };
  /**
   * 撤审报价
   */
  const onCAudit = (list: any) => {
    ElMessageBox.confirm("是否确定要撤审单据吗?", "询问", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        AuditSoftBedQuote({ list, type: 0 }).then(() => {
          ElMessage.success(t("sys.api.operationSuccess"));
          state.VxeTableRef.refresh();
        });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };
  /**
   * 删除报价
   */
  const onDelete = (list: any, cb?: Function) => {
    ElMessageBox.confirm(`是否确定要删除${list.length}张报价单吗?`, "询问", {
      confirmButtonText: t("common.delText"),
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        DeleteSoftBedQuote({ list }).then(() => {
          ElMessage.success(t("sys.api.operationSuccess"));
          cb && cb();
          state.VxeTableRef.refresh();
        });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };
  /**
   * 复制报价
   */
  const onCopyQuote = () => {};
  /**
   * 显示公式
   */
  const onShowFormula = () => {};

  const GetMoneyRateMapper = async () => {
    return CommonDynamicSelect({ dsname: "_Mapper_if_moneyrate", queryparams: {} });
  };
  /**
   * @description 获取部门汇率 和  折扣率
   */
  const wf_get_moneyrate_discount = (val: any) => {
    const { _mainData, enumMap } = state.LjDetailRef;

    let deptEnum = enumMap.get("deptid");
    console.log("deptEnum :>> ", deptEnum);
    if (deptEnum) {
      let depItem = deptEnum.find((item: any) => item.deptid == _mainData.deptid);
      if (depItem) {
        let _moneyrate = !depItem.moneyrate || Number(depItem.moneyrate) == 0 ? 1 : depItem.moneyrate;
        if (val == 0 || !_mainData.money_type) {
          _mainData.money_type = 0;
          _mainData.moneyrate = 1;
        } else {
          _mainData.moneyrate = _moneyrate;
        }
        _mainData.discount = depItem.discount;
      }
    }
  };

  const funcTaxrateChange = async (val: any, data) => {
    data.taxrate = val;
  };

  /**
   * @description 弹窗模块：客户选择
   * @param data 当前数据
   * @param status 当前订单状态
   * @returns Promise
   */
  const fModelChoseTemplate = (data: any, params: any) => {
    return new Promise((resolve, reject) => {
      let _params = {
        arg_search: ""
      };
      state.SoftBedTemplateDialogProps = {
        onSubmit: (res: any) => {
          // submit
          nextTick(() => {
            rModelSetTemplate(data, res.value[0]);
            resolve(1);
          });
        },
        onCancel: (error: any) => {
          // cancel 回调
        }
      };
      state.SoftBedTemplateDialogRef.show(_params);
    });
  };
  /**
   * @description 数据赋值: 联系人
   * @param data 当前数据
   * @param item 当前选择的数据
   */
  const rModelSetTemplate = (data: any, item: any) => {
    data.template_id = Number(item.softbed_id);
    data.template_code = item.softbed_code;
    data.template_name = item.softbed_name;
  };
  /**
   * 清空选择参数
   * @param data
   */
  const rModelClearTemplate = (data: any) => {
    data.template_id = 0;
    data.template_code = "";
    data.template_name = "";
  };

  const toAddMx = async (tableRef: any) => {
    const { _mainData } = state.LjDetailRef;
    const $table = tableRef.element;
    if ($table) {
      // 新增
      const records = {
        softbed_id: _mainData.softbed_id,
        has_type: getHasType(tableRef),
        mtrlname: "",
        mtrlcode: "",
        mtrlmode: "",
        unit: "",
        allow_edit: 0,
        cutting_length: 0,
        cutting_width: 0,
        cutting_qty: 0,
        loss_rate: 0,
        price: 0
      };
      const { row } = await $table.insertAt(records, -1);
      await $table.setCurrentRow(row);
      await $table.setEditRow(row);
    }
  };

  const toDelMx = (tableRef: any) => {
    const { $table } = getCurrentRecords(tableRef);
    ElMessageBox.confirm(`是否确定要删除明细吗?`, "询问", {
      confirmButtonText: t("common.delText"),
      cancelButtonText: "否",
      type: "error"
    })
      .then(() => {
        $table.removeCurrentRow();
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };

  const getHasType = (tableRef: any) => {
    return tableRef === state.VxeTableHeadBoardMxRef ? 1 : tableRef === state.VxeTableNightStandMxRef ? 2 : 4;
  };

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

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

  /**
   * @description 数据赋值: 联系人
   * @param data 当前数据
   * @param item 当前选择的数据
   */
  const rModelSetMtrlErp = (data: any, item: any) => {
    data.mtrlid = Number(item.mtrlid);
    data.mtrlname = item.mtrlname;
    data.mtrlcode = item.mtrlcode;
    data.mtrlmode = item.mtrlmode;
    data.unit = item.unit;
  };

  const rModelClearMtrlErp = (data: any) => {
    data.mtrlid = 0;
    data.mtrlname = "";
    data.mtrlcode = "";
    data.mtrlmode = "";
    data.unit = "";
  };

  return {
    ...toRefs(state),
    columns,
    columnsMx,
    detail_getData,
    toAddMx,
    toDelMx,
    onSave,
    onAudit,
    onCAudit,
    onDelete,
    onCopyQuote,
    onShowFormula,
    onConfirmConfigureDialog
  };
};
