<template>
  <LjDetail
    name="rpMustPayCrmDetail"
    ref="LjDetailRef"
    v-bind="detailProps"
    :request-api="getData"
    :data-callback="dataCallback"
    :init-param="initParams"
    v-model:order-status="orderStatus"
    :action="orderDefaultAction"
    @after-mounted="funcAfterMound"
    :if-layout-editable="false"
    :default-columns-value="defaultColumnsValue"
  >
    <template #rightBtn="scope">
      <el-space warp>
        <el-checkbox
          v-model="isShowOriginFormulaMattress"
          v-if="CheckPower(131)"
          label="显示旧公式"
          size="small"
          @change="showOriginFormulaMattress"
        />
        <el-select disabled v-model="scope.data.dannum_type" placeholder="大小单" style="width: 80px">
          <el-option label="散单" :value="1" />
          <el-option label="小单" :value="4" />
          <el-option label="标准" :value="2" />
          <el-option label="大单" :value="3" />
        </el-select>
      </el-space>
    </template>
    <template #headerSuffix>
      <Statistic
        :data="cmpFormulaReplace"
        :differ="cmpDiffer"
        :iforigin="isShowOriginFormulaMattress"
        :precision="2"
        :moneyrate="cmpMoneyrate"
        :ifMoneyrate="cmpIfMoneyrate"
        @click="gotoShowFormula"
      />
    </template>
    <!-- @to-pin-detail="emit('toPinDetail')" -->
    <template #fabricMx__tabtitle="scope">
      <template v-if="isTabsBadge_fabric_error">
        <el-badge :value="isTabsBadge_fabric_error + '异常'" type="danger">
          {{ scope.props.label }}
        </el-badge>
      </template>
      <template v-else>
        <el-badge :value="isTabsBadge_fabric" type="primary" :show-zero="false">
          {{ scope.props.label }}
        </el-badge>
      </template>
    </template>
    <template #fabricMx>
      <el-tabs v-model="fabricMxTabs" type="card" class="h-full flx-col fabric-mx-tabs" @tab-click="SetCurrentTabs">
        <el-tab-pane
          class="h-full flx"
          label="裥面"
          name="tabpage_8"
          v-if="mattresstypeEnum && Number(mattresstypeEnum?.if_top_side) == 1"
        >
          <template #label>
            <template v-if="isFilterErrorBadge(fabricMxTab8)">
              <el-badge :value="isFilterErrorBadge(fabricMxTab8) + '异常'" type="danger"> 裥面 </el-badge>
            </template>
            <template v-else>
              <el-badge
                :value="isFilterSucessBadge(fabricMxTab8)"
                type="primary"
                :show-zero="false"
                :color="_variables.colorPrimary200"
              >
                裥面
              </el-badge>
            </template>
          </template>
          <LjVxeTable
            ref="fabricMxTab8Ref"
            row-key="key"
            table-cls="h-full"
            :data="fabricMxTab8"
            :columns="columnsMx"
            :dwname="DwnameEnum.mattressQuoteMx"
            :table-props="tableProps_mx"
            :tool-button="[]"
            :auto-load-layout="false"
            collapseButtons
            :request-auto="false"
            :extra-loading="mxLoading"
            :footer-method="footerMethod"
          >
            <template #tableHeader v-if="orderStatus">
              <el-space wrap>
                <el-button type="default" @click="toMove(1, 'fabricMxTab8Ref')">{{ t("common.moveUp") }}</el-button>
                <el-button type="default" @click="toMove(-1, 'fabricMxTab8Ref')">{{ t("common.moveDown") }}</el-button>
              </el-space>
            </template>
          </LjVxeTable>
        </el-tab-pane>
        <el-tab-pane
          class="h-full flx"
          label="裥底"
          name="tabpage_9"
          v-if="mattresstypeEnum && Number(mattresstypeEnum.if_button_sdie) == 1"
        >
          <template #label>
            <template v-if="isFilterErrorBadge(fabricMxTab9)">
              <el-badge :value="isFilterErrorBadge(fabricMxTab9) + '异常'" type="danger"> 裥底 </el-badge>
            </template>
            <template v-else>
              <el-badge
                :value="isFilterSucessBadge(fabricMxTab9)"
                type="primary"
                :show-zero="false"
                :color="_variables.colorPrimary200"
              >
                裥底
              </el-badge>
            </template>
          </template>
          <LjVxeTable
            ref="fabricMxTab9Ref"
            row-key="key"
            table-cls="h-full"
            :data="fabricMxTab9"
            :columns="columnsMx"
            :dwname="DwnameEnum.mattressQuoteMx"
            :table-props="tableProps_mx"
            :tool-button="[]"
            :request-auto="false"
            :auto-load-layout="false"
            collapseButtons
            :extra-loading="mxLoading"
            :footer-method="footerMethod"
          >
            <template #tableHeader v-if="orderStatus">
              <el-space wrap>
                <el-button type="default" @click="toMove(1, 'fabricMxTab9Ref')">{{ t("common.moveUp") }}</el-button>
                <el-button type="default" @click="toMove(-1, 'fabricMxTab9Ref')">{{ t("common.moveDown") }}</el-button>
              </el-space>
            </template>
          </LjVxeTable>
        </el-tab-pane>
        <el-tab-pane
          class="h-full flx"
          label="裥大恻"
          name="tabpage_10"
          v-if="mattresstypeEnum && Number(mattresstypeEnum.if_big_side) == 1"
        >
          <template #label>
            <template v-if="isFilterErrorBadge(fabricMxTab10)">
              <el-badge :value="isFilterErrorBadge(fabricMxTab10) + '异常'" type="danger"> 裥大恻 </el-badge>
            </template>
            <template v-else>
              <el-badge
                :value="isFilterSucessBadge(fabricMxTab10)"
                type="primary"
                :show-zero="false"
                :color="_variables.colorPrimary200"
              >
                裥大恻
              </el-badge>
            </template>
          </template>
          <LjVxeTable
            ref="fabricMxTab10Ref"
            row-key="key"
            table-cls="h-full"
            :data="fabricMxTab10"
            :columns="columnsMx"
            :dwname="DwnameEnum.mattressQuoteMx"
            :table-props="tableProps_mx"
            :tool-button="[]"
            :request-auto="false"
            :auto-load-layout="false"
            collapseButtons
            :extra-loading="mxLoading"
            :footer-method="footerMethod"
          >
            <template #tableHeader v-if="orderStatus">
              <el-space wrap>
                <el-dropdown placement="bottom-start" @command="val => handleSelFabricMxNewMtrlGroup('tabpage_10', val)">
                  <el-button type="primary">
                    {{ t("business.detail.addChastr") }}<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="item in fabricMx10NewMtrlGroup" :key="item.value" :command="item">{{
                        item.label
                      }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button type="danger" @click="handleDelFabricMxNewMtrlGroup('tabpage_10')">{{
                  t("business.detail.delChastr")
                }}</el-button>
              </el-space>
              <el-divider direction="vertical" />
              <el-space wrap>
                <el-button type="default" @click="toMove(1, 'fabricMxTab10Ref')">{{ t("common.moveUp") }}</el-button>
                <el-button type="default" @click="toMove(-1, 'fabricMxTab10Ref')">{{ t("common.moveDown") }}</el-button>
              </el-space>
            </template>
          </LjVxeTable>
        </el-tab-pane>
        <el-tab-pane
          class="h-full flx"
          label="裥小恻"
          name="tabpage_11"
          v-if="mattresstypeEnum && Number(mattresstypeEnum.if_small_side) == 1"
        >
          <template #label>
            <template v-if="isFilterErrorBadge(fabricMxTab11)">
              <el-badge :value="isFilterErrorBadge(fabricMxTab11) + '异常'" type="danger"> 裥小恻 </el-badge>
            </template>
            <template v-else>
              <el-badge
                :value="isFilterSucessBadge(fabricMxTab11)"
                type="primary"
                :show-zero="false"
                :color="_variables.colorPrimary200"
              >
                裥小恻
              </el-badge>
            </template>
          </template>
          <LjVxeTable
            ref="fabricMxTab11Ref"
            row-key="key"
            table-cls="h-full"
            :data="fabricMxTab11"
            :columns="columnsMx"
            :dwname="DwnameEnum.mattressQuoteMx"
            :table-props="tableProps_mx"
            :tool-button="[]"
            :request-auto="false"
            :auto-load-layout="false"
            collapseButtons
            :extra-loading="mxLoading"
            :footer-method="footerMethod"
          >
            <template #tableHeader v-if="orderStatus">
              <el-space wrap>
                <el-dropdown placement="bottom-start" @command="val => handleSelFabricMxNewMtrlGroup('tabpage_11', val)">
                  <el-button type="primary">
                    {{ t("business.detail.addChastr") }}<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="item in fabricMx11NewMtrlGroup" :key="item.value" :command="item">{{
                        item.label
                      }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button type="danger" @click="handleDelFabricMxNewMtrlGroup('tabpage_10')">{{
                  t("business.detail.delChastr")
                }}</el-button>
              </el-space>
              <el-divider direction="vertical" />
              <el-space wrap>
                <el-button type="default" @click="toMove(1, 'fabricMxTab11Ref')">{{ t("common.moveUp") }}</el-button>
                <el-button type="default" @click="toMove(-1, 'fabricMxTab11Ref')">{{ t("common.moveDown") }}</el-button>
              </el-space>
            </template>
          </LjVxeTable>
        </el-tab-pane>
        <el-tab-pane
          class="h-full flx"
          label="裥V恻"
          name="tabpage_12"
          v-if="mattresstypeEnum && Number(mattresstypeEnum.if_v_side) == 1"
        >
          <template #label>
            <template v-if="isFilterErrorBadge(fabricMxTab12)">
              <el-badge :value="isFilterErrorBadge(fabricMxTab12) + '异常'" type="danger"> 裥V恻 </el-badge>
            </template>
            <template v-else>
              <el-badge
                :value="isFilterSucessBadge(fabricMxTab12)"
                type="primary"
                :show-zero="false"
                :color="_variables.colorPrimary200"
              >
                裥V恻
              </el-badge>
            </template>
          </template>
          <LjVxeTable
            ref="fabricMxTab12Ref"
            row-key="key"
            table-cls="h-full"
            :data="fabricMxTab12"
            :columns="columnsMx"
            :dwname="DwnameEnum.mattressQuoteMx"
            :table-props="tableProps_mx"
            :tool-button="[]"
            :request-auto="false"
            :auto-load-layout="false"
            collapseButtons
            :extra-loading="mxLoading"
            :footer-method="footerMethod"
          >
            <template #tableHeader v-if="orderStatus">
              <el-space wrap>
                <el-button type="default" @click="toMove(1, 'fabricMxTab12Ref')">{{ t("common.moveUp") }}</el-button>
                <el-button type="default" @click="toMove(-1, 'fabricMxTab12Ref')">{{ t("common.moveDown") }}</el-button>
              </el-space>
            </template>
          </LjVxeTable>
        </el-tab-pane>
        <el-tab-pane class="h-full flx" label="拉手刺绣及其他工艺" name="tabpage_13">
          <template #label>
            <template v-if="isFilterErrorBadge(fabricMxTab13)">
              <el-badge :value="isFilterErrorBadge(fabricMxTab13) + '异常'" type="danger"> 拉手刺绣及其他工艺 </el-badge>
            </template>
            <template v-else>
              <el-badge
                :value="isFilterSucessBadge(fabricMxTab13)"
                type="primary"
                :show-zero="false"
                :color="_variables.colorPrimary200"
              >
                拉手刺绣及其他工艺
              </el-badge>
            </template>
          </template>
          <LjVxeTable
            ref="fabricMxTab13Ref"
            row-key="key"
            table-cls="h-full"
            :data="fabricMxTab13"
            :columns="columnsMx"
            :dwname="DwnameEnum.mattressQuoteMx"
            :table-props="tableProps_mx"
            :tool-button="[]"
            :request-auto="false"
            :auto-load-layout="false"
            collapseButtons
            :extra-loading="mxLoading"
            :footer-method="footerMethod"
          >
            <template #tableHeader v-if="orderStatus">
              <el-space wrap>
                <el-button type="default" @click="toMove(1, 'fabricMxTab13Ref')">{{ t("common.moveUp") }}</el-button>
                <el-button type="default" @click="toMove(-1, 'fabricMxTab13Ref')">{{ t("common.moveDown") }}</el-button>
              </el-space>
            </template>
          </LjVxeTable>
        </el-tab-pane>
      </el-tabs>
    </template>

    <template #bednetMx__tabtitle="scope">
      <template v-if="isTabsBadge_bednet_error">
        <el-badge :value="isTabsBadge_bednet_error + '异常'" type="danger">
          {{ scope.props.label }}
        </el-badge>
      </template>
      <template v-else>
        <el-badge :value="isTabsBadge_bednet" type="primary" :show-zero="false">
          {{ scope.props.label }}
        </el-badge>
      </template>
    </template>
    <template #bednetMx>
      <LjVxeTable
        ref="bednetMxRef"
        row-key="key"
        table-cls="h-full"
        :data="bednetMxData"
        :columns="columnsMxBednet"
        :dwname="DwnameEnum.mattressQuoteMxBednet"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :request-auto="false"
        :auto-load-layout="false"
        collapseButtons
        :extra-loading="mxLoading"
        :footer-method="footerMethod"
        @cell-dblclick="handleCellDblClick_bednet"
      >
        <template #tableHeader v-if="orderStatus">
          <el-space wrap>
            <el-button type="primary" @click="handleAddBednetMx">{{ t("common.add") }}</el-button>
            <el-button type="danger" @click="handleEditBednetMx">{{ t("common.editText") }}</el-button>
          </el-space>
          <el-divider direction="vertical" />
          <el-space wrap>
            <el-button type="default" @click="toMove(1, 'bednetMxRef')">{{ t("common.moveUp") }}</el-button>
            <el-button type="default" @click="toMove(-1, 'bednetMxRef')">{{ t("common.moveDown") }}</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>

    <template #cushionsMx__tabtitle="scope">
      <template v-if="isTabsBadge_cushions_error">
        <el-badge :value="isTabsBadge_cushions_error + '异常'" type="danger">
          {{ scope.props.label }}
        </el-badge>
      </template>
      <template v-else>
        <el-badge :value="isTabsBadge_cushions" type="primary" :show-zero="false">
          {{ scope.props.label }}
        </el-badge>
      </template>
    </template>
    <template #cushionsMx>
      <LjVxeTable
        ref="cushionsMxRef"
        row-key="key"
        table-cls="h-full"
        :data="cushionsMxData"
        :columns="columnsMxCushions"
        :dwname="DwnameEnum.mattressQuoteMxCushions"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :request-auto="false"
        :auto-load-layout="false"
        collapseButtons
        :extra-loading="mxLoading"
        :footer-method="footerMethod"
      >
        <template #tableHeader v-if="orderStatus">
          <el-space wrap>
            <el-button type="primary" @click="toAddMx_cushions(0)">{{ t("common.addText") }}</el-button>
            <el-button type="primary" @click="toAddMx_cushions(1)">{{ t("common.insert") }}</el-button>
            <el-button type="danger" @click="toDelMx_cushions">{{ t("common.delText") }}</el-button>
          </el-space>
          <el-divider direction="vertical" />
          <el-space wrap>
            <el-button type="default" @click="toMove(1, 'cushionsMxRef')">{{ t("common.moveUp") }}</el-button>
            <el-button type="default" @click="toMove(-1, 'cushionsMxRef')">{{ t("common.moveDown") }}</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>

    <template #accessoriesMx__tabtitle="scope">
      <template v-if="isTabsBadge_accessories_error">
        <el-badge :value="isTabsBadge_accessories_error + '异常'" type="danger">
          {{ scope.props.label }}
        </el-badge>
      </template>
      <template v-else>
        <el-badge :value="isTabsBadge_accessories" type="primary" :show-zero="false">
          {{ scope.props.label }}
        </el-badge>
      </template>
    </template>
    <template #accessoriesMx>
      <LjVxeTable
        ref="accessoriesMxRef"
        row-key="key"
        table-cls="h-full"
        :data="accessoriesMxData"
        :columns="columnsMxAccessories"
        :dwname="DwnameEnum.mattressQuoteMxAccessories"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :request-auto="false"
        :auto-load-layout="false"
        collapseButtons
        :extra-loading="mxLoading"
        :footer-method="footerMethod"
      >
        <!-- <template #tableHeader>
          <el-space wrap>
            <el-button type="primary">{{ $t("common.addText") }}</el-button>
            <el-button type="danger">{{ $t("common.delText") }}</el-button>
          </el-space>
        </template> -->
      </LjVxeTable>
    </template>

    <template #packagMx__tabtitle="scope">
      <template v-if="isTabsBadge_packag_error">
        <el-badge :value="isTabsBadge_packag_error + '异常'" type="danger">
          {{ scope.props.label }}
        </el-badge>
      </template>
      <template v-else>
        <el-badge :value="isTabsBadge_packag" type="primary" :show-zero="false">
          {{ scope.props.label }}
        </el-badge>
      </template>
    </template>
    <template #packagMx="scope">
      <LjVxeTable
        ref="packagMxRef"
        row-key="key"
        table-cls="h-full"
        :data="packagMxData"
        :columns="columnsMxPackag"
        :dwname="DwnameEnum.mattressQuoteMxPackag"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :request-auto="false"
        :auto-load-layout="false"
        collapseButtons
        :extra-loading="mxLoading"
        :footer-method="footerMethod"
      >
        <template #tableHeader>
          <el-space wrap>
            <el-form label-width="70px" inline :disabled="!orderStatus">
              <el-form-item label="包装方式">
                <el-select v-model="scope.data.packtype" style="width: 120px" @change="funcPacktypeChange">
                  <el-option v-for="item in packtypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="卷包直径" v-if="scope.data.packtype == 1">
                <el-input-number v-model="scope.data.diameter" :min="0" :max="1000" />CM
              </el-form-item>
              <el-form-item label="木托方式" v-if="scope.data.packtype == 0">
                <el-select v-model="scope.data.woodpallettype" style="width: 120px">
                  <el-option v-for="item in woodpallettypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="压包数量" v-if="scope.data.packtype == 0">
                <el-input-number v-model="scope.data.packqty" :min="0" :max="1000" />
              </el-form-item>
              <el-form-item label="地区">
                <el-select v-model="scope.data.area" style="width: 120px" clearable>
                  <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="柜型">
                <el-select v-model="scope.data.cabinet_type" style="width: 120px" clearable>
                  <el-option v-for="item in cabinetTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="体积">
                <el-input-number v-model="scope.data.cubage" :min="0" :max="1000" />
              </el-form-item>
            </el-form>
          </el-space>
        </template>
      </LjVxeTable>
    </template>

    <template #innerClothLayerMx__tabtitle="scope">
      <template v-if="innerClothLayerNum_error">
        <el-badge :value="innerClothLayerNum_error + '异常'" type="danger">
          {{ scope.props.label }}
        </el-badge>
      </template>
      <template v-else>
        <el-badge :value="innerClothLayerNum" type="primary" :show-zero="false">
          {{ scope.props.label }}
        </el-badge>
      </template>
    </template>
    <template #innerClothLayerMx>
      <LjVxeTable
        ref="innerClothLayerMxRef"
        row-key="key"
        table-cls="h-full"
        :request-api="getData_innerClothLayer"
        :data-callback="dataCallbackMx"
        :init-param="initParams"
        :columns="columnsMxInnerClothLayer"
        :dwname="DwnameEnum.mattressQuoteMxInnerClothLayer"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        collapseButtons
        :footer-method="footerMethod"
        @after-mounted="resetMergeCellsInner"
      >
        <template #tableHeader v-if="orderStatus">
          <el-space wrap>
            <el-button type="primary" @click="handleToImportMxInner">{{ t("business.detail.importMx") }}</el-button>
            <el-button type="danger" @click="hanleDelMxInner(0)">{{ t("business.detail.deleteMx") }}</el-button>
            <el-button type="danger" @click="hanleDelMxInner(1)">{{ t("business.detail.deleteAllMx") }}</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>

    <template #topCottonMx__tabtitle="scope">
      <template v-if="topCottonNum_error">
        <el-badge :value="topCottonNum_error + '异常'" type="danger">
          {{ scope.props.label }}
        </el-badge>
      </template>
      <template v-else>
        <el-badge :value="topCottonNum" type="primary" :show-zero="false">
          {{ scope.props.label }}
        </el-badge>
      </template>
    </template>
    <template #topCottonMx>
      <LjVxeTable
        ref="topCottonMxRef"
        row-key="key"
        table-cls="h-full"
        :request-api="getData_topCotton"
        :data-callback="dataCallbackMx"
        :init-param="initParams"
        :columns="columnsMx"
        :dwname="DwnameEnum.mattressQuoteMx"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        collapseButtons
        :footer-method="footerMethod"
        @after-mounted="resetMergeCellsTopCotton"
      >
        <template #tableHeader v-if="orderStatus">
          <el-space wrap>
            <el-dropdown placement="bottom-start" @command="wf_add_w_butao">
              <el-button type="primary">
                {{ t("common.addText") }}<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="item in topCottonAddList" :key="item.value" :command="item">{{
                    item.label
                  }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="danger" @click="wf_del_w_butao">{{ t("common.delText") }}</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>

    <template #specialProcesses__tabtitle="scope">
      <el-badge :value="specialProcessesNum" type="primary" :show-zero="false">
        {{ scope.props.label }}
      </el-badge>
    </template>
    <template #specialProcesses>
      <LjVxeTable
        ref="specialProcessesMxRef"
        row-key="key"
        table-cls="h-full"
        :request-api="getData_specialProcesses"
        :data-callback="dataCallbackMx"
        :init-param="initParams"
        :columns="columnsMx_processes"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        collapseButtons
        :footer-sum-attrs="['price']"
      >
        <template #tableHeader v-if="orderStatus">
          <el-space wrap>
            <el-button type="primary" @click="funcAddMtrlMx({}, null, 'specialProcessesMxRef', -1)">
              {{ t("common.addText") }}
            </el-button>
            <!-- <el-button type="danger" @click="funcDelMtrlMx()">{{ t("common.delText") }}</el-button> -->
          </el-space>
        </template>
      </LjVxeTable>
    </template>

    <template #additionalCosts__tabtitle="scope">
      <el-badge :value="additionalCostsNum" type="primary" :show-zero="false">
        {{ scope.props.label }}
      </el-badge>
    </template>
    <template #additionalCosts>
      <LjVxeTable
        ref="additionalCostsMxRef"
        row-key="key"
        table-cls="h-full"
        :request-api="getData_additionalCosts"
        :data-callback="dataCallbackMx"
        :init-param="initParams"
        :columns="columnsMx_additional"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        collapseButtons
        :footer-sum-attrs="['price']"
      >
        <template #tableHeader v-if="orderStatus">
          <el-space wrap>
            <el-button type="primary" @click="funcAddMtrlMx({}, null, 'additionalCostsMxRef', -1)">
              {{ t("common.addText") }}
            </el-button>
            <!-- <el-button type="danger" @click="wf_del_w_butao">{{ t("common.delText") }}</el-button> -->
          </el-space>
        </template>
      </LjVxeTable>
    </template>

    <template #subSpecs__tabtitle="scope">
      <template v-if="LjDetailRef._mainData.parentid > 0">
        <el-badge value="副" type="primary" :show-zero="false">
          {{ scope.props.label }}
        </el-badge>
      </template>
      <el-badge v-else :value="subSpecsNum" type="primary" :show-zero="false">
        {{ scope.props.label }}
      </el-badge>
    </template>
    <template #subSpecs>
      <LjVxeTable
        v-if="columnsMx_subSpecs_dis.length"
        ref="subSpecsRef"
        row-key="key"
        table-cls="h-full"
        :request-auto="false"
        :data="subSpecsData"
        :columns="columnsMx_subSpecs_dis"
        :table-props="tableProps_subSpecs"
        :table-events="tableEvents"
        :tool-button="[]"
        :auto-load-layout="false"
        collapseButtons
      >
        <template #tableHeader>
          <el-space wrap v-if="orderStatus">
            <el-button type="primary" @click="toAddMx_subSpecs">{{ t("common.addText") }}</el-button>
            <el-button type="danger" @click="toDelMx_subSpecs">{{ t("common.delText") }}</el-button>
          </el-space>
          <el-space wrap v-else-if="!LjDetailRef._mainData.parentid && Number(LjDetailRef._mainData.flag) == 1">
            <template v-if="!editSubSpecs">
              <el-button type="primary" @click="toEdit_subSpecs">{{ t("common.editText") }}</el-button>
            </template>
            <template v-else>
              <el-button type="primary" @click="toAddMx_subSpecs">{{ t("common.addText") }}</el-button>
              <el-button type="danger" @click="toDelMx_subSpecs">{{ t("common.delText") }}</el-button>
              <el-divider direction="vertical" />
              <el-button type="success" @click="toSave_subSpecs">{{ t("common.saveText") }}</el-button>
              <el-button type="default" @click="toCancel_subSpecs">{{ t("common.cancelText") }}</el-button>
            </template>
          </el-space>
          <el-space wrap v-if="LjDetailRef._mainData.parentid > 0">
            <el-button type="primary" @click="gotoMainMattress">查看主规格</el-button>
          </el-space>
        </template>
      </LjVxeTable>
    </template>
  </LjDetail>

  <MtrldefDialog ref="MtrldefDialogRef" v-bind="MtrldefDialogProps" />
  <BednetDialog ref="BednetDialogRef" v-bind="BednetDialogProps" />
  <LjDrawerQuoteList ref="QuoteListDrawerRef" :iforigin="isShowOriginFormulaMattress" @export="handleExportQuote" />
  <AllFormula
    ref="AllFormulaRef"
    :iforigin="isShowOriginFormulaMattress"
    :dannum_type="currentType"
    :formula="cmpFormulas"
    :replace="cmpFormulaReplace"
    :formula_ori="cmpFormulasOri"
    :formula_bednet="cmpFormulasBednet"
    :differ="cmpDiffer"
  />

  <LjDrawer ref="LjDrawerRef" class="lj-drawer-win" size="80%" direction="btt" :title="drawerTitle">
    <BednetDetail
      :mattress-width="LjDetailRef._mainData.mattress_width"
      :mattress-length="LjDetailRef._mainData.mattress_length"
      :ifcopy="ifcopy"
      :ifnotoutper="1"
      v-bind="bednetDrawerProps"
      @aftersave="autoBednetSave"
      @aftercancel="LjDrawerRef.hide()"
    />
  </LjDrawer>
</template>

<script setup lang="ts" name="mattressQuoteEdit">
import { ref, watch, reactive, inject, nextTick, computed, onMounted, getCurrentInstance } from "vue";
import { DwnameEnum } from "@/enums/dwnameEnum";
import LjDetail from "@/components/LjDetail/index.vue";
import { DetailProp } from "@/components/LjDetail/interface";
import { useI18n } from "vue-i18n";
import { useHooks } from "./hooks/index";
import { useHooksCpQuote } from "./hooks/cpQuote";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
import { cloneDeep } from "lodash-es";
import { useRoute, useRouter } from "vue-router";
import { CommonDynamicSelect, GetFormulaCompute } from "@/api/modules/common";
import { SaveMattress, SaveMattressAuditing, DelMattress, GetMattressImportDW2, GetMattressSubspecs } from "@/api/modules/quote";
// import ToastFormula from "@/components/ToastWidget/Formula/index.vue";
import { TYPE, useToast, POSITION } from "vue-toastification";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
// import { calculateFormula } from "@/utils/index";
import MtrldefDialog from "@/views/system/selector/mtrldef/index.vue";
import BednetDialog from "@/views/system/selector/bednet/index.vue";
// import LjDrawerQuoteList from "./components/QuoteList.vue";
import LjDrawerQuoteList from "./components/QuoteListNew.vue";
import mittBus from "@/utils/mittBus";
import { MittEnum } from "@/enums/mittEnum";
import { getCurrentRecords, floatAdd, floatMul, text2Formula } from "@/utils/index";
import { useUserStore } from "@/stores/modules/user";
import AllFormula from "./components/AllFormula.vue";
import LjDrawer from "@/components/LjDrawer/index.vue";
import BednetDetail from "@/views/quote/bednetQuote/detail.vue";
import Statistic from "./components/Statistic.vue";
import variables from "@/styles/js.module.scss";
import { useGlobalStore } from "@/stores/modules/global";

// interface detailProp {
//   // /**
//   //  * @argument any 页面数据
//   //  */
//   // data1?: any;
//   // /**
//   //  * @argument string 请求数据的api ==> 非必传
//   //  */
//   // requestApi?: (params: any) => Promise<any>;
//   // /**
//   //  * @argument any 基础信息，表格展示数据
//   //  */
//   // // columns?: any;
//   // /**
//   //  * @description 是否可编辑
//   //  */
//   // status: "edit" | "new" | string;
// }

// const props = withDefaults(defineProps<detailProp>(), {});
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const globalStore = useGlobalStore();
// const { isShowOriginFormulaMattress } = storeToRefs(globalStore);
const ifcopy = ref(false);

const showOriginFormulaMattress = (value: any) => {
  globalStore.setGlobalState("isShowOriginFormulaMattress", Boolean(value));

  // 刷新页面
  router.go(0);
  // LjDetailRef.value.refresh();
};

const _variables: any = variables;
const {
  columns,
  columnsMx,
  columnsMxBednet,
  columnsMxCushions,
  columnsMxAccessories,
  columnsMxPackag,
  columnsMxInnerClothLayer,
  columnsMx_processes,
  columnsMx_additional,
  LjDetailRef,
  MtrldefDialogRef,
  MtrldefDialogProps,
  BednetDialogRef,
  BednetDialogProps,
  fabricMxTabList,
  mattresstypeEnum,
  fabricMxTabs,
  fabricMxTab8Ref,
  fabricMxTab9Ref,
  fabricMxTab10Ref,
  fabricMxTab11Ref,
  fabricMxTab12Ref,
  fabricMxTab13Ref,
  fabricMxTab8,
  fabricMxTab9,
  fabricMxTab10,
  fabricMxTab11,
  fabricMxTab12,
  fabricMxTab13,
  fabricMx10NewMtrlGroup,
  fabricMx11NewMtrlGroup,
  initParams,
  cushionsMxData,
  fabricMxData,
  accessoriesMxData,
  bednetMxData,
  packagMxData,
  oriMxData,
  orderStatus,
  showFormula,
  QuoteListDrawerRef,
  formulaKindEnum,
  bednetMxRef,
  cushionsMxRef,
  accessoriesMxRef,
  packagMxRef,
  innerClothLayerMxRef,
  topCottonMxRef,
  packtypeOptions,
  woodpallettypeOptions,
  areaOptions,
  cabinetTypeOptions,
  topCottonAddList,
  AllFormulaRef,
  LjDrawerRef,
  cmpFormulas,
  cmpFormulaReplace,
  cmpFormulasOri,
  cmpFormulasBednet,
  cmpDiffer,
  subSpecsRef,
  columnsMx_subSpecs,
  diancengAreaEnum,
  specialProcessesMxRef,
  additionalCostsMxRef,
  specialProcessesMxData,
  additionalCostsMxData,
  specialProcessesMxInitData,
  additionalCostsMxInitData,
  specialProcessesEnum,
  additionalCostsEnum,
  isShowOriginFormulaMattress,
  columnsMx_subSpecs_dis,
  subSpecsData,
  funcAddMxSide,
  funcChaifenTab,
  getData_mx,
  dataCallback,
  dataCallbackMx,
  getMattressType,
  gotoSummy,
  gotoHisprice,
  getFormulakindEnum,
  funcPacktypeChange,
  dynamicRef,
  wf_cmp_cb,
  handleToImportMxInner,
  hanleDelMxInner,
  wf_add_w_butao,
  wf_del_w_butao,
  w_mattress_add_itemname_choose,
  wf_rtr_bednet,
  funcAddMtrlMx,
  resetMergeCellsInner,
  resetMergeCellsTopCotton,
  wf_rtr_cwdc,
  resetSpecialProcesses,
  gotoErpapi,
  updateSubspecsTable
} = useHooks(t);
const { toExcelQuote, toExcelQuoteNew } = useHooksCpQuote();
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);
const { userInfo } = useUserStore();
// const toast = useToast();

// const orderStatus = ref("");
// const mainData = ref([]);
const tabRemove: Function = inject("tabRemove") as Function;

const defaultColumnsValue = ref<any>({});
const mxLoading = ref(false);
const drawerTitle = ref("");
const bednetDrawerProps = reactive({
  bednetid: 0,
  state: "",
  deptid: 0,
  onlyView: false,
  dannum_type: 0
});

const footerMethod = ({ columns, data }: any) => {
  // 返回一个二维数组的表尾合计
  return [
    columns.map((column: any, columnIndex: number) => {
      if (columnIndex === 0) {
        return "合计";
      }
      if (columnIndex === 1) {
        return data.length;
      }
      // if ((column.field && column.field.indexOf("qty") > -1) || props.footerSumAttrs?.includes(column.field)) {
      if ((column.field && column.field.indexOf("qty") > -1) || (column.field && column.field.indexOf("amt") > -1)) {
        let count = 0;
        data.forEach((item: any) => {
          count = floatAdd(count, isNaN(Number(item[column.field])) ? 0 : Number(item[column.field]));
        });
        return count;
      } else if (column.field && column.field.indexOf("dannum") > -1) {
        let count = 0;

        let fieldCost = column.field.split("_");
        let _field = fieldCost[0] + "_cost";

        column.field.indexOf("dannum") > -1;

        data.forEach((item: any) => {
          if (item.hasOwnProperty(_field)) {
            count = floatAdd(count, item[_field]);
          } else {
            count = floatAdd(count, floatMul(Number(item.costamt), 1 + item[column.field]));
          }
        });
        return count;
      }
    })
  ];
};

/**
 * @description 明细表格组件基础配置
 */
const tableProps_mx = ref({
  height: "auto",
  align: "left",
  // height: "",
  minHeight: "100px",
  editConfig: { trigger: "click", mode: "row", enabled: false, autoClear: false },
  // exportConfig: {
  //   filename: t("menu.saleTaskCrmDetail") + formatToDate(new Date(), "YYYY-MM-DDHH:mm:ss")
  // }
  editRules: {
    mattress_width: [
      {
        validator: ({ cellValue, rule, rules, row, rowIndex, column, columnIndex }) => {
          const { _mainData } = LjDetailRef.value;

          let _value = Number(cellValue);
          if (_value < 0) {
            return new Error("不能小于0");
          }
          if (!isNaN(_value) && _value > Number(_mainData.mattress_width)) {
            return new Error("不能大于床垫尺寸");
          }
          return true;
        }
      }
    ],
    mattress_length: [
      {
        validator: ({ cellValue, rule, rules, row, rowIndex, column, columnIndex }) => {
          const { _mainData } = LjDetailRef.value;

          let _value = Number(cellValue);
          if (_value < 0) {
            return new Error("不能小于0");
          }
          if (!isNaN(_value) && _value > Number(_mainData.mattress_length)) {
            return new Error("不能大于床垫尺寸");
          }
          return true;
        }
      }
    ]
  },
  keyboardConfig: {
    isEdit: true,
    isArrow: true,
    isEnter: true,
    isTab: true,
    isDel: true,
    isBack: true,
    isEsc: true,
    editMethod({ $table, row, column }) {
      // 先清空原先的值
      row[column.field] = "";
      // 再激活编辑状态并输入新值
      $table.setEditCell(row, column);
    }
  },
  mouseConfig: {
    selected: true
  }
});

// const tableEventsMx = {
//   "edit-activated": ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) => {
//     console.log("thickness row editDisabled:>> ", row.if_inputqty, row.formulakind);
//     if (column.field === "thickness") {
//       return !(
//         (row.if_inputqty == 0 && [50, 51, 52, 53, 54, 104, 114, 11, 12, 13, 14, 32, 33].includes(row.formulakind)) ||
//         row.formulakind == 7 ||
//         row.formulakind == 202
//       );
//     }
//   },
//   "edit-disabled": ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) => {
//     console.log("thickness row editDisabled:>> ", row.if_inputqty, row.formulakind);
//     if (column.field === "thickness") {
//       return !(
//         (row.if_inputqty == 0 && [50, 51, 52, 53, 54, 104, 114, 11, 12, 13, 14, 32, 33].includes(row.formulakind)) ||
//         row.formulakind == 7 ||
//         row.formulakind == 202
//       );
//     }
//   }
// };

const tableProps_subSpecs = ref({
  height: "auto",
  align: "left",
  // height: "",
  minHeight: "100px",
  editConfig: { trigger: "click", mode: "row", enabled: false, autoClear: false },
  // exportConfig: {
  //   filename: t("menu.saleTaskCrmDetail") + formatToDate(new Date(), "YYYY-MM-DDHH:mm:ss")
  // }
  keyboardConfig: {
    isEdit: true,
    isArrow: true,
    isEnter: true,
    isTab: true,
    isDel: true,
    isBack: true,
    isEsc: true,
    editMethod({ $table, row, column }) {
      // 先清空原先的值
      row[column.field] = "";
      // 再激活编辑状态并输入新值
      $table.setEditCell(row, column);
    }
  },
  mouseConfig: {
    selected: true
  }
});

// const keyboardConfig = ref<any>({
//   isEdit: true,
//   isArrow: true,
//   isEnter: true,
//   isTab: true,
//   isDel: true,
//   isBack: true,
//   isEsc: true,
//   editMethod({ $table, row, column }) {
//     // 先清空原先的值
//     row[column.field] = "";
//     // 再激活编辑状态并输入新值
//     $table.setEditCell(row, column);
//   }
// });

const isTabsBadge_packag = computed(() => {
  let arr = [];
  arr = packagMxData.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0);
  return arr.length;
});
const isTabsBadge_packag_error = computed(() => {
  let arr = [];
  arr = packagMxData.value.filter(t => Number(t.if_success));
  return arr.length;
});

const isTabsBadge_cushions = computed(() => {
  let arr = [];
  arr = cushionsMxData.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0);
  return arr.length;
});
const isTabsBadge_cushions_error = computed(() => {
  let arr = [];
  console.log("isTabsBadge_cushions_error cushionsMxData.value:>> ", cushionsMxData.value);
  arr = cushionsMxData.value.filter(t => Number(t.if_success));
  return arr.length;
});

const isTabsBadge_accessories = computed(() => {
  let arr = [];
  arr = accessoriesMxData.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0);
  return arr.length;
});
const isTabsBadge_accessories_error = computed(() => {
  let arr = [];
  arr = accessoriesMxData.value.filter(t => Number(t.if_success));
  return arr.length;
});

const isTabsBadge_bednet = computed(() => {
  let arr = [];
  const $table = bednetMxRef.value?.element;
  if ($table) {
    arr = $table.getTableData().visibleData.filter(t => t.mtrlid && Number(t.mtrlid) > 0);
  }
  return arr.length;
});
const isTabsBadge_bednet_error = computed(() => {
  let arr = [];
  arr = bednetMxData.value.filter(t => Number(t.if_success));
  return arr.length;
});

const isTabsBadge_fabric = computed(() => {
  let arr = [];
  arr = fabricMxTab8.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0);
  arr = arr.concat(fabricMxTab9.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0));
  arr = arr.concat(fabricMxTab10.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0));
  arr = arr.concat(fabricMxTab11.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0));
  arr = arr.concat(fabricMxTab12.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0));
  arr = arr.concat(fabricMxTab13.value.filter(t => t.mtrlid && Number(t.mtrlid) > 0));
  console.log("isTabsBadge_fabric arr :>> ", arr);
  return arr.length;
});
const isTabsBadge_fabric_error = computed(() => {
  let arr = [];
  arr = fabricMxTab8.value.filter(t => Number(t.if_success));
  arr = arr.concat(fabricMxTab9.value.filter(t => Number(t.if_success)));
  arr = arr.concat(fabricMxTab10.value.filter(t => Number(t.if_success)));
  arr = arr.concat(fabricMxTab11.value.filter(t => Number(t.if_success)));
  arr = arr.concat(fabricMxTab12.value.filter(t => Number(t.if_success)));
  arr = arr.concat(fabricMxTab13.value.filter(t => Number(t.if_success)));
  return arr.length;
});

const isFilterErrorBadge = data => {
  let arr = [];
  arr = data.filter(t => Number(t.if_success));
  return arr.length;
};

const isFilterSucessBadge = data => {
  let arr = [];
  arr = data.filter(t => t.mtrlid && Number(t.mtrlid) > 0);
  return arr.length;
};

const isQuoteListMxData = computed(() => {
  let innerData = [];
  if (innerClothLayerMxRef.value) {
    innerData = innerClothLayerMxRef.value?.element.getTableData()?.visibleData;
  }
  let topCottonData = [];
  if (topCottonMxRef.value) {
    topCottonData = topCottonMxRef.value?.element.getTableData()?.visibleData;
  }
  return [
    {
      label: "面裥绵",
      field: "tabpage_8",
      replace: "面裥绵-",
      data: fabricMxTab8.value
    },
    {
      label: "底裥绵",
      field: "tabpage_9",
      replace: "底裥绵-",
      data: fabricMxTab9.value
    },
    {
      label: "裥大侧",
      field: "tabpage_10",
      replace: "大侧裥绵-",
      data: fabricMxTab10.value
    },
    {
      label: "裥小侧",
      field: "tabpage_11",
      replace: "小侧裥绵-",
      data: fabricMxTab11.value
    },
    {
      label: "裥V侧",
      field: "tabpage_12",
      replace: "V侧裥绵-",
      data: fabricMxTab12.value
    },
    {
      label: "其他工艺",
      field: "tabpage_13",
      replace: "V侧裥绵-",
      data: fabricMxTab13.value
    },
    {
      label: "垫层",
      field: "cushions",
      data: {
        cushions: cushionsMxData.value,
        bednet: bednetMxData.value
      }
    },
    {
      label: "辅料",
      field: "accessories",
      data: accessoriesMxData.value
    },
    {
      label: "包装",
      field: "packag",
      data: packagMxData.value
    },
    {
      label: "内布套",
      field: "innerClothLayerMx",
      data: innerData
    },
    {
      label: "顶布裥棉",
      field: "topCottonMx",
      data: topCottonData
    }
  ];
});

/**
 * @description tab 面料
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
// /**
//  * @description 面料数据
//  */
// const fabricMxData = ref([]);
// const fabricMxTabData = ref([]);
// const fabricMxTabs = ref("fabricMx");

/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description tab 床网
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
// /**
//  * @description 床网数据
//  */
// const bednetMxData = ref([]);

// const getData_cushions = (params: any) => {
//   console.log("getData params :>> ", params);
//   let newParams: any = {};
//   params.pageNum && (newParams.pageindex = params.pageNum);
//   params.pageSize && (newParams.pagesize = params.pageSize);
//   delete params.pageNum;
//   delete params.pageSize;
//   newParams.queryParams = params;
//   console.log("params :>> ", params);
//   newParams.dsname = "web_mattress_mx_dianceng";
//   return CommonDynamicSelect(newParams, DwnameEnum.mattressQuoteMxBednet);
// };
/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description tab 垫层
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
// /**
//  * @description 垫层数据
//  */
// const cushionsMxData = ref([]);

/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description tab 辅料
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
// /**
//  * @description 辅料数据
//  */
// const accessoriesMxData = ref([]);

// const getData_bednet = (params: any) => {
//   console.log("getData params :>> ", params);
//   let newParams: any = {};
//   params.pageNum && (newParams.pageindex = params.pageNum);
//   params.pageSize && (newParams.pagesize = params.pageSize);
//   delete params.pageNum;
//   delete params.pageSize;
//   newParams.queryParams = params;
//   console.log("params :>> ", params);
//   newParams.dsname = "web_mattress_mx_bednet";
//   return CommonDynamicSelect(newParams, DwnameEnum.mattressQuoteMxAccessories);
// };
/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description tab 包装
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
// /**
//  * @description 包装数据
//  */
// const packagMxData = ref([]);

/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description tab 内布套
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
/**
 * @description 内布套数据
 */
// const innerClothLayerMxData = ref([]);
// const innerClothLayerMxRef = ref();
const innerClothLayerNum = computed(() => {
  let arr = [];
  const $table = innerClothLayerMxRef.value?.element;
  if ($table) {
    arr = $table.getTableData().visibleData.filter(t => t.mtrlid && Number(t.mtrlid) > 0);
  }
  return arr.length;
});
const innerClothLayerNum_error = computed(() => {
  let arr = [];
  const $table = innerClothLayerMxRef.value?.element;
  if ($table) {
    arr = $table.getTableData().visibleData.filter(t => Number(t.if_success));
  }
  return arr.length;
});

const getData_innerClothLayer = (params: any) => {
  console.log("getData params :>> ", params);
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  delete params.pageNum;
  delete params.pageSize;
  newParams.queryParams = params;
  newParams.queryParams.arg_formulatype = [101, 102];
  console.log("params :>> ", params);
  newParams.dsname = "web_mattress_mx_neibutao";
  return CommonDynamicSelect(newParams, DwnameEnum.mattressQuoteMxInnerClothLayer);
};
/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description tab 顶部裥棉
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
// const topCottonMxRef = ref();
const topCottonNum = computed(() => {
  let arr = [];
  const $table = topCottonMxRef.value?.element;
  if ($table) {
    arr = $table.getTableData().visibleData.filter(t => t.mtrlid && Number(t.mtrlid) > 0);
  }
  return arr.length;
});
const topCottonNum_error = computed(() => {
  let arr = [];
  const $table = topCottonMxRef.value?.element;
  if ($table) {
    arr = $table.getTableData().visibleData.filter(t => Number(t.if_success));
  }
  return arr.length;
});

const getData_topCotton = async (params: any) => {
  if (!Object.keys(initParams.value).includes("arg_mattressid") || initParams.value.arg_mattressid == 0) return false;
  let _params = { ...params, arg_formulatype: [103] };
  return await getData_mx(_params);
};
/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description 主副规格
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
const subSpecsNum = computed(() => {
  let arr = [];
  const $table = subSpecsRef.value?.element;
  if ($table) {
    arr = $table.getTableData().visibleData;
  }
  return arr.length;
});
const getData_subSpecs = (params?: any) => {
  console.log("getData_subSpecs getData params :>> ", params);
  let newParams: any = {};
  newParams.mattressid = initParams.value.arg_mattressid;
  return GetMattressSubspecs(newParams);
};
const dataCallbackSubspecs = (data: any) => {
  let cols = [];
  let list = data.mattresses.map((item: any, index: any) => {
    let _item = {
      mattress_width: item.mattress_width,
      mattress_length: item.mattress_length,
      mattress_height: item.mattress_height,
      mattressid: item.mattressid,
      mattresscode: item.mattresscode,
      mattressname: item.mattressname,
      mattressrelcode: item.mattressrelcode
    };
    let bednetMxs = data.bednetMxs.filter((t: any) => t.mattressid == item.mattressid);
    console.log("dataCallbackSubspecs bednetMxs :>> ", bednetMxs);
    if (bednetMxs.length > 0) {
      bednetMxs
        .filter(bItem => bItem.mattressid == item.mattressid)
        .map((bItem, idx) => {
          _item["spring_qty_width_" + (idx + 1)] = bItem.spring_qty_width;
          _item["spring_qty_length_" + (idx + 1)] = bItem.spring_qty_length;
          _item["bednet_iffork_" + (idx + 1)] = bItem.bednet_iffork;
          _item["bednet_fork_qty_" + (idx + 1)] = bItem.bednet_fork_qty;
        });
    }

    let mtrlList = data.mtrllist.filter((t: any) => t.mattressid == item.mattressid);
    if (mtrlList.length > 0) {
      mtrlList.map((bItem, idx) => {
        _item["cushions_subspecs_" + (idx + 1)] = bItem.mtrlid;
        _item["cushions_subspecs_formulakind_" + (idx + 1)] = bItem.formulakind;
        _item["cushions_subspecs_mtrlname_" + (idx + 1)] = bItem.mtrlname;
      });
    }
    return _item;
  });

  console.log("list dataCallbackSubspecs:>> ", list, columnsMx_subSpecs);
  // columnsMx_subSpecs_dis.value = columnsMx_subSpecs.concat(cols);
  console.log("list dataCallbackSubspecs:>> ", columnsMx_subSpecs_dis.value);
  return {
    list
    // tableinfo: { columns: columnsMx_subSpecs_dis.value }
  };
};
/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description 特殊工艺
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
const specialProcessesNum = computed(() => {
  let arr = [];
  const $table = specialProcessesMxRef.value?.element;
  if ($table) {
    arr = $table.getTableData().visibleData.filter(t => t.extraid && Number(t.extraid) > 0);
  }
  return arr.length;
});
const getData_specialProcesses = (params: any) => {
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  delete params.pageNum;
  delete params.pageSize;
  newParams.queryParams = params;
  newParams.queryParams.arg_typeid = 1; // 1：特殊工艺 2：额外费用
  console.log("params :>> ", params);
  newParams.dsname = "web_mattress_mx_extra";
  return CommonDynamicSelect(newParams);
};
/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

/**
 * @description 额外费用
 * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 */
const additionalCostsNum = computed(() => {
  let arr = [];
  const $table = additionalCostsMxRef.value?.element;
  if ($table) {
    arr = $table.getTableData().visibleData.filter(t => t.extraid && Number(t.extraid) > 0);
  }
  return arr.length;
});
const getData_additionalCosts = (params: any) => {
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  delete params.pageNum;
  delete params.pageSize;
  newParams.queryParams = params;
  newParams.queryParams.arg_typeid = 2;
  console.log("params :>> ", params);
  newParams.dsname = "web_mattress_mx_extra";
  return CommonDynamicSelect(newParams);
};
/**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */

const detailProps = reactive<DetailProp>({
  dwname: DwnameEnum.mattressQuote,
  columns: columns,
  // headerstatus: ["status", "ifamt_ok"],
  basicDefault: {},
  header: {
    fieldNames: {
      code: "sptcode",
      codeLabel: t("table.u_spt.sptcode") + "：",
      name: "name"
    },
    // icon: "iconclipboard",
    // tabsProp: {
    //   scrollspy: true,
    //   sticky: true
    // }
    floatbtn: [
      {
        id: "oaFlow",
        originLeft: 100,
        originTop: 50
      }
    ]
  },
  mould: [
    {
      id: "fabricMx",
      type: "table",
      label: t("business.detail.fabric")
    },
    {
      id: "bednetMx",
      type: "table",
      label: t("business.detail.bednet")
    },
    {
      id: "cushionsMx",
      type: "table",
      label: t("business.detail.cushions")
    },
    {
      id: "accessoriesMx",
      type: "table",
      label: t("business.detail.accessories")
    },
    {
      id: "packagMx",
      type: "table",
      label: t("business.detail.packag")
    },
    {
      id: "innerClothLayerMx",
      type: "table",
      label: t("business.detail.innerClothLayer"),
      limited: (params: any) => {
        if (!params) return true;
        return !params?.if_n_butao || params?.if_n_butao == "0";
      }
    },
    {
      id: "topCottonMx",
      type: "table",
      label: t("business.detail.topCotton"),
      limited: (params: any) => {
        if (!params) return true;
        return !params?.if_w_butao || params?.if_w_butao == "0";
      }
    },
    {
      id: "specialProcesses",
      type: "table",
      label: t("business.detail.specialProcesses")
    },
    {
      id: "additionalCosts",
      type: "table",
      label: t("business.detail.additionalCosts")
    },
    {
      id: "subSpecs",
      type: "table",
      label: t("business.detail.subSpecs")
    }
  ]
});

const getData = (params: any) => {
  console.log("getData params :>> ", params);
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  delete params.pageNum;
  delete params.pageSize;
  newParams.queryParams = params;
  console.log("params :>> ", params);
  newParams.dsname = "web_mattress";
  return CommonDynamicSelect(newParams, DwnameEnum.mattressQuote);
  // return [];
};

const currentType = ref(1);
const gotoShowFormula = (type: any) => {
  currentType.value = type;
  AllFormulaRef.value.open();
};

const loadingStatus = reactive({
  save: false,
  download: false
});

const save = async () => {
  console.log("save LjDetailRef.value._mainData :>> ", LjDetailRef.value._mainData);
  console.log("save------------ :>> ", loadingStatus.save);
  console.log("save cushionsMxData :>> ", cushionsMxData.value);

  try {
    await LjDetailRef.value.toValidateForm();

    if (!(await wf_cmp_cb())) return;

    let mattress = LjDetailRef.value._mainData;
    mattress.mattressid = Number(mattress.mattressid ?? 0);
    mattress.xd_flag = Number(mattress.xd_flag ?? 0);
    console.log("bbbbbbbbbbbbbbbbbbbb mattress :>> ", mattress);
    // mattress.if_moneyrate = Number(mattress.if_moneyrate ?? 0);
    // mattress.if_bcp_type = Number(mattress.if_bcp_type ?? 0);
    // mattress.if_d_chai = Number(mattress.if_d_chai ?? 0);
    // mattress.if_m_chai = Number(mattress.if_m_chai ?? 0);
    // mattress.if_m_wbutao_way = Number(mattress.if_m_wbutao_way ?? 0);
    // mattress.if_n_butao = Number(mattress.if_n_butao ?? 0);
    // mattress.if_w_butao = Number(mattress.if_w_butao ?? 0);
    // mattress.if_z_chai = Number(mattress.if_z_chai ?? 0);
    // mattress.if_zhedie_type = Number(mattress.if_zhedie_type ?? 0);

    let mattressMx = [];

    try {
      fabricMxTabList.value.map(t => {
        if (t.ref) {
          console.log("t.ref?.value :>> ", t.ref, dynamicRef(t.ref));
          if (dynamicRef(t.ref) && !["specialProcessesMxRef", "additionalCostsMxRef"].includes(t.ref)) {
            let $table = dynamicRef(t.ref)?.element;
            $table.clearEdit();
            let { visibleData } = $table.getTableData();
            console.log("visibleData t.ref?.value :>> ", t.ref, visibleData);
            visibleData = visibleData.map((itm, idx) => {
              // 检查明细输入是否正确
              let _disabled = !(
                (itm.if_inputqty == 0 && [50, 51, 52, 53, 54, 104, 114, 11, 12, 13, 14, 32, 33].includes(itm.formulakind)) ||
                itm.formulakind == 202 ||
                itm.formulakind == 7
              );
              console.log("_disabled :>> ", _disabled);
              if (t.ref == "cushionsMxRef") {
                _disabled = !(
                  (itm.if_inputqty == 0 && [50, 51, 52, 53, 54, 104, 114, 11, 14, 32, 33].includes(itm.formulakind)) ||
                  itm.formulakind == 7 ||
                  itm.formulakind == 999
                );
              } else if (t.ref == "innerClothLayerMxRef") {
                _disabled = !(
                  (itm.if_inputqty == 0 && [50, 51, 52, 53, 54, 104, 114, 11, 14, 32, 33].includes(itm.formulakind)) ||
                  itm.formulakind == 202 ||
                  itm.formulakind == 203
                );
              }
              console.log(
                "itm.mtrlid > 0 && !_disabled && Number(itm.thickness) <= 0 :>> ",
                _disabled,
                itm.mtrlid > 0 && !_disabled && Number(itm.thickness) <= 0
              );
              if (itm.mtrlid > 0 && !_disabled && Number(itm.thickness) <= 0) {
                throw new Error(t.label + "相关厚度输入有误，请检查");
              }

              itm.xu = idx + 1;
              itm.mattress_width = Number(itm?.mattress_width ?? 0);
              itm.mattress_length = Number(itm?.mattress_length ?? 0);
              return itm;
            });

            mattressMx = mattressMx.concat(visibleData);
          }
        }
      });
    } catch (error) {
      ElMessage.error(error.message);
      return false;
    }

    if (orderStatus.value == "copy") {
      mattress.copy_id = mattress.mattressid;
    }

    // 主副规格
    let subspecs = [];
    let $table_subspecs = subSpecsRef.value.element;
    if ($table_subspecs) {
      $table_subspecs.clearEdit();
      subspecs = $table_subspecs.getTableData().visibleData;

      try {
        // 忽略长宽高没填的明细行
        subspecs = subspecs.filter(
          itm => Number(itm.mattress_width) > 0 || Number(itm.mattress_length) > 0 || Number(itm.mattress_height) > 0
        );

        let ifHas99 = mattressMx.filter(itm => itm.formulakind == 99 && itm.mtrlid > 0);
        if (ifHas99.length > 0) {
          subspecs.map(itm => {
            if (Number(itm.mattress_width) <= 0 || Number(itm.mattress_length) <= 0 || Number(itm.mattress_height) <= 0) {
              throw new Error("主副规格相关尺寸输入有误(不能为空)，请输入正数");
            }
            for (const key in itm) {
              if (key.indexOf("spring_qty_") > -1) {
                if (Number(itm[key]) <= 0) {
                  throw new Error("主副规格相关弹簧排列数不能为空，请检查");
                }
              }
            }
          });
        }
      } catch (error) {
        ElMessage.error(error.message);
        return false;
      }
    }

    // 特殊工艺
    let extraProcesses = [];
    let $table_processes = specialProcessesMxRef.value.element;
    if ($table_processes) {
      $table_processes.clearEdit();
      console.log("$table_processes.getTableData() :>> ", $table_processes.getTableData());
      extraProcesses = $table_processes.getTableData().visibleData;
      extraProcesses = extraProcesses.filter(itm => Number(itm.extraid) > 0);
    }

    console.log("save++++extraProcesses :>> ", extraProcesses);

    // 材料额外费用
    let extraCosts = [];
    let $table_costs = additionalCostsMxRef.value.element;
    if ($table_costs) {
      $table_costs.clearEdit();
      extraCosts = $table_costs.getTableData().visibleData;
      extraCosts = extraCosts.filter(itm => Number(itm.extraid) > 0);
    }

    loadingStatus.save = true;
    let _param_mf = {
      mattress,
      mattressMx,
      subspecs,
      extraProcesses,
      extraCosts
    };
    try {
      console.log("综合 _param_mf :>> ", _param_mf);
      await SaveMattress(_param_mf)
        .then(res => {
          ElNotification({
            title: "温馨提示",
            message: t("sys.api.sueccessToSave"),
            type: "success"
          });
          if (res.mattressid) {
            console.log("tabRemove route.fullPath :>> ", route.fullPath);
            // tabRemove(route.fullPath);
            router.replace(`/mattressQuote/detail?id=${res.mattressid}&code=${res.mattresscode}`);
          } else {
            router.replace("/mattressQuote");
          }
          setTimeout(() => {
            let _msg = res.message ?? "";
            if (res.message || res.mxmessage?.length) {
              let defaultNum = res.message ? 1 : 0;
              _msg && (_msg = "1." + _msg + "<br/>");

              if (res.mxmessage?.length) {
                res.mxmessage.map((itm, idx) => {
                  _msg += `${idx + 1 + defaultNum}. ${itm}<br/>`;
                });
              }
              let _num = res.message ? 1 + res.mxmessage?.length : res.mxmessage?.length;
              ElNotification({
                title: `计算失败(${_num})`,
                message: `<div style="word-wrap:break-word;word-break:break-all;">${_msg}</div>`,
                dangerouslyUseHTMLString: true,
                type: "warning"
              });
            }
          }, 100);
          loadingStatus.save = false;
        })
        .catch(error => {
          console.log("error !! :>> ", error);
          loadingStatus.save = false;
        });
    } catch (error) {
      ElMessage.error(t("sys.api.operationFailed"));
    }
  } catch (e) {
    loadingStatus.save = false;
    console.log("buttonNew eee :>> ", e, loadingStatus.save);
  }
};

const orderDefaultAction = [
  buttonDefault({
    label: t("common.cancelText"),
    icon: "iconchevron-left",
    limited: () => {
      return !orderStatus.value;
    },
    clickFunc: item => {
      if (route.path.indexOf("/new") > -1) {
        tabRemove(route.fullPath);
        router.replace("/mattressQuote");
      } else {
        router.replace(
          `/mattressQuote/detail?id=${LjDetailRef.value._mainData.mattressid}&code=${LjDetailRef.value._mainData.mattresscode}`
        );
      }
    }
  }),
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    loading: () => loadingStatus.save,
    limited: () => !orderStatus.value,
    clickFunc: () => save()
  }),
  buttonDefault({
    label: t("common.add"),
    power: 72,
    limited: () => {
      return !!orderStatus.value;
    },
    clickFunc: item => {
      router.push(`/mattressQuote/new?id=0&deptid=${LjDetailRef.value._mainData?.deptid ?? 0}`);
    }
  }),
  buttonDefault({
    power: 72,
    label: t("common.editText"),
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: data => {
      if (data.parentid > 0) {
        return "副规格无法编辑，请在主规格中进行";
      }
      if (data.flag == 1) {
        return "单据已审核，不能修改";
      }
      return "";
    },
    clickFunc: item => {
      router.replace(
        `/mattressQuote/edit?id=${LjDetailRef.value._mainData.mattressid}&code=${LjDetailRef.value._mainData.mattresscode}`
      );
    }
  }),
  buttonDefault({
    power: 77,
    label: t("common.delText"),
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(77)) {
        return "你没有【报价单-删除】的使用权限";
      }
      return "";
    },
    clickFunc: item => {
      console.log("dellll clickFunc item :>> ", LjDetailRef.value);
      ElMessageBox.confirm("是否确定要删除床垫报价单吗?", "询问", {
        confirmButtonText: t("common.delText"),
        cancelButtonText: "否",
        type: "error"
      })
        .then(() => {
          DelMattress({ mattressids: [Number(LjDetailRef.value._mainData.mattressid)] }).then(() => {
            ElMessage.success("删除成功！");

            tabRemove(route.fullPath);
            router.replace("/mattressQuote");
            mittBus.emit(MittEnum.MattressList);
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  // [
  buttonDefault({
    label: t("common.businessOrder"),
    power: 94,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(94)) {
        return `你没有【报价单-${t("common.businessOrder")}】的使用权限`;
      }
      if (data.parentid > 0) {
        return "副规格无法操作，请在主规格中进行";
      }
      return "";
    },
    clickFunc: item => {
      ElMessageBox.confirm("是否确定要业务下单吗?", "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          let _params = {
            mattressids: [Number(LjDetailRef.value._mainData.mattressid)],
            xd_flag: 1
          };
          SaveMattressAuditing(_params).then(() => {
            ElMessage.success(t("sys.api.operationSuccess"));

            LjDetailRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  buttonDefault({
    label: t("common.businessOrderCancel"),
    power: 95,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(95)) {
        return `你没有【报价单-${t("common.businessOrderCancel")}】的使用权限`;
      }
      if (data.parentid > 0) {
        return "副规格无法操作，请在主规格中进行";
      }
      return "";
    },
    clickFunc: item => {
      ElMessageBox.confirm(`是否确定要${t("common.businessOrderCancel")}吗?`, "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          let _params = {
            mattressids: [Number(LjDetailRef.value._mainData.mattressid)],
            xd_flag: 0
          };
          SaveMattressAuditing(_params).then(() => {
            ElMessage.success(t("sys.api.operationSuccess"));

            LjDetailRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  // ],
  // [
  buttonDefault({
    label: t("common.auditFinance"),
    power: 73,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(73)) {
        return `你没有【报价单-${t("common.auditFinance")}】的使用权限`;
      }
      if (data.parentid > 0) {
        return "副规格无法操作，请在主规格中进行";
      }
      if (data.flag == 1) {
        return "已审核";
      }
      return "";
    },
    clickFunc: item => {
      ElMessageBox.confirm(`是否确定要${t("common.auditFinance")}吗?`, "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          let _params = {
            mattressids: [Number(LjDetailRef.value._mainData.mattressid)],
            flag: 1
          };
          SaveMattressAuditing(_params).then(() => {
            ElMessage.success(t("sys.api.operationSuccess"));

            LjDetailRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  buttonDefault({
    label: t("common.withdrawAuditFinance"),
    power: 74,
    limited: () => {
      return !!orderStatus.value;
    },
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(74)) {
        return `你没有【报价单-${t("common.withdrawAuditFinance")}】的使用权限`;
      }
      if (data.parentid > 0) {
        return "副规格无法操作，请在主规格中进行";
      }
      if (data.flag != 1) {
        return "未审核";
      }
      return "";
    },
    clickFunc: item => {
      ElMessageBox.confirm(`是否确定要${t("common.withdrawAuditFinance")}吗?`, "询问", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          let _params = {
            mattressids: [Number(LjDetailRef.value._mainData.mattressid)],
            flag: 0
          };
          SaveMattressAuditing(_params).then(() => {
            ElMessage.success(t("sys.api.operationSuccess"));

            LjDetailRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  // ],
  buttonDefault({
    label: t("common.copyQuote"),
    power: 75,
    limited: () => {
      return !!orderStatus.value;
    },
    clickFunc: item => {
      let _cur = LjDetailRef.value._mainData;

      router.push(`/mattressQuote/copy?id=${_cur.mattressid}&code=${_cur.mattresscode}`);
    }
  }),
  buttonDefault({
    label: t("common.showFormula"),
    disabledTextCallBack: () => {
      return userInfo.usermode == 1 ? "业务员模式不可以查看！" : "";
    },
    clickFunc: item => gotoShowFormula(LjDetailRef.value._mainData.dannum_type)
  }),
  buttonDefault({
    label: t("common.viewHistoricalQuotes"),
    clickFunc: () => {
      console.log("LjDetailRef.value._mainData :>> ", LjDetailRef.value._mainData);
      gotoHisprice(0, { id: LjDetailRef.value._mainData.mattressid, typeid: 1 });
    }
  }),
  buttonDefault({
    label: t("common.showQuoteList"),
    clickFunc: item => {
      let _data = {
        data: LjDetailRef.value._mainData,
        mxdata: isQuoteListMxData.value,
        enumMap: LjDetailRef.value.enumMap,
        fabricMx: fabricMxTabList.value,
        formulakindenum: formulaKindEnum.value,
        dannum_type: LjDetailRef.value._mainData.dannum_type,
        formula: cmpFormulas.value,
        replace: cmpFormulaReplace.value,
        formula_ori: cmpFormulasOri.value,
        formula_bednet: cmpFormulasBednet.value,
        differ: cmpDiffer.value
      };
      QuoteListDrawerRef.value.show(_data);
    }
  }),
  buttonDefault({
    label: t("common.exportQuoteList"),
    loading: () => loadingStatus.download,
    power: 72,
    clickFunc: async item => {
      loadingStatus.download = true;
      let _data = {
        data: LjDetailRef.value._mainData,
        mxdata: isQuoteListMxData.value,
        enumMap: LjDetailRef.value.enumMap,
        fabricMx: fabricMxTabList.value,
        formulakindenum: formulaKindEnum.value,
        differ: cmpDiffer.value
      };
      await toExcelQuote(_data, "床垫报价单_" + LjDetailRef.value._mainData.mattresscode);
      loadingStatus.download = false;
    }
  }),
  buttonDefault({
    label: t("common.businessSupplement"),
    power: 72,
    clickFunc: item => {
      let _cur = LjDetailRef.value._mainData;
      let type = 1;

      gotoErpapi(_cur, type);
    }
  }),
  // buttonDefault({
  //   label: t("common.dataTransmission"),
  //   power: 72,
  //   clickFunc: item => {
  //     router.push(`/mattressQuote/new?id=0`);
  //   }
  // })
  buttonDefault({
    label: t("common.back"),
    clickFunc: item => {
      router.push("/mattressQuote");
    }
  })
];

onMounted(() => {
  console.log("route onMounted:>> ", route);
  console.log("route onMounted:>> ", route.params);
  console.log("route onMounted:>> ", route.params.id);

  if (Number(route.query?.id)) {
    // 赋值主表数据
    // mainData.value = res.datatable.length ? res.datatable[0] : {};
    // console.log("mainData.value :>> ", mainData.value);
    // 刷新数据
    initParams.value.arg_mattressid = Number(route.query?.id);
    console.log("detail onMounted initParams.value :>> ", initParams.value);
  } else {
    if (route.query?.deptid) {
      defaultColumnsValue.value.deptid = Number(route.query?.deptid);
    }
  }
  defaultColumnsValue.value.packtype = "0";
  defaultColumnsValue.value.packqty = 1;
  // defaultColumnsValue.value.woodpallettype = "0";
  // defaultColumnsValue.value.total_cost = 0;
  // defaultColumnsValue.value.nottax_factory_cost = 0;
  // defaultColumnsValue.value.nottax_dept_cost = 0;
  // defaultColumnsValue.value.foreign_cost = 0;
  // defaultColumnsValue.value.fob = 0;
  defaultColumnsValue.value.dannum_type = 2;
  defaultColumnsValue.value.dannum_rate = 1;
  defaultColumnsValue.value.if_moneyrate = "0";
  defaultColumnsValue.value.moneyrate = "1";
  defaultColumnsValue.value.taxrate = 1.07;
  defaultColumnsValue.value.taxes = 1;
  // defaultColumnsValue.value.flag = 0;

  defaultColumnsValue.value.woodpallettype = "0";
  defaultColumnsValue.value.total_hr_cost = "0";
  defaultColumnsValue.value.total_material_cost = "0";
  defaultColumnsValue.value.total_hr_cost = 0;
  defaultColumnsValue.value.total_material_cost = 0;
  defaultColumnsValue.value.total_fees_cost = 0;
  defaultColumnsValue.value.total_cost = 0;
  defaultColumnsValue.value.commissionrate = 0;
  defaultColumnsValue.value.fob = 0;
  defaultColumnsValue.value.profitrate = 0;
  defaultColumnsValue.value.nottax_factory_cost = 0;
  defaultColumnsValue.value.nottax_dept_cost = 0;
  defaultColumnsValue.value.dept_cost = 0;
  defaultColumnsValue.value.foreign_cost = 0;
  defaultColumnsValue.value.diameter = 0;
  defaultColumnsValue.value.area = "";
  defaultColumnsValue.value.cabinet_type = "";
  defaultColumnsValue.value.hrcost = 0;
  defaultColumnsValue.value.biandaicost = 0;
  defaultColumnsValue.value.flag = 0;
  defaultColumnsValue.value.dept_profitrate_rangli = 0;
  defaultColumnsValue.value.profitrate_point = 0;
  defaultColumnsValue.value.chaizhuang_point = 0;
  defaultColumnsValue.value.haimian_point = 0;
  defaultColumnsValue.value.qr_auditingdate = "";
  defaultColumnsValue.value.zhizao_amt = 0;
  defaultColumnsValue.value.foreign_cost_bz = 0;
  defaultColumnsValue.value.cubage = 0;
  defaultColumnsValue.value.discount = 1;
  defaultColumnsValue.value.butao_point = 1;
  defaultColumnsValue.value.guanli_rate = 1;
  defaultColumnsValue.value.if_bcp_type = 0;
  defaultColumnsValue.value.if_d_chai = 0;
  defaultColumnsValue.value.if_m_chai = 0;
  defaultColumnsValue.value.if_m_wbutao_way = 0;
  defaultColumnsValue.value.if_n_butao = 0;
  defaultColumnsValue.value.if_w_butao = 0;
  defaultColumnsValue.value.if_z_chai = 0;
  defaultColumnsValue.value.if_zhedie_type = 0;

  console.log("defaultColumnsValue.value :>> ", route.query?.deptid, defaultColumnsValue.value);

  getFormulakindEnum();
});

/**
 * @description 页面数据加载完成
 */
const funcAfterMound = async () => {
  console.log("onMounted detail sale start!!!! :>> ", orderStatus.value, orderStatus.value != "new");
  if (route.fullPath.indexOf("/copy?") > -1) {
    LjDetailRef.value._mainData.mattresscode = "";
  }

  if (!orderStatus.value) {
    // 详情页
  } else {
    // 新增/编辑
    tableProps_mx.value.editConfig.enabled = true;
    tableProps_subSpecs.value.editConfig.enabled = true;

    topCottonAddList.value = w_mattress_add_itemname_choose(4);
  }

  console.log("onMounted detail sale start LjDetailRef.value.mainData :>> ", LjDetailRef.value);

  if (orderStatus.value != "new") {
    mxLoading.value = true;
    getMattressType();

    let res = await getData_mx(initParams.value);
    oriMxData.value = dataCallbackMx(res);
    oriMxData.value.list = oriMxData.value.list.map(t => {
      t.formulakind = Number(t.formulakind);
      t.thickness = Number(t.thickness);
      t.qty = Number(t.qty);
      return t;
    });

    let _params = {
      mattressid: Number(initParams.value.arg_mattressid),
      mattresstypeid: 0,
      ifbcptype: 0,
      packtype: 0
    };
    let resDw2 = await GetMattressImportDW2(_params);
    if (resDw2) {
      diancengAreaEnum.value = resDw2?.diancengarea;

      specialProcessesMxData.value = resDw2?.extraEnum.filter(t => t.typeid == 1);
      additionalCostsMxData.value = resDw2?.extraEnum.filter(t => t.typeid == 2);

      specialProcessesEnum.value = resDw2?.extraTypeEnum.filter(t => t.typeid == 1);
      additionalCostsEnum.value = resDw2?.extraTypeEnum.filter(t => t.typeid == 2);
    }

    console.log("funcAfterMound oriMxData.value :>> ", oriMxData.value);

    funcChaifenTab();
    mxLoading.value = false;

    nextTick(() => {
      console.log("detail onMounted subSpecsRef.value :>> ", subSpecsRef.value);
      // subSpecsRef.value.refresh();
      getData_subSpecs().then(res => {
        const { list } = dataCallbackSubspecs(res);
        subSpecsData.value = list;
        console.log("detail onMounted subSpecsRef.value getData_subSpecs:>> ", res, subSpecsData.value);

        updateSubspecsTable();
      });

      gotoSummy();
    });
  }
};

const handleSelFabricMxNewMtrlGroup = async (target: string, item: any) => {
  console.log("handleSelFabricMxNewMtrlGroup target :>> ", target, item, fabricMxTab10.value);
  if (target == "tabpage_10") {
    // 裥大恻
    const $table = fabricMxTab10Ref.value.element;
    const { visibleData } = $table.getTableData();
    let hasSame = visibleData.findIndex(t => t.sortcode == item.label);
    if (hasSame > -1) {
      ElMessage.error(item.label + "已存在");
      return false;
    }

    if ($table) {
      let _arr = [];
      if (item.label == "普通大侧") {
        $table.remove();
      } else {
        visibleData.map(t => {
          if (t.sortcode == "普通大侧") {
            _arr.push(t);
          }
        });
        $table.remove(_arr);
      }
    }

    let _params = {
      arg_array_formulakind: [2, 42, 52, 62, 72, 82],
      arg_array_formulatype: [0, 1, 2, 3]
    };
    await funcAddMxSide(_params, item, fabricMxTab10Ref.value);

    autoLoadExtraData(fabricMxTab10Ref.value, specialProcessesMxRef.value);
  } else if (target == "tabpage_11") {
    // 裥小恻
    const $table = fabricMxTab11Ref.value.element;
    const { visibleData } = $table.getTableData();
    let hasSame = visibleData.findIndex(t => t.sortcode == item.label);
    if (hasSame > -1) {
      ElMessage.error(item.label + "已存在");
      return false;
    }

    if ($table) {
      let _arr = [];
      visibleData.map(t => {
        if (t.sortcode == "小侧1") {
          _arr.push(t);
        }
      });
      $table.remove(_arr);
    }

    let _params = {
      arg_array_formulakind: [3, 83, 43, 53, 63, 73],
      arg_array_formulatype: [0, 1, 2, 3]
    };
    await funcAddMxSide(_params, item, fabricMxTab11Ref.value);
  }
};

/**
 * @description 判断目前选择的拼接数据量，自动导入修改特殊工艺费用
 */
const autoLoadExtraData = (tableRef?: any, targetRef?: any) => {
  //计算拼侧数量

  const $table = tableRef.element;
  const { visibleData } = $table.getTableData();
  const $tableTarget = targetRef.element;
  const { visibleData: tgVisibleData } = $tableTarget.getTableData();

  let arr = [];
  // 收集拼侧，并去重
  visibleData.map(t => arr.push(t.sortcode));
  arr = Array.from(new Set(arr));

  //
  let _remove = [];
  tgVisibleData.map(t => {
    if (t.extraid == 1) {
      _remove.push(t);
    }
  });
  $tableTarget.remove(_remove);
  if (!arr.includes("普通大侧")) {
    let result = [];
    result = result.concat(computedExtraSizeNum(specialProcessesMxData.value, arr, "上下"));
    result = result.concat(computedExtraSizeNum(specialProcessesMxData.value, arr, "左右"));

    console.log("autoLoadExtraData result :>> ", result);

    if (result.length) {
      let _arr = [];
      let _mattressId = LjDetailRef.value._mainData.mattressid;
      result.map(o => {
        let _itm = {
          mattressid: _mattressId,
          mattressmxid: 0,
          extraid: o.extraid,
          extramxid: o.extramxid,
          // extratypename: "",
          extraname: o.extramxname,
          price: o.price,
          qty: o.qty,
          dscrp: o.dscrp,
          inputtype: o.inputtype,
          typeid: o.typeid
        };
        _arr.push(_itm);
      });
      $tableTarget.insertAt(_arr, -1);
    }
  }
};

/**
 * @description 计算拼侧数量
 */
const computedExtraSizeNum = (enumarr: any, arr: any, key: string) => {
  console.log("computedExtraSizeNum specialProcessesEnum.value :>> ", enumarr);
  let extraArr = enumarr.filter(item => item.typeid == 1 && item.extraid == 1 && item.extramxname.includes(key));

  let arrNum = arr.filter(item => item.includes(key)).length;

  let result = [];
  extraArr.forEach(o => {
    // 判断名称中出现的数量
    try {
      const checker = new Function("value", `return ${text2Formula(o.extramxname)};`);

      if (checker(arrNum)) {
        result.push(o);
      }
    } catch (error) {
      console.log("error :>> ", error);
      ElMessage.error(`${t("sys.api.operationFailed")}特殊工艺名称: ${error}`);
    }
  });

  return result;
};

const handleDelFabricMxNewMtrlGroup = (target: string) => {
  let sameMx = [];
  let $table = null;
  if (target == "tabpage_10") {
    $table = fabricMxTab10Ref.value.element;
  } else if (target == "tabpage_11") {
    $table = fabricMxTab11Ref.value.element;
  }

  if ($table) {
    const curRow = $table.getCurrentRecord();
    let { visibleData } = $table.getTableData();

    if (!curRow) {
      ElMessage.warning("请先选择要删除的行");
      return;
    }

    sameMx = visibleData.filter(t => t.sortcode == curRow.sortcode);

    ElMessageBox.confirm(`是否确定要删除${sameMx.length}条明细吗?`, "询问：" + sameMx[0].sortcode, {
      confirmButtonText: t("common.delText"),
      cancelButtonText: "否",
      type: "error"
    })
      .then(() => {
        if (target == "tabpage_10") {
          let _arr = [];
          let _idx = [];
          visibleData.map((t, idx) => {
            if (t.sortcode == sameMx[0].sortcode) {
              _arr.push(t);
              _idx.push(idx);
            }
          });
          $table.remove(_arr);

          fabricMxTab10.value = visibleData.filter((t, idx) => !_idx.includes(idx));

          autoLoadExtraData(fabricMxTab10Ref.value, specialProcessesMxRef.value);
        } else if (target == "tabpage_11") {
          let _arr = [];
          let _idx = [];
          fabricMxTab11.value.map((t, idx) => {
            if (t.sortcode == sameMx[0].sortcode) {
              _arr.push(t);
              _idx.push(idx);
            }
          });
          $table.remove(_arr);

          fabricMxTab11.value = visibleData.filter((t, idx) => !_idx.includes(idx));
        }
      })
      .catch((e: TypeError) => {
        console.log("e :>> ", e);
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  }
};

const moveData = async ($table: any, index: number, nextIndex: number) => {
  let { visibleData } = $table.getTableData();
  const curRecords = $table?.getCurrentRecord();

  let prevRow = visibleData[nextIndex];
  visibleData[nextIndex] = visibleData[index];
  visibleData[index] = prevRow;

  $table.reloadData(visibleData);
  await $table.setCurrentRow(curRecords);
};

const fMoveFormBednetMxToCushionsMx = ($table: any, curIdx: number, action: number) => {
  let curRecords = $table?.getCurrentRecord();
  let visibleData = $table.getTableData().visibleData;

  const $table_cushions = dynamicRef("cushionsMxRef")?.element;
  const { visibleData: visibleData_cushions } = $table_cushions.getTableData();
  let currentBednetIndex = $table.getRowSeq(curRecords);
  console.log("wf_rtr_cwdc cur currentBednetIndex:>> ", currentBednetIndex);
  let index = 1;
  visibleData_cushions.map(o => {
    if (Number(o.formulakind) == 999) {
      if (index == currentBednetIndex) {
        curRecords = o;
      }
      index++;
    }
  });

  index = 1;
  let oNextRecordes = visibleData[curIdx - action];
  currentBednetIndex = $table.getRowSeq(oNextRecordes);
  console.log("wf_rtr_cwdc next currentBednetIndex:>> ", currentBednetIndex);
  let nextRecords = null;
  visibleData_cushions.map(o => {
    if (Number(o.formulakind) == 999) {
      if (index == currentBednetIndex) {
        nextRecords = o;
      }
      index++;
    }
  });

  console.log("wf_rtr_cwdc table_cushions :>> ", $table_cushions.getRowSeq(curRecords), $table_cushions.getRowSeq(nextRecords));
  curIdx = visibleData_cushions.findIndex(t => t === curRecords);
  let nextIdx = visibleData_cushions.findIndex(t => t === nextRecords);

  console.log("wf_rtr_cwdc  curIdx, nextIdx :>> ", curIdx, nextIdx);
  moveData($table_cushions, curIdx, nextIdx);
};

const fMoveFormCushionsMxToBednetMx = ($table: any, curIdx: number, action: number) => {
  let curRecords = $table?.getCurrentRecord();
  let visibleData = $table.getTableData().visibleData;
  let nextIdx = -1;
  let oNextRecordes = visibleData[curIdx - action];

  const $table_bednet = dynamicRef("bednetMxRef")?.element;
  const { visibleData: visibleData_cushions } = $table_bednet.getTableData();
  let currentBednetIndex = $table.getRowSeq(curRecords);
  console.log("wf_rtr_cwdc cur currentBednetIndex:>> ", currentBednetIndex);
  let index = -1;
  curIdx = 0;
  visibleData.map((o, idx) => {
    if (Number(o.formulakind) == 999) {
      index++;
      if (idx + 1 == currentBednetIndex) {
        curIdx = index;
      }
    }
  });

  index = -1;
  currentBednetIndex = $table.getRowSeq(oNextRecordes);
  console.log("wf_rtr_cwdc next currentBednetIndex:>> ", currentBednetIndex);
  let nextRecords = null;
  visibleData.map((o, idx) => {
    if (Number(o.formulakind) == 999) {
      index++;
      if (idx + 1 == currentBednetIndex) {
        nextIdx = index;
      }
    }
  });

  // console.log("wf_rtr_cwdc table_cushions :>> ", $table_bednet.getRowSeq(curRecords), $table_bednet.getRowSeq(nextRecords));
  // curIdx = visibleData_cushions.findIndex(t => t === curRecords);
  // let nextIdx = visibleData_cushions.findIndex(t => t === nextRecords);

  console.log("wf_rtr_cwdc  curIdx, nextIdx :>> ", curIdx, nextIdx);
  if (curIdx > -1 && nextIdx > -1) {
    moveData($table_bednet, curIdx, nextIdx);
  }
};

const toMove = async (action: number, tableName: string) => {
  console.log("bvtoMove action :>> ", action);
  // const { $table, curRecords } = getCurrentRecords(cushionsMxRef.value);
  const $table = dynamicRef(tableName)?.element;
  let curRecords = $table?.getCurrentRecord();
  console.log("curRecords :>> ", curRecords);

  console.log("$table.getTableData() :>> ", $table.getTableData());
  let visibleData = $table.getTableData().visibleData;

  if (!curRecords) {
    ElMessage.warning("请先选择要移动的行");
    return;
  }

  let curIdx = visibleData.findIndex(t => t === curRecords);
  console.log("curIdx :>> ", curIdx);

  if (action == 1) {
    // 上移
    if (curIdx == 0) {
      ElMessage.warning("已经是第一条了");
      return;
    }
    // let prevRow = visibleData[curIdx - 1];
    // visibleData[curIdx - 1] = visibleData[curIdx];
    // visibleData[curIdx] = prevRow;

    // $table.reloadData(visibleData);
    // await $table.setCurrentRow(curRecords);
    moveData($table, curIdx, curIdx - 1);

    // 床网与垫层互联
    if (tableName == "bednetMxRef") {
      fMoveFormBednetMxToCushionsMx($table, curIdx, action);
      // const $table_cushions = dynamicRef("cushionsMxRef")?.element;
      // const { visibleData: visibleData_cushions } = $table_cushions.getTableData();
      // let currentBednetIndex = $table.getRowSeq(curRecords);
      // console.log("wf_rtr_cwdc cur currentBednetIndex:>> ", currentBednetIndex);
      // let index = 1;
      // visibleData_cushions.map(o => {
      //   if (Number(o.formulakind) == 999) {
      //     if (index == currentBednetIndex) {
      //       curRecords = o;
      //     }
      //     index++;
      //   }
      // });

      // index = 1;
      // let oNextRecordes = visibleData[curIdx - 1];
      // currentBednetIndex = $table.getRowSeq(oNextRecordes);
      // console.log("wf_rtr_cwdc next currentBednetIndex:>> ", currentBednetIndex);
      // let nextRecords = null;
      // visibleData_cushions.map(o => {
      //   if (Number(o.formulakind) == 999) {
      //     if (index == currentBednetIndex) {
      //       nextRecords = o;
      //     }
      //     index++;
      //   }
      // });

      // console.log(
      //   "wf_rtr_cwdc table_cushions :>> ",
      //   $table_cushions.getRowSeq(curRecords),
      //   $table_cushions.getRowSeq(nextRecords)
      // );
      // curIdx = visibleData_cushions.findIndex(t => t === curRecords);
      // let nextIdx = visibleData_cushions.findIndex(t => t === nextRecords);

      // console.log("wf_rtr_cwdc  curIdx, nextIdx :>> ", curIdx, nextIdx);
      // moveData($table_cushions, curIdx, nextIdx);
    } else if (tableName == "cushionsMxRef") {
      fMoveFormCushionsMxToBednetMx($table, curIdx, action);
    }
  } else if (action == -1) {
    // 下移
    if (curIdx == visibleData.length - 1) {
      ElMessage.warning("已经是最后一条了");
      return;
    }
    // let nextRow = visibleData[curIdx + 1];
    // visibleData[curIdx + 1] = visibleData[curIdx];
    // visibleData[curIdx] = nextRow;
    moveData($table, curIdx, curIdx + 1);

    // $table.reloadData(visibleData);
    // await $table.setCurrentRow(curRecords);

    // 床网与垫层互联
    if (tableName == "bednetMxRef") {
      fMoveFormBednetMxToCushionsMx($table, curIdx, action);
    } else if (tableName == "cushionsMxRef") {
      fMoveFormCushionsMxToBednetMx($table, curIdx, action);
    }
  }

  // 床网与主副规格互联
  nextTick(() => {
    updateSubspecsTable();
  });
};

/**
 * @description 垫层：增加明细
 */
const toAddMx_cushions = async (type: number) => {
  const { $table, curRecords } = getCurrentRecords(cushionsMxRef.value);
  const row = curRecords[0];
  const { visibleData } = $table.getTableData();
  let newRow;

  if ($table) {
    const records = {
      chastr: row.chastr,
      formulatype: row.formulatype,
      if_mtrl: row.if_mtrl,
      formulaid: row.formulaid,
      sortcode: row.sortcode,
      formulakind: row.formulakind,
      formula: row.formula,
      thickness: 0,
      mtrlid: 0
    };
    if (type) {
      // 插入
      const curIndex = visibleData.findIndex(t => t._X_ROW_KEY === row._X_ROW_KEY);

      // 插入数据
      visibleData.splice(curIndex + 1, 0, records); // 假设 records 是要插入的新数据
      $table.loadData(visibleData); // 重新加载数据

      newRow = records;
    } else {
      // 新增
      const { row } = await $table.insertAt(records, -1);
      newRow = row;
    }

    // await $table.setEditCell(newRow, "mtrlname");
    await $table.setCurrentRow(newRow);

    console.log("wf_rtr_cwdc  formulakind :>> ", row, row.formulakind);
    if (row.formulakind == 999) {
      const $table_bednet = bednetMxRef.value.element;
      if ($table_bednet) {
        const { visibleData: visibleData_bednet } = $table_bednet.getTableData();
        let curIndex = visibleData_bednet.length - 1;
        if (type) {
          curIndex = visibleData.filter(t => t.formulakind == 999).findIndex(t => t._X_ROW_KEY === row._X_ROW_KEY);
        }
        funcAddMtrlMx({ row: visibleData_bednet[curIndex] }, null, "bednetMxRef");
      }
    }
  }
};

/**
 * @description 垫层：删除
 */
const toDelMx_cushions = () => {
  const { $table, curRecords } = getCurrentRecords(cushionsMxRef.value);
  ElMessageBox.confirm(`是否确定要删除明细吗?`, "询问", {
    confirmButtonText: t("common.delText"),
    cancelButtonText: "否",
    type: "error"
  })
    .then(() => {
      if (curRecords.length == 1 && Number(curRecords[0].formulakind) == 999) {
        wf_rtr_bednet(curRecords[0]);
      }
      $table.removeCurrentRow();
      nextTick(() => {
        // 床网与主副规格互联
        updateSubspecsTable();
      });
    })
    .catch((e: TypeError) => {
      console.log("e :>> ", e);
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

const handleAddBednetMx = () => {
  nextTick(() => {
    console.log("LjDetailRef.value._mainData :>> ", LjDetailRef.value._mainData);
    drawerTitle.value = "新增床网报价";
    bednetDrawerProps.deptid = LjDetailRef.value._mainData.deptid;
    bednetDrawerProps.bednetid = 0;
    bednetDrawerProps.state = "new";
    bednetDrawerProps.onlyView = false;

    ifcopy.value = false;
    LjDrawerRef.value.show(true);
  });
};

const handleEditBednetMx = () => {
  const $table = bednetMxRef.value.element;

  if ($table) {
    const { $table, curRecords } = getCurrentRecords(bednetMxRef.value);
    if (curRecords) {
      const records = curRecords[0];
      if (!Number(records?.mtrlid)) {
        handleAddBednetMx();
      } else {
        nextTick(() => {
          drawerTitle.value = "修改床网报价";
          bednetDrawerProps.deptid = LjDetailRef.value._mainData.deptid;
          bednetDrawerProps.bednetid = records.mtrlid;
          bednetDrawerProps.dannum_type = LjDetailRef.value._mainData.dannum_type;
          bednetDrawerProps.state = "edit";
          bednetDrawerProps.onlyView = false;

          ifcopy.value = true;
          LjDrawerRef.value.show(true);
        });
      }
    }
  }
};

const autoBednetSave = async (res: any, oldBednetid: number) => {
  const $table = bednetMxRef.value.element;

  let _res = res.bednet;
  _res.bednet_height = res.bednet.mattress_height;
  if ($table) {
    const { visibleData } = $table.getTableData();
    let idx = visibleData.findIndex(t => t.mtrlid == oldBednetid || oldBednetid == 0);
    let _mtrlname =
      _res.typename + " " + _res.bednetcode + " " + _res.mattress_width + "*" + _res.mattress_length + "*" + _res.mattress_height;
    if (idx > -1) {
      visibleData[idx].mtrlid = _res.bednetid;
      visibleData[idx].mtrlname = _mtrlname;
      visibleData[idx].price = _res.total_cost;
      visibleData[idx].qty = 1;

      await $table.reloadData(visibleData);

      wf_rtr_cwdc(visibleData[idx], _res, "set");
    } else {
      let _data = cloneDeep(visibleData[0]);
      let _row = {
        addmx: "+",
        delmx: "-",
        formulatype: _data.formulatype,
        if_mtrl: _data.if_mtrl,
        formulaid: _data.formulaid,
        sortcode: _data.sortcode,
        formulakind: _data.formulakind,
        formula: _data.formula,
        thickness: 0,
        mtrlid: _res.bednetid,
        mtrlname: _mtrlname,
        price: _res.total_cost,
        qty: 1
      };

      await $table.insertAt(_row, -1);

      wf_rtr_cwdc(_row, _res, "add");
    }
  }

  LjDrawerRef.value.hide();
};

/**
 * @description 设置上次激活的标签页
 * @param type 类型
 * @param data 数据
 */
const SetCurrentTabs = (data: any) => {
  let _dwname = detailProps.dwname + "__fabric";
  let _dftabs = globalStore?.detailtabs ?? {};
  _dftabs[_dwname] = data.paneName;
  globalStore.setGlobalState("mattresTabs", _dftabs);
};

/**
 * @description 新增主副规格
 */
const toAddMx_subSpecs = async () => {
  const $table = subSpecsRef.value.element;
  if ($table) {
    // updateSubspecsTable();

    console.log("$table.getTable :>> ", $table.getTableData());
    const $tableCushions = cushionsMxRef.value.element;
    let cushionsAttr = {};
    if ($tableCushions) {
      let idx = 0;
      const { visibleData: visibleData_cushions } = $tableCushions.getTableData();
      visibleData_cushions.map(item => {
        if (item.mtrlid > 0 && item.if_subspecs == 1) {
          cushionsAttr["cushions_subspecs_" + (idx + 1)] = item.mtrlid;
          cushionsAttr["cushions_subspecs_formulakind_" + (idx + 1)] = item.formulakind;
          cushionsAttr["cushions_subspecs_mtrlname_" + (idx + 1)] = item.mtrlname;

          idx++;
        }
      });
    }

    let records = {
      mattressid: 0,
      mattresscode: "",
      mattress_width: 0,
      mattress_length: 0,
      mattress_height: LjDetailRef.value._mainData.mattress_height,
      mattressname: LjDetailRef.value._mainData.mattressname,
      mattressrelcode: LjDetailRef.value._mainData.mattressrelcode
      // spring_qty_length: 0,
      // spring_qty_width: 0
    };
    for (const key in cushionsAttr) {
      records[key] = cushionsAttr[key];
    }
    const { row: newRow } = await $table.insertNextAt(records, -1);
    await $table.setEditCell(newRow, "mattress_width");
    await $table.setCurrentRow(newRow);
  }
};

/**
 * @description 删除主副规格
 */
const toDelMx_subSpecs = () => {
  const { $table, curRecords } = getCurrentRecords(subSpecsRef.value);
  if ($table) {
    $table.remove(curRecords);
  }
};

/**
 * @description 审核后，修改主副规格
 */
const editSubSpecs = ref(false);

const toEdit_subSpecs = () => {
  editSubSpecs.value = true;

  tableProps_subSpecs.value.editConfig.enabled = true;
};

const toCancel_subSpecs = () => {
  editSubSpecs.value = false;
  subSpecsRef.value.refresh();
};

const toSave_subSpecs = async () => {
  await save();

  editSubSpecs.value = false;
};

const gotoMainMattress = () => {
  if (globalStore.detailBlank) {
    // 打开新的窗口
    const routeUrl = router.resolve({
      path: `/mattressQuote/detail`,
      query: {
        id: LjDetailRef.value._mainData.parentid
        // code: row.mattresscode
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    router.push(`/mattressQuote/detail?id=${LjDetailRef.value._mainData.parentid}`);
  }
};

const handleDBlClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  if (orderStatus.value || editSubSpecs.value) return false;
  if (globalStore.detailBlank) {
    // 打开新的窗口
    const routeUrl = router.resolve({
      path: `/mattressQuote/detail`,
      query: {
        id: row.mattressid,
        code: row.mattresscode
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    router.push(`/mattressQuote/detail?id=${row.mattressid}&code=${row.mattresscode}`);
  }
};

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

const handleCellDblClick_bednet = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  if (!orderStatus.value && row.mtrlid > 0) {
    drawerTitle.value = "床网报价详情";
    // bednetDrawerProps.deptid = LjDetailRef.value._mainData.deptid;
    bednetDrawerProps.dannum_type = LjDetailRef.value._mainData.dannum_type;
    bednetDrawerProps.bednetid = row.mtrlid;
    bednetDrawerProps.deptid = LjDetailRef.value._mainData.deptid;
    bednetDrawerProps.state = "";
    bednetDrawerProps.onlyView = true;
    LjDrawerRef.value.show(true);
  }
};

const cmpMoneyrate = computed(() => {
  return LjDetailRef.value?._mainData.moneyrate ?? 0;
});
const cmpIfMoneyrate = computed(() => {
  return LjDetailRef.value?._mainData.if_moneyrate ?? 0;
});

const handleExportQuote = async (ifExpandAll: any, ifShowOrigin: any, fields: any) => {
  console.log("handleExportQuote ifExpandAll :>> ", ifExpandAll, ifShowOrigin);
  if (ifShowOrigin) {
    loadingStatus.download = true;
    let _data = {
      data: LjDetailRef.value._mainData,
      mxdata: isQuoteListMxData.value,
      enumMap: LjDetailRef.value.enumMap,
      fabricMx: fabricMxTabList.value,
      formulakindenum: formulaKindEnum.value,
      differ: cmpDiffer.value
    };
    await toExcelQuote(_data, "床垫报价单_" + LjDetailRef.value._mainData.mattresscode);
    loadingStatus.download = false;
  } else {
    loadingStatus.download = true;
    // let _data = {
    //   data: LjDetailRef.value._mainData,
    //   mxdata: isQuoteListMxData.value,
    //   enumMap: LjDetailRef.value.enumMap,
    //   fabricMx: fabricMxTabList.value,
    //   formulakindenum: formulaKindEnum.value,
    //   differ: cmpDiffer.value,
    //   fields: fields
    // };
    let _data = {
      data: LjDetailRef.value._mainData,
      mxdata: isQuoteListMxData.value,
      enumMap: LjDetailRef.value.enumMap,
      fabricMx: fabricMxTabList.value,
      formulakindenum: formulaKindEnum.value,
      dannum_type: LjDetailRef.value._mainData.dannum_type,
      formula: cmpFormulas.value,
      replace: cmpFormulaReplace.value,
      formula_ori: cmpFormulasOri.value,
      formula_bednet: cmpFormulasBednet.value,
      differ: cmpDiffer.value,
      fields: fields
    };
    await toExcelQuoteNew(_data, "床垫报价单_" + LjDetailRef.value._mainData.mattresscode, ifExpandAll);
    loadingStatus.download = false;
  }
};

// const autoTabsClicks = (data: any) => {
//   console.log("autoTabsClicks data :>> ", data);

//   if (data.name == "subspecs") {
//     updateSubspecsTable();
//   }
// };
</script>

<style lang="scss">
.select-text-right {
  .el-select__wrapper {
    text-align: right;
  }
}
.fabric-mx-tabs {
  .el-tabs__content {
    flex: 1;
  }
  .el-tab-pane {
    display: flex;
    flex-direction: column;
  }
}
</style>
