import { ref, reactive, computed, toRefs, nextTick } from "vue";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { GetSoftBedMxList, SaveSoftBedQuote, GetSoftBedConfigureList, GetChangeSoftBedMxList } 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 ErpMtrlPriceSelect from "@/views/system/selector/erpMtrlPrice/select.vue";
import { useUserStore } from "@/stores/modules/user";
import FormulaEditor from "@/views/system/formula-editor/index.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;
  /**
   * @description 公式编辑弹窗Ref
   */
  formulaEditorRef: any;
  /**
   * @description 当前编辑的行数据
   */
  currentEditRow: any;
  /**
   * @description 当前编辑的列
   */
  currentEditCol: any;
  /**
   * @description 共享公式编辑器Ref
   */
  sharedFormulaEditorRef: any;
  /**
   *
   */
  initParams: any;
  /**
   * @description 详情页主表数据
   */
  softBed: any;
  /**
   * @description 详情页主表明细数据-床头
   */
  headBoardMx: any[];
  /**
   * @description 详情页主表明细数据-床头柜
   */
  nightStandMx: any[];
  /**
   * @description 详情页主表明细数据-床架
   */
  bedFrameMx: any[];
  /**
   * @description 详情页主表明细数据-其他
   */
  otherMx: any[];
  /**
   * @description 详情页明细表格Ref-其他
   */
  VxeTableOtherMxRef: 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;
  ErpMtrlPriceDialogRef: any;
  ErpMtrlPriceDialogProps: any;
  softBedFormulaEnum: any[];
  deptEnum: any[];
  accessoryEnum: any[];
  /**
   * @description 按钮loading状态管理
   */
  loadingStatus: {
    save: boolean;
    audit: boolean;
    caudit: boolean;
    delete: boolean;
    download: boolean;
  };
}

/**
 * @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,
    VxeTableOtherMxRef: null,
    formulaEditorRef: null,
    currentEditRow: null,
    currentEditCol: null,
    sharedFormulaEditorRef: null,
    softBed: {},
    headBoardMx: [],
    nightStandMx: [],
    bedFrameMx: [],
    otherMx: [],
    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: {},
    ErpMtrlPriceDialogRef: null,
    ErpMtrlPriceDialogProps: {},
    softBedFormulaEnum: [],
    deptEnum: [],
    accessoryEnum: [],
    loadingStatus: {
      save: false,
      audit: false,
      caudit: false,
      delete: false,
      download: false
    }
  });
  // 表格配置项
  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: async () => {
        const data = (await getDeptList({})).datatable.map(t => {
          return { ...t, label: t.deptname, value: t.deptid };
        });
        state.deptEnum = data;
        return { data };
      },
      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) => {
          return ALLOW_EDIT_STATE.includes(scope.status) && Number(scope.searchParam.softbed_id) <= 0;
        },
        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",
        editable: (scope: any) => {
          return ALLOW_EDIT_STATE.includes(scope.status) && useUserStore().userInfo.usermode != 1;
        },
        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) => {
          return ALLOW_EDIT_STATE.includes(scope.status) && !Number(scope.searchParam.is_template);
        }
      }
    },
    {
      field: "softbed_relcode",
      title: "报价编码",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        span: 1,
        row: 1,
        order: 7,
        group: "单据信息"
      }
    },
    {
      field: "mtrlmode",
      title: "物料规格",
      // enum: async () => {
      //   const data = (await GetSoftBedMtrlmodeMapper()).datatable;
      //   return data;
      // },
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        props: {
          placeholder: "请输入规格，格式如：长*宽（例如：100*200 或 100 * 200）"
        },
        rules: [
          {
            required: true,
            pattern: new RegExp(/^\d+\s*\*\s*\d+$/),
            message: "格式不正确，请使用 长*宽 格式（数字），如：100*200 或 100 * 200",
            trigger: "blur"
          }
        ],
        span: 1,
        row: 1,
        order: 8,
        group: "单据信息"
      }
    },
    {
      field: "create_emp",
      title: "报价人",
      basicinfo: {
        span: 1,
        row: 1,
        order: 9,
        group: "单据信息"
      }
    },
    {
      field: "mtrltype",
      title: "物料类别",
      enum: async () => {
        const data = (await GetSoftBedMtrltypeMapper()).datatable;
        return data;
      },
      basicinfo: {
        el: "select",
        editable: ALLOW_EDIT_STATE,
        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 enable = ALLOW_EDIT_STATE.includes(state.orderStatus) && Number(scope.searchParam.is_template);

          let bt_enable =
            ALLOW_EDIT_STATE.includes(state.orderStatus) &&
            (scope.searchParam.has_headboard || scope.searchParam.has_nightstand || scope.searchParam.has_bedframe) &&
            (scope.searchParam.softbed_id > 0 || scope.searchParam.template_id > 0);

          let _type = !bt_enable ? "info" : "primary";
          return (
            <>
              <ElRow>
                <ElCol span={16}>
                  <el-checkbox
                    v-model={scope.searchParam.has_headboard}
                    true-value={1}
                    false-value={0}
                    disabled={!enable}
                    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={!enable}
                    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={!enable}
                    label="床架"
                    // onChange={val => autoLoadExtraData_chai(val, "if_d_chai")}
                  />
                </ElCol>
                <ElCol span={8}>
                  <ElButton type={_type} size="small" disabled={!bt_enable} 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 &&
            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: async () => {
        const data = (await GetMoneyRateMapper()).datatable;
        return data;
      },
      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 &&
            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_mtrl_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: 88,
      align: "center",
      datatype: "checkbox",
      visiable: false,
      editRender: {},
      editColRender: (scope: any) => {
        const { row } = scope;
        const { _mainData } = state.LjDetailRef;
        if (Number(row.allow_edit) == 0) {
          row.allow_edit = 0;
        }

        const _disabled = !row.allow_edit && !_mainData.is_template;

        return (
          <>
            <el-checkbox
              v-model={row.allow_edit}
              true-value={1}
              false-value={0}
              class="vxe-edit-col-middle"
              disabled={_disabled}
            ></el-checkbox>
          </>
        );
      }
    },
    {
      field: "pzname",
      title: "部件选配项",
      width: 160,
      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-autocomplete
            v-model={row.pzname}
            disabled={_disabled}
            clearable={true}
            value-key={"pzname"}
            fetch-suggestions={(queryString, cb) => {
              const results =
                state[targetArray]?.filter(item => item.pzname?.toLowerCase().includes(queryString.toLowerCase())) || [];
              cb(results);
            }}
            onSelect={val => fModelChosePzName(row, val)}
          />
        );
      }
    },
    {
      field: "formulaname",
      title: "公式名",
      width: 160,
      enum: async () => {
        const data = (await GetSoftBedFormulaMapper()).datatable.map(t => {
          return { ...t, label: t.formulaname, value: t.formulaid };
        });
        state.softBedFormulaEnum = data;
        return { data };
      },
      editRender: {},
      editColRender: (scope: any) => {
        const { row } = scope;
        const { _mainData } = state.LjDetailRef;
        const _disabled = !row.allow_edit && !_mainData.is_template;

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

        return (
          <el-select
            v-model={row.formulaname}
            disabled={_disabled}
            valueKey={"formulaid"}
            clearable={true}
            onChange={val => fModelChoseFormula(row, val)}
          >
            {options}
          </el-select>
        );
      }
    },
    {
      field: "mtrlcode",
      title: "物料编码"
    },
    {
      field: "mtrlname",
      title: "物料名称规格",
      width: 300,
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        const { _mainData } = state.LjDetailRef;
        let _label = column.title;
        let params = {
          keyword: row.mtrlcode
        };
        const _disabled = !row.allow_edit && !_mainData.is_template;

        return (
          <ErpMtrlPriceSelect
            value={row.mtrlid}
            {...params}
            clearable
            disabled={_disabled}
            placeholder={_label}
            onOpenModal={() => fModelChoseMtrlErp(row, params)}
            onSelect={val => rModelSetMtrlErp(row, val)}
            onClear={() => rModelClearMtrlErp(row)}
          >
            {{
              label: () => `${row.mtrlname} ${row.mtrlmode}`
            }}
          </ErpMtrlPriceSelect>
        );
      }
    },
    {
      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",
      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.useqty} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "use_formula",
      title: "用料量公式",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        return (
          <el-input
            v-model={scope.row.use_formula}
            readonly
            placeholder="点击编辑公式"
            onClick={() => openSharedFormulaEditor(scope.row.use_formula, row, column)}
          />
        );
      }
    },
    {
      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.price} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "price_formula",
      title: "单价公式",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        return (
          <el-input
            v-model={scope.row.price_formula}
            readonly
            placeholder="点击编辑公式"
            onClick={() => openSharedFormulaEditor(scope.row.price_formula, row, column)}
          />
        );
      }
    },
    {
      field: "price_formula_str",
      title: "单价文本公式"
    },
    {
      field: "cost_price",
      title: "成本单价",
      datatype: "number"
    },
    {
      field: "cost_amt",
      title: "成本金额",
      datatype: "number"
    }
  ];

  // 其他tab页明细表格配置项（包含配件列）
  const columnsMxOther: ColumnProps<any>[] = [
    {
      field: "printid",
      title: "行号",
      width: 50
    },
    {
      field: "allow_edit",
      title: "业务修改",
      width: 88,
      align: "center",
      datatype: "checkbox",
      visiable: false,
      editRender: {},
      editColRender: (scope: any) => {
        const { row } = scope;
        const { _mainData } = state.LjDetailRef;
        if (Number(row.allow_edit) == 0) {
          row.allow_edit = 0;
        }

        const _disabled = !row.allow_edit && !_mainData.is_template;

        return (
          <>
            <el-checkbox
              v-model={row.allow_edit}
              true-value={1}
              false-value={0}
              class="vxe-edit-col-middle"
              disabled={_disabled}
            ></el-checkbox>
          </>
        );
      }
    },
    {
      field: "parts_type",
      title: "配件",
      width: 120,
      enum: async () => {
        const data = (await GetSoftBedAccessoryMapper()).datatable;
        state.accessoryEnum = data.map((t: any) => {
          return { label: t.label, value: t.value };
        });
        return state.accessoryEnum;
      },
      editRender: {},
      editColRender: (scope: any) => {
        const { row } = scope;
        const { _mainData } = state.LjDetailRef;
        const _disabled = !row.allow_edit && !_mainData.is_template;

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

        return (
          <el-select v-model={row.parts_type} disabled={_disabled} clearable={true} placeholder="请选择配件类型">
            {options}
          </el-select>
        );
      }
    },
    {
      field: "pzname",
      title: "部件选配项",
      width: 160,
      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-autocomplete
            v-model={row.pzname}
            disabled={_disabled}
            clearable={true}
            value-key={"pzname"}
            fetch-suggestions={(queryString, cb) => {
              const results =
                state[targetArray]?.filter(item => item.pzname?.toLowerCase().includes(queryString.toLowerCase())) || [];
              cb(results);
            }}
            onSelect={val => fModelChosePzName(row, val)}
          />
        );
      }
    },
    {
      field: "formulaname",
      title: "公式名",
      width: 160,
      enum: async () => {
        const data = (await GetSoftBedFormulaMapper()).datatable.map(t => {
          return { ...t, label: t.formulaname, value: t.formulaid };
        });
        state.softBedFormulaEnum = data;
        return { data };
      },
      editRender: {},
      editColRender: (scope: any) => {
        const { row } = scope;
        const { _mainData } = state.LjDetailRef;
        const _disabled = !row.allow_edit && !_mainData.is_template;

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

        return (
          <el-select
            v-model={row.formulaname}
            disabled={_disabled}
            valueKey={"formulaid"}
            clearable={true}
            onChange={val => fModelChoseFormula(row, val)}
          >
            {options}
          </el-select>
        );
      }
    },
    {
      field: "mtrlcode",
      title: "物料编码"
    },
    {
      field: "mtrlname",
      title: "物料名称规格",
      width: 300,
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        const { _mainData } = state.LjDetailRef;
        let _label = column.title;
        let params = {
          keyword: row.mtrlcode
        };
        const _disabled = !row.allow_edit && !_mainData.is_template;

        return (
          <ErpMtrlPriceSelect
            value={row.mtrlid}
            {...params}
            clearable
            disabled={_disabled}
            placeholder={_label}
            onOpenModal={() => fModelChoseMtrlErp(row, params)}
            onSelect={val => rModelSetMtrlErp(row, val)}
            onClear={() => rModelClearMtrlErp(row)}
          >
            {{
              label: () => `${row.mtrlname} ${row.mtrlmode}`
            }}
          </ErpMtrlPriceSelect>
        );
      }
    },
    {
      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",
      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.useqty} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "use_formula",
      title: "用料量公式",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        return (
          <el-input
            v-model={scope.row.use_formula}
            readonly
            placeholder="点击编辑公式"
            onClick={() => openSharedFormulaEditor(scope.row.use_formula, row, column)}
          />
        );
      }
    },
    {
      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.price} type="number" disabled={_disabled}></el-input>;
      }
    },
    {
      field: "price_formula",
      title: "单价公式",
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        return (
          <el-input
            v-model={scope.row.price_formula}
            readonly
            placeholder="点击编辑公式"
            onClick={() => openSharedFormulaEditor(scope.row.price_formula, row, column)}
          />
        );
      }
    },
    {
      field: "price_formula_str",
      title: "单价文本公式"
    },
    {
      field: "cost_price",
      title: "成本单价",
      datatype: "number"
    },
    {
      field: "cost_amt",
      title: "成本金额",
      datatype: "number"
    }
  ];
  /**
   * 详细页获取数据
   */
  const detail_getData = async (params: any) => {
    if (state.orderStatus === "new") {
      const { _mainData } = state.LjDetailRef;
      _mainData.taxrate = 1;
      return;
    }

    const result = await GetSoftBedMxList(params);
    if (state.orderStatus === "copy") {
      result.softbed.copy_id = result.softbed.softbed_id;
      result.softbed.softbed_id = 0;
      result.softbed.softbed_code = "";
    }
    //
    state.softBed = [result.softbed];
    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);
    state.otherMx = result.mxList.filter(item => item.has_type === 8);
  };
  /**
   * 打开部件配置弹窗
   */
  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, state.partsConfig.nightstand);
        } else if (item.contfigtypename.includes("床架")) {
          handleConfigItem(item, state.bedframeConfigOptions, state.partsConfig.bedframe);
        } else if (item.contfigtypename.includes("床头")) {
          handleConfigItem(item, state.headboardConfigOptions, state.partsConfig.headboard);
        }
      }
    }

    nextTick(() => {
      state.showHeadboard = Boolean(_mainData.has_headboard);
      state.showNightstand = Boolean(_mainData.has_nightstand);
      state.showBedframe = Boolean(_mainData.has_bedframe);
      state.isModalVisible = true;
    });
  };
  /**
   *
   * @param item
   * @param targetOption
   * @param targetConfig
   */
  const handleConfigItem = (item: any, targetOption: any[], targetConfig: any[]) => {
    if (item.codeList?.length > 0) {
      for (const code of item.codeList) {
        targetOption.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));

            // 自动添加标准选配值
            if (targetConfig.findIndex(t => t.pzid === code.pzid) === -1) {
              targetConfig.push(
                ...code.codeMxList
                  .filter(t => t.ifdft === 1)
                  .map(t => {
                    return { pzid: t.pzid, selectedId: t.printid, selectedValue: t.namemx };
                  })
              );
            }
          }
        }
      }
    }
  };
  /**
   * 确认部件配置项值
   * @param params 返回内容
   */
  const onConfirmConfigureDialog = (params: any) => {
    const { _mainData } = state.LjDetailRef;
    const { fullData: headboard_table = [] } = state.VxeTableHeadBoardMxRef?.element.getTableData() || {};
    const { fullData: nightstand_table = [] } = state.VxeTableNightStandMxRef?.element.getTableData() || {};
    const { fullData: bedframe_table = [] } = state.VxeTableBedFrameMxRef?.element.getTableData() || {};

    nextTick(async () => {
      _mainData.has_headboard = Number(state.showHeadboard);
      _mainData.has_nightstand = Number(state.showNightstand);
      _mainData.has_bedframe = Number(state.showBedframe);

      state.isModalVisible = false;

      const _codeMxList = [];
      if (_mainData.has_headboard) {
        _codeMxList.push(
          ...state.partsConfig.headboard.map(t => {
            return { pzid: t.pzid, printid: t.selectedId, has_type: 1 };
          })
        );
      }
      if (_mainData.has_nightstand) {
        _codeMxList.push(
          ...state.partsConfig.nightstand.map(t => {
            return { pzid: t.pzid, printid: t.selectedId, has_type: 2 };
          })
        );
      }
      if (_mainData.has_bedframe) {
        _codeMxList.push(
          ...state.partsConfig.bedframe.map(t => {
            return { pzid: t.pzid, printid: t.selectedId, has_type: 4 };
          })
        );
      }

      const billid = _mainData.template_id > 0 ? Number(_mainData.template_id) : Number(_mainData.softbed_id);
      const result = await GetChangeSoftBedMxList({
        billid,
        mxList: [...headboard_table, ...nightstand_table, ...bedframe_table],
        codeList: _codeMxList
      });
      const newHeadBoardMx = [];
      const newNightStandMx = [];
      const newBedFrameMx = [];

      result.mxList.forEach(mx => {
        if (mx.has_type === 1) newHeadBoardMx.push(mx);
        else if (mx.has_type === 2) newNightStandMx.push(mx);
        else if (mx.has_type === 4) newBedFrameMx.push(mx);
      });

      state.headBoardMx = newHeadBoardMx;
      state.nightStandMx = newNightStandMx;
      state.bedFrameMx = newBedFrameMx;

      if (result.mxList.length > 0) {
        ElNotification({
          title: "导入成功",
          type: "success"
        });
      } else {
        ElNotification({
          title: "导入失败",
          type: "warning"
        });
      }
    });
  };
  /**
   * 保存报价
   */
  const onSave = async cb => {
    const { _mainData } = state.LjDetailRef;

    const { fullData: headboard_table = [] } = state.VxeTableHeadBoardMxRef?.element.getTableData() || {};
    const { fullData: nightstand_table = [] } = state.VxeTableNightStandMxRef?.element.getTableData() || {};
    const { fullData: bedframe_table = [] } = state.VxeTableBedFrameMxRef?.element.getTableData() || {};
    const { fullData: other_table = [] } = state.VxeTableOtherMxRef?.element.getTableData() || {};

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

    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);
    if (other_table && other_table.length > 0) _mxList.push(...other_table);

    if (_softbed.has_headboard)
      _codeMxList.push(
        ...state.partsConfig.headboard.map(t => {
          return { pzid: t.pzid, printid: t.selectedId };
        })
      );
    if (_softbed.has_nightstand)
      _codeMxList.push(
        ...state.partsConfig.nightstand.map(t => {
          return { pzid: t.pzid, printid: t.selectedId };
        })
      );
    if (_softbed.has_bedframe)
      _codeMxList.push(
        ...state.partsConfig.bedframe.map(t => {
          return { pzid: t.pzid, printid: t.selectedId };
        })
      );

    transformData(_softbed);

    const params: any = {
      softbed: _softbed,
      type: state.orderStatus
    };

    // 设置loading状态为true
    state.loadingStatus.save = true;

    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);
          ElMessage.error(t("sys.api.operationFailed"));
        })
        .finally(() => {
          // 无论成功失败都要重置loading状态
          state.loadingStatus.save = false;
        });
    } catch (error) {
      ElMessage.error(t("sys.api.operationFailed"));
      // 异常情况下也要重置loading状态
      state.loadingStatus.save = false;
    }
  };

  const transformData = (data: any) => {
    for (let key in data) {
      if (typeof data[key] === "boolean") data[key] = Number(data[key]);
    }
  };
  /**
   * 审核报价
   */
  const onAudit = (list: any, cb?: Function) => {
    ElMessageBox.confirm("是否确定要审核单据吗?", "询问", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        state.loadingStatus.audit = true;
        AuditSoftBedQuote({ list, type: 1 })
          .then(() => {
            ElMessage.success(t("sys.api.operationSuccess"));
            cb && cb();
          })
          .catch(error => {
            console.log("审核失败:", error);
            ElMessage.error(t("sys.api.operationFailed"));
          })
          .finally(() => {
            state.loadingStatus.audit = false;
          });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };
  /**
   * 撤审报价
   */
  const onCAudit = (list: any, cb?: Function) => {
    ElMessageBox.confirm("是否确定要撤审单据吗?", "询问", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        state.loadingStatus.caudit = true;
        AuditSoftBedQuote({ list, type: 0 })
          .then(() => {
            ElMessage.success(t("sys.api.operationSuccess"));
            cb && cb();
            state.VxeTableRef.refresh();
          })
          .catch(error => {
            console.log("撤审失败:", error);
            ElMessage.error(t("sys.api.operationFailed"));
          })
          .finally(() => {
            state.loadingStatus.caudit = false;
          });
      })
      .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(() => {
        state.loadingStatus.delete = true;
        DeleteSoftBedQuote({ list })
          .then(() => {
            ElMessage.success(t("sys.api.operationSuccess"));
            cb && cb();
            state.VxeTableRef.refresh();
          })
          .catch(error => {
            console.log("删除失败:", error);
            ElMessage.error(t("sys.api.operationFailed"));
          })
          .finally(() => {
            state.loadingStatus.delete = false;
          });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };
  /**
   * 复制报价
   */
  const onCopyQuote = () => {};
  /**
   * 显示公式
   */
  const onShowFormula = () => {};
  /**
   * 获取规格
   * @returns
   */
  const GetSoftBedMtrlmodeMapper = async () => {
    return CommonDynamicSelect({ dsname: "_Mapper_softbed_mtrlmode", queryparams: {} });
  };
  /**
   * 获取币种
   * @returns
   */
  const GetSoftBedMtrltypeMapper = async () => {
    return CommonDynamicSelect({ dsname: "_Mapper_softbed_mtrltype", queryparams: {} });
  };
  /**
   * 获取币种
   * @returns
   */
  const GetMoneyRateMapper = async () => {
    return CommonDynamicSelect({ dsname: "_Mapper_if_moneyrate", queryparams: {} });
  };
  /**
   * 获取软床公式
   * @returns
   */
  const GetSoftBedFormulaMapper = async () => {
    return await CommonDynamicSelect({ dsname: "_Mapper_softbed_formulaid", queryparams: {} });
    // if (result) {
    //   state.softBedFormulaEnum.push(
    //     result.datatable.map(t => {
    //       return { label: t.formulaname, value: t.formulaid, ...t };
    //     })
    //   );
    // }
  };
  /**
   * 获取配件类型
   * @returns
   */
  const GetSoftBedAccessoryMapper = async () => {
    const result = await CommonDynamicSelect({ dsname: "_Mapper_softbed_accessory", queryparams: {} });
    if (result && result.datatable) {
      state.accessoryEnum = result.datatable.map((item: any) => {
        return { label: item.label, value: item.value };
      });
    }
    return result;
  };
  /**
   * @description 获取部门汇率 和  折扣率
   */
  const wf_get_moneyrate_discount = (val: any) => {
    const { _mainData } = state.LjDetailRef;

    if (state.deptEnum) {
      let depItem = state.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 = async (data: any, item: any) => {
    // 获取明细
    const result = await GetSoftBedMxList({ billid: Number(item.softbed_id) });
    const coverList = [
      "deptid",
      "mtrlmode",
      "mtrltype",
      "commission",
      "taxes",
      "taxrate",
      "other_rate",
      "extras_cost",
      "money_type",
      "moneyrate",
      "dscrp",
      "costamt",
      "nottax_factory_cost",
      "nottax_dept_cost",
      "dept_cost",
      "foreign_cost",
      "total_mtrl_cost",
      "total_hr_cost",
      "total_cost"
    ];
    //
    data.template_id = result.softbed.softbed_id;
    data.template_code = result.softbed.softbed_code;
    data.template_name = result.softbed.softbed_name;
    data.has_headboard = Number(result.softbed.has_headboard);
    data.has_nightstand = Number(result.softbed.has_nightstand);
    data.has_bedframe = Number(result.softbed.has_bedframe);
    //
    for (const key of coverList) {
      data[key] = result.softbed[key];
    }
    //
    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);
    state.otherMx = result.mxList.filter(item => item.has_type === 8);
  };
  /**
   * 清空选择参数
   * @param data
   */
  const rModelClearTemplate = (data: any) => {
    data.template_id = 0;
    data.template_code = "";
    data.template_name = "";
    data.has_headboard = 0;
    data.has_nightstand = 0;
    data.has_bedframe = 0;
  };

  const toAddMx = async (tableRef: any) => {
    const { _mainData } = state.LjDetailRef;

    // 检测是否有勾
    const has_type = getHasType(tableRef);
    if (
      (has_type === 1 && _mainData.has_headboard === 1) ||
      (has_type === 2 && _mainData.has_nightstand === 1) ||
      (has_type === 4 && _mainData.has_bedframe === 1) ||
      has_type === 8 // 其他tab页不需要勾选
    ) {
      const $table = tableRef.element;
      if ($table) {
        // 获取当前表格数据，计算行号
        const currentData = $table.getData() || [];
        let startIndex = 1;
        if (currentData.length > 0) {
          // 找到当前最大的行号
          const maxPrintId = Math.max(...currentData.map((row: any) => row.printid || 0));
          startIndex = maxPrintId + 1;
        }

        // 对于其他tab页，检查是否有value=1的配件类型，如果有则自动添加
        if (has_type === 8) {
          // 确保配件枚举数据已加载
          if (state.accessoryEnum.length === 0) {
            await GetSoftBedAccessoryMapper();
          }

          // 查找value=1的配件类型
          const defaultAccessories = state.accessoryEnum.filter(item => item.value === 1);
          if (defaultAccessories.length > 0) {
            // 为每个value=1的配件类型添加一行记录
            for (let i = 0; i < defaultAccessories.length; i++) {
              const accessory = defaultAccessories[i];
              const records = {
                softbed_id: _mainData.softbed_id,
                has_type: has_type,
                printid: startIndex + i, // 设置行号
                mtrlname: "",
                mtrlcode: "",
                mtrlmode: "",
                unit: "",
                allow_edit: 1,
                cutting_length: 0,
                cutting_width: 0,
                cutting_qty: 0,
                loss_rate: 0,
                price: 0,
                parts_type: accessory.label // 设置配件类型的值
              };
              const { row } = await $table.insertAt(records, -1);
              await $table.setCurrentRow(row);
            }
            ElMessage({
              type: "success",
              message: `已自动添加 ${defaultAccessories.length} 个默认配件类型`
            });
            return;
          }
        }

        // 普通新增逻辑
        const records = {
          softbed_id: _mainData.softbed_id,
          has_type: has_type,
          printid: startIndex, // 设置行号
          mtrlname: "",
          mtrlcode: "",
          mtrlmode: "",
          unit: "",
          allow_edit: 1,
          cutting_length: 0,
          cutting_width: 0,
          cutting_qty: 0,
          loss_rate: 0,
          price: 0,
          parts_type: has_type === 8 ? "" : undefined // 其他tab页添加配件列
        };
        const { row } = await $table.insertAt(records, -1);
        await $table.setCurrentRow(row);
      }
    } else {
      ElMessage({
        type: "info",
        message: "请先勾选对应类型"
      });
    }
  };

  const toDelMx = (tableRef: any) => {
    const { $table, curRecords } = getCurrentRecords(tableRef);
    const { _mainData } = state.LjDetailRef;
    for (const row of curRecords) {
      if (!row.allow_edit && !_mainData.is_template) {
        ElMessage({
          type: "warning",
          message: `非可编辑行，无法删除!`
        });
        return;
      }
    }
    ElMessageBox.confirm(`是否确定要删除明细吗?`, "询问", {
      confirmButtonText: t("common.delText"),
      cancelButtonText: "否",
      type: "error"
    })
      .then(() => {
        $table.removeCurrentRow();
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "warning",
          message: "操作取消"
        });
      });
  };

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

  /**
   * @description 弹窗模块：客户选择
   * @param data 当前数据
   * @param status 当前订单状态
   * @returns Promise
   */
  const fModelChoseMtrlErp = (data: any, params: any) => {
    return new Promise((resolve, reject) => {
      let _params = {
        keyword: ""
      };
      state.ErpMtrlPriceDialogProps = {
        onSubmit: (res: any) => {
          // submit
          nextTick(() => {
            rModelSetMtrlErp(data, res.value[0]);
            resolve(1);
          });
        },
        onCancel: (error: any) => {
          // cancel 回调
          console.log("openCustDialog error", error);
        }
      };
      state.ErpMtrlPriceDialogRef.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;
    data.price = item.price;
  };

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

  /**
   * @description 选择公式返回
   */
  const fModelChoseFormula = (data: any, val: any) => {
    data.formulaid = val.formulaid;
    data.formulaname = val.formulaname;
    data.use_formula = val.use_formula;
    data.price_formula = val.price_formula;
  };

  /**
   * @description 选择公式返回
   */
  const fModelChosePzName = (data: any, val: any) => {
    data.pzid = val.pzid;
    data.pzname = val.pzname;
  };

  /**
   * 打开共享公式编辑器
   */
  const openSharedFormulaEditor = (formula: string, row: any, col: any) => {
    state.currentEditRow = row;
    state.currentEditCol = col;
    state.sharedFormulaEditorRef?.show?.(0, false, formula);
  };

  /**
   * 处理公式确认
   */
  const handleFormulaConfirm = (payload: { formula: string; valid: boolean; parameters: any[] }) => {
    if (payload.valid && state.currentEditRow && state.currentEditCol) {
      state.currentEditRow[state.currentEditCol.field] = payload.formula;
    }
  };

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