<template>
  <div class="app-container">
    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb10">
      <svg-icon
        v-show="queryParams.signStatus === 1"
        icon-class="signed"
        class-name="card-icon-signed"
      />
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:synthetical-send-resource:query']"
          type="primary"
          size="mini"
          :disabled="queryParams.signStatus === 1"
          @click="handleGenerateSupport"
        >新增支援</el-button>
        <!-- <el-button
          v-hasPermi="['wms:synthetical-send-master:create']"
          size="mini"
          type="primary"
          :disabled="queryDisabled"
          @click="handleSubmit"
        >提交</el-button> -->
        <el-button
          v-hasPermi="['wms:synthetical-send-master:update']"
          size="mini"
          type="primary"
          :disabled="queryParams.signStatus === 1"
          @click="handleSign"
        >签收</el-button>
        <el-tooltip
          class="item"
          effect="dark"
          content="只打印有拆分的标签"
          placement="top"
        >
          <el-button
            v-hasPermi="['wms:synthetical-send-master:update']"
            size="mini"
            type="primary"
            @click="handleRepair"
          >标签补打</el-button>
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          content="打印所有发料的标签，包括拆分出来未发料的"
          placement="top"
        >
          <el-button
            size="mini"
            type="primary"
            @click="handleBatchRepair"
          >批量打印</el-button>
        </el-tooltip>
      </el-col>
    </el-row>

    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
      :disabled="queryDisabled"
    >
      <el-row v-if="queryParams !== null" :gutter="10">
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="queryParams.remark"
              placeholder="请输入备注"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            v-show="
              $route.query.masterId !== null &&
                $route.query.masterId !== undefined
            "
            label="开单时间"
            prop="createTime"
          >
            <el-input
              v-model="queryParams.createTime"
              placeholder="请输入开单时间"
              clearable
              style="width: 115px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            v-show="
              $route.query.masterId !== null &&
                $route.query.masterId !== undefined
            "
            label="备料单号"
            prop="prepareOrderNo"
          >
            <el-input
              v-model="queryParams.prepareOrderNo"
              placeholder="请输入备料单号"
              clearable
              style="width: 140px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-input
            v-show="
              $route.query.masterId !== null &&
                $route.query.masterId !== undefined &&
                queryParams.signStatus === 1
            "
            v-model="queryParams.signEmployee"
            placeholder="请输入签收人"
            clearable
            class="signPerson"
            style="width: 120px"
            @keyup.enter.native="handleQuery"
          />
        </el-col>
        <el-col :span="4">
          <el-form-item label="备料状态" prop="syntheticalStatus">
            <DictSelect
              v-show="$route.query.masterId"
              v-model="queryParams.syntheticalStatus"
              placeholder="请选择备料状态"
              dict-type="WMS_MATERIAL_PREPARATION_STATUS"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="slideOpen">
      <i
        class="operateBtn"
        :class="isOpen ? 'el-icon-arrow-right' : 'el-icon-arrow-left'"
        :style="{ right: operatePosition }"
        @click="handleOpenTask"
      />
      <div v-show="isOpen" class="side">
        <!-- 已备内容 -->
        <PreparedContent ref="preparedContent" />
      </div>

      <!-- 列表 -->
      <div
        :class="{ 'sidebar-open': isOpen }"
        class="leftMain"
        :style="{ width: mainContentWidth }"
      >
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="list"
          border
          :row-key="getOnlyRowKey"
          :current-row-key="currentRowKey"
          :row-class-name="rowClassName"
          @selection-change="handleSelectionChange"
          @expand-change="expandChange"
        >
          <el-table-column
            type="selection"
            width="55"
            fixed="left"
            :reserve-selection="true"
          />

          <el-table-column type="expand">
            <template slot-scope="{ row, $index }">
              <el-form
                :inline="false"
                class="table-expand"
                label-position="left"
              >
                <el-row :gutter="10" class="mb2">
                  <el-col :span="1.5">
                    <el-button
                      type="text"
                      size="mini"
                      :disabled="saveDisable"
                      @click="handleGenerateSupportDetail($index)"
                    >新增</el-button>
                    <el-button
                      type="text"
                      size="mini"
                      :disabled="saveDisable"
                      @click="handleDeleteSupport($index)"
                    >删除</el-button>
                    <el-button
                      type="text"
                      :disabled="saveDisable"
                      size="mini"
                      @click="handleSaveSupport($index)"
                    >保存</el-button>
                  </el-col>
                </el-row>

                <el-table
                  ref="expandTables"
                  v-loading="supportLoading"
                  :data="row.childList || []"
                  border
                  :row-key="$index + ''"
                  size="mini"
                  :summary-method="getSummaries"
                  show-summary
                  style="width: 100%"
                  @selection-change="handleSelectionExpand"
                >
                  <!-- :row-key="row.materialNo" -->
                  <el-table-column
                    type="selection"
                    width="55"
                    :reserve-selection="true"
                    fixed="left"
                  />
                  <el-table-column
                    label="生产订单"
                    align="center"
                    prop="workOrderNo"
                  />
                  <el-table-column
                    label="用料清单"
                    align="center"
                    prop="workOrderBomNo"
                  />
                  <el-table-column
                    label="宽度(mm)"
                    align="center"
                    prop="width"
                    width="100"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="步长(mm)"
                    align="center"
                    prop="stepLength"
                    width="100"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="穴数"
                    align="center"
                    prop="hillQty"
                    width="100"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="调机米数"
                    align="center"
                    prop="testScrapLength"
                    width="100"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="损耗"
                    align="center"
                    prop="pcsScrap"
                    width="100"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="总长度(m)"
                    align="center"
                    prop="sumLength"
                    width="100"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="需求数量(㎡)"
                    align="center"
                    prop="needQty"
                    width="100"
                  />
                  <el-table-column
                    label="本次发料量(㎡)"
                    align="center"
                    prop="nowSendQty"
                    width="100"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.nowSendQty"
                        :disabled="saveDisable"
                        @change="qtyChange(scope.row.nowSendQty, $index)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="剩余待发量(㎡)"
                    align="center"
                    prop="overplusSendQty"
                    width="100"
                  />
                </el-table>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            label="物料编码"
            align="center"
            prop="materialNo"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div class="custom-column">
                <el-button type="text" @click="handleShowPrepared(scope.row)">
                  {{ scope.row.materialNo }}
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="物料名称"
            align="center"
            prop="materialName"
            show-overflow-tooltip
          />
          <el-table-column
            label="应备总量"
            align="center"
            prop="shouldPrepareQty"
            show-overflow-tooltip
          />
          <el-table-column
            label="可应答量"
            align="center"
            prop="canUseQty"
            show-overflow-tooltip
          />
          <el-table-column
            label="当前库存"
            align="center"
            prop="totalNowQty"
            show-overflow-tooltip
          />
        </el-table>
      </div>
    </div>
    <!-- 发料支援明细 -->
    <IssueSupport ref="issueSupport" @send-data="handleRows" />
    <SignScan ref="signScan" @complete="getList" />

    <!-- 标签打印 -->
    <el-dialog
      :visible.sync="visible"
      title="标签补打"
      append-to-body
      width="400px"
    >
      <el-form
        ref="form"
        :model="form"
        size="mini"
        label-width="110px"
      >
        <el-form-item label="打印模板" prop="BtReportId">
          <el-select
            v-model="form.BtReportId"
            placeholder="请选择模板"
            @change="reportChange"
          >
            <el-option
              v-for="item in btTemplateList"
              :key="item.id"
              :label="item.originName"
              :value="item.id"
            >
              <el-row :gutter="10">
                <el-col :span="12">{{ item.originName }}</el-col>
                <el-col :span="12" class="text-right">{{
                  item.version
                }}</el-col>
              </el-row>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button
          type="primary"
          @click="handlePrintRepair"
        >打印标签</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMasterDetail,
  createSendMaster
} from '@/api/wms/inLibrary/productionPreparation'
import {
  getWorkOrderBomPage,
  getResourcePage,
  updateAllSynthetical,
  getMaterialTotalList
} from '@/api/wms/orders/productMaterials'
import IssueSupport from './IssueSupport.vue'
import SignScan from './SignScan.vue'
import { getBatchLabelPrintData } from '@/api/wms/incoming/register'
import { printLabel } from '@/api/common'
import { getAppendixTableData } from '@/api/system/appendix.js'
// 已备内容
import PreparedContent from './PreparedContent.vue'

export default {
  name: 'ProductionPreparation',
  components: {
    IssueSupport,
    SignScan,
    PreparedContent
  },
  data() {
    return {
      printData: [],
      currentRowKey: null,
      visible: false, // 是否显示打印标签
      // bartender模板列表
      btTemplateList: [],
      // 遮罩层
      loading: false,
      supportLoading: false,
      addSupportDisable: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用料清单（投料单）列表
      list: [],
      supportList: [],
      // 是否显示弹出层
      open: false,
      currentRows: [],
      expandCurrent: [],
      // 是否显示已备料内容
      isOpen: false,
      // 保存的列表
      saveList: [],
      // 禁用修改
      saveDisable: false,
      // 查看查询禁用
      queryDisabled: false,
      expandMaterialNo: null,
      expandTest: true,
      // 发料支援表列表
      resourceList: [],
      // 可应答量list
      canUseQtyList: [],
      // 展开的index
      currentExpandIndex: null,
      //
      saveId: undefined,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        materialNo: null,
        materialName: null
      },
      // 主表ID
      masterId: '',
      qtySum: null,
      qtyRaws: null,
      compareItemQty: null,
      totalQtys: null,
      form: {
        BtReportId: '',
        BtReportUrl: '',
        BtReportName: ''
      }
    }
  },
  computed: {
    mainContentWidth() {
      return this.isOpen ? 'calc(100% - 500px)' : '100%'
    },
    operatePosition() {
      return this.isOpen ? '500px' : '0'
    },
    queryWidth() {
      return this.isOpen ? 'calc(100% - 500px)' : '100%'
    }
  },
  created() {
    this.masterId = this.$route.query.masterId
    this.getTemplateList()
    if (this.masterId !== null && this.masterId !== undefined) {
      this.queryDisabled = true
      this.addSupportDisable = true
      this.getList()
    } else {
      this.queryDisabled = false
      this.addSupportDisable = false
    }
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      const params = {
        pageNo: this.queryParams.pageNo,
        pageSize: this.queryParams.pageSize,
        masterId: this.masterId
      }
      getMasterDetail(params)
        .then(async(response) => {
          const { body } = response.data || {}
          this.list = body.map((item) => {
            return {
              ...item,
              childList: []
            }
          })
          await this.handleCanUseQtyList(this.list)
          this.getResetCanQty()
          const { head } = response.data || {}
          this.queryParams = head
          this.total = response.data?.total
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 获取支援
    async getSupportList(row) {
      this.supportLoading = true
      // 执行查询
      const params = {
        wmsSyntheticalSendDetailId: this.queryParams?.masterId || ''
      }
      if (this.queryParams.masterId) {
        row.childList = (await getResourcePage(params)).data.list
        this.supportList = this.supportList.slice(0)
        const materialNo = row.childList[0].materialNo
        const items = this.list.find((i) => i.materialNo === materialNo)
        localStorage.setItem('should', items.shouldPrepareQty)
        this.compareItemQty = localStorage.getItem('should')
        this.supportLoading = false
      } else {
        getWorkOrderBomPage(params)
          .then((response) => {
            const { list } = response.data || []
            row.childList = list
            this.supportList = this.supportList.slice(0)
          })
          .finally(() => {
            this.supportLoading = false
          })
      }
    },
    // 获取BT打印模板
    getTemplateList() {
      getAppendixTableData({
        pageNum: 1,
        pageSize: 999,
        printFlag: '1',
        filesMenuId: '1000000000000000001'
      }).then(({ data }) => {
        this.btTemplateList = data?.list ?? []
      })
    },
    reportChange(e) {
      const fdIndex = this.btTemplateList.findIndex((ret) => ret.id === e)
      this.form.BtReportName = this.btTemplateList[fdIndex].originName
      this.form.BtReportUrl = this.btTemplateList[fdIndex].url
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.queryParams.pageSize = 10
      this.masterId = this.$route.query.masterId
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 支援明细
    handleGenerateSupport() {
      this.$refs.issueSupport.detailAdd = '0'
      this.$refs.issueSupport.orderDisabled = false
      this.$refs.issueSupport.title = '新增支援明细'
      this.$refs.issueSupport.open = true
    },
    async handleRows(data) {
      this.resourceList.push(...data)
      if (this.$refs.issueSupport.detailAdd === '1') {
        data.forEach((item, index) => {
          const {
            workOrderNo,
            id,
            workOrderBomNo,
            materialModels,
            needQty,
            materialNo,
            materialName,
            nowSendQty,
            detailErpId: workDetailErpId,
            id: wmsProductionWorkOrderBomDetailId
          } = item
          const detailSupport = []
          const findIndex = this.list[
            this.currentExpandIndex
          ].childList.findIndex(
            (i) => i.id === id || i.wmsProductionWorkOrderBomDetailId === id
          )
          // id相同，数量累加
          if (findIndex > -1) {
            this.list[this.currentExpandIndex].childList[findIndex].nowSendQty =
              parseFloat(
                this.list[this.currentExpandIndex].childList[findIndex]
                  .nowSendQty
              ) + parseFloat(nowSendQty)
            const sum = this.list[this.currentExpandIndex].childList.reduce(
              (accumulator, item) =>
                parseFloat(accumulator) + parseFloat(item.nowSendQty),
              parseFloat(0)
            )
            const raws = this.list.find(
              (item) =>
                item.materialNo ===
                this.list[this.currentExpandIndex].childList[0].materialNo
            )
            raws.shouldPrepareQty = this.getHandleNumber(sum)
          } else {
            // 否则，给列表push一条数据，并累加计算主列表shouldPrepareQty的值
            this.list[this.currentExpandIndex].childList.push({
              id,
              workOrderNo,
              workOrderBomNo,
              needQty,
              materialModels,
              materialNo,
              materialName,
              nowSendQty,
              detailSupport,
              workDetailErpId,
              wmsProductionWorkOrderBomDetailId
            })
            console.log(this.list[this.currentExpandIndex].childList)
            // const sum =  this.list[this.currentExpandIndex].childList.reduce((accumulator, item) => parseFloat(accumulator) + parseFloat(item.nowSendQty), 0)
            const sum = this.list[this.currentExpandIndex].childList.reduce(
              (accumulator, item) =>
                parseFloat(accumulator) + parseFloat(item.nowSendQty),
              parseFloat(0)
            )
            const raws = this.list.find(
              (item) =>
                item.materialNo ===
                this.list[this.currentExpandIndex].childList[0].materialNo
            )
            raws.shouldPrepareQty = this.getHandleNumber(sum)
          }
        })
        // 获取可应答量
        await this.handleCanUseQtyChangeList(
          this.list[this.currentExpandIndex].childList
        )
      } else {
        data.forEach(async(item, index) => {
          const {
            materialNo,
            materialName,
            nowSendQty: shouldPrepareQty,
            id
          } = item
          const detailList = []
          const findIndex = this.list.findIndex(
            (i) => i.materialNo === materialNo
          )
          if (findIndex > -1) {
            this.list[findIndex].shouldPrepareQty = this.getHandleNumber(
              parseFloat(shouldPrepareQty) +
                parseFloat(this.list[findIndex].shouldPrepareQty)
            )
          } else {
            this.list.push({
              materialNo,
              materialName,
              shouldPrepareQty,
              detailList,
              id
            })
          }
        })
        this.handleSubmit()
        await this.handleCanUseQtyChangeList(data)
      }
      // 计算可应答量
      this.getResetCanQty()
    },
    // 提交
    handleSubmit() {
      this.resourceList = this.resourceList.map((item) => {
        const {
          materialName,
          materialNo,
          needQty,
          nowSendQty,
          workOrderBomNo,
          workOrderNo,
          detailErpId: workDetailErpId,
          id: wmsProductionWorkOrderBomDetailId
        } = item
        return {
          materialName,
          materialNo,
          needQty,
          nowSendQty,
          workOrderBomNo,
          workOrderNo,
          workDetailErpId,
          wmsProductionWorkOrderBomDetailId
        }
      })
      const rowList = this.list.reduce((acc, cur) => {
        const { materialNo } = cur
        const item = this.resourceList.filter(
          (i) => i.materialNo === materialNo
        )
        acc.push({ ...cur, ...{ resource: item }})
        acc = acc.filter((resourceItem) => resourceItem.resource.length > 0)
        return acc
      }, [])
      const params = {
        remark: this.queryParams.remark,
        detail: rowList,
        id: this.masterId
      }
      createSendMaster(params).then((res) => {
        this.masterId = res.data
        this.$modal.msgSuccess('创建成功!')
        this.$emit('commitComplete')
        this.getList()
        this.resourceList = []
        this.addSupportDisable = true
        // this.$tab.closeOpenPage()
        // this.$router.go(-1)
      })
    },
    getOnlyRowKey(row) {
      return row.id
    },
    // 选中的
    handleSelectionChange(val) {
      this.currentRows = val
    },
    // 选中的
    handleSelectionExpand(val) {
      this.expandCurrent = val
    },
    // 删除支援
    async handleDeleteSupport(index) {
      this.currentExpandIndex = index
      if (this.expandCurrent.length <= 0) {
        this.$modal.msgWarning('请选择您要删除的数据!')
        return
      }
      this.list[this.currentExpandIndex].childList = this.list[
        this.currentExpandIndex
      ].childList.filter((item) => !this.expandCurrent.includes(item))
      this.$refs.expandTables.clearSelection()
      const sum = this.list[this.currentExpandIndex].childList.reduce(
        (accumulator, item) =>
          parseFloat(accumulator) + parseFloat(item.nowSendQty),
        parseFloat(0)
      )
      // this.list[0].shouldPrepareQty = sum
      const raws = this.list.find(
        (item) =>
          item.materialNo ===
          this.list[this.currentExpandIndex].childList[0].materialNo
      )
      raws.shouldPrepareQty = this.getHandleNumber(sum)
      await this.handleCanUseQtyChangeList(
        this.list[this.currentExpandIndex].childList
      )
      // 列表可应答量重新计算
      this.getResetCanQty()
    },
    // 保存支援
    handleSaveSupport(index) {
      this.currentExpandIndex = index
      if (this.masterId !== null && this.masterId !== undefined) {
        this.saveDisable = false
        this.saveList = this.saveList.map((item) => {
          const { materialNo, materialName, shouldPrepareQty } = item
          return {
            materialNo,
            materialName,
            shouldPrepareQty
          }
        })
        const { materialNo, materialName } = this.saveList[0]
        const params = {
          id: this.queryParams.id,
          detail: [
            {
              materialNo,
              materialName,
              shouldPrepareQty: this.totalQtys,
              resource: this.list[this.currentExpandIndex].childList
            }
          ]
        }
        updateAllSynthetical(params).then((res) => {
          this.saveId = res.data
          this.$modal.msgSuccess('保存成功!')
          this.getList()
          this.queryParams.remark = ''
          this.queryParams.signEmployee = ''
          localStorage.removeItem('should')
        })
      } else {
        this.saveDisable = true
      }
    },
    // 生成支援
    handleGenerateSupportDetail(index) {
      this.currentExpandIndex = index
      const generateSupport = this.$refs.issueSupport
      generateSupport.queryParams.materialNo = this.expandMaterialNo
      if (
        generateSupport.queryParams.materialNo !== null &&
        generateSupport.queryParams.materialNo !== undefined
      ) {
        generateSupport.orderDisabled = true
      } else {
        generateSupport.orderDisabled = false
      }
      generateSupport.detailAdd = '1'
      this.$refs.issueSupport.title = '新增支援明细'
      generateSupport.open = true
    },
    // 小数点问题处理
    getHandleNumber(val) {
      return Math.round(parseFloat(val) * 100000000) / 100000000
    },

    // 展开
    expandChange(row, expandedRows) {
      this.saveList = expandedRows
      const { materialNo, id, syntheticalStatus } = row
      if (syntheticalStatus === 2) {
        this.saveDisable = true
      } else {
        this.saveDisable = false
      }
      const multipleTable = this.$refs.multipleTable
      if (expandedRows.length > 1) {
        expandedRows.forEach((expandRow) => {
          if (row.id !== expandRow.id) {
            multipleTable.toggleRowExpansion(expandRow, false)
            this.$refs.expandTables.clearSelection()
            setTimeout(() => {
              this.expandTest = true
            })
          }
        })
      }
      this.expandMaterialNo = materialNo
      this.queryParams.masterId = id
      this.expandTest = false
      this.$nextTick(() => {
        if (row.childList.length === 0) {
          this.getSupportList(row)
        }
      })
    },
    async qtyChange(v, index) {
      this.currentExpandIndex = index
      if (typeof v === 'string') {
        v = Number(v)
      }
      this.qtySum = this.list[this.currentExpandIndex].childList.reduce(
        (accumulator, item) =>
          parseFloat(accumulator) + parseFloat(item.nowSendQty),
        parseFloat(0)
      )
      this.qtyRaws = this.list.find(
        (item) =>
          item.materialNo ===
          this.list[this.currentExpandIndex].childList[0].materialNo
      )
      this.qtyRaws.shouldPrepareQty = this.getHandleNumber(this.qtySum)
      await this.handleCanUseQtyChangeList(
        this.list[this.currentExpandIndex].childList
      )
      this.getResetCanQty()
    },
    // 重新计算可应大量
    getResetCanQty() {
      this.list = this.list.map((obj2) => {
        const newObj = { ...obj2 }
        this.canUseQtyList.forEach((obj1) => {
          if (obj1.materialNo === obj2.materialNo) {
            newObj.canUseQty = obj1.canUseQty
            newObj.totalNowQty = obj1.totalNowQty
          }
        })
        return newObj
      })
    },
    // 备料签收
    handleSign() {
      this.$refs.signScan.signId = this.queryParams.id
      this.$refs.signScan.codeOpen = true
    },
    // 批量打印
    async handleBatchRepair() {
      if (this.currentRows.length === 0) {
        this.$modal.msgWarning('请先选择您要打印的数据!')
        return
      }
      this.visible = true
    },

    // 标签补打
    async handleRepair() {
      if (this.currentRows.length === 0) {
        this.$modal.msgWarning('请先选择您要打印的数据!')
        return
      }
      if (
        this.currentRows[0].splitFlag === 0 ||
        this.currentRows[0].splitFlag === null
      ) {
        this.$modal.msgWarning('该数据未拆批，暂无标签可打印!')
        return
      }
      this.visible = true
    },
    // 打印
    async handlePrintRepair() {
      const wmsSyntheticalSendDetailId = this.currentRows.map(
        (item) => item.id
      )
      try {
        const batchParams = {
          wmsSyntheticalSendDetailIdList: wmsSyntheticalSendDetailId.join(',')
        }
        const batchData = await getBatchLabelPrintData(batchParams)
        const { data } = batchData
        this.printData.push(...data)
        // 打印参数
        const printParams = {
          printJson: JSON.stringify(this.printData),
          fileUrl: this.form.BtReportUrl
        }

        await printLabel(printParams) // 打印
        this.printData = []
        this.visible = false
      } catch (error) {
        console.log(error)
      }
    },
    // 展开已备料内容
    handleShowPrepared(row) {
      const { id } = row
      this.$refs.preparedContent.queryParams.wmsSyntheticalSendDetailId = id
      this.isOpen = true
      this.$refs.preparedContent.getList()
    },
    handleOpenTask() {
      this.isOpen = !this.isOpen
    },
    // 获取可应答量
    async handleCanUseQtyList(canList) {
      const resultMap = canList.reduce((acc, curr) => {
        const materialNo = curr.materialNo
        if (acc.has(materialNo)) {
          acc.set(materialNo)
        } else {
          acc.set(materialNo)
        }
        return acc
      }, new Map())
      const result = Array.from(resultMap, ([materialNo, totalQty]) => ({
        materialNo,
        totalQty
      }))
      const { data } = await getMaterialTotalList(result)
      if (result.length > 0) {
        this.canUseQtyList = data
      } else {
        this.canUseQtyList = []
      }
    },
    // 数量改变时获取可应答量
    async handleCanUseQtyChangeList(canList) {
      const arr1Sum = canList.reduce(
        (sum, item) => this.getHandleNumber(sum + parseFloat(item.nowSendQty)),
        0
      )
      this.totalQtys = arr1Sum
      // const arr2Sum = this.list.reduce((sum, item) => sum + item.shouldPrepareQty, 0)
      // this.qtyRaws.shouldPrepareQty = this.getHandleNumber(this.qtySum)
      const result = arr1Sum - this.compareItemQty
      const params = [
        {
          materialNo: canList[0].materialNo,
          totalQty: result
        }
      ]
      const { data } = await getMaterialTotalList(params)
      this.canUseQtyList = data
    },
    // 应答量不足预警
    rowClassName(row) {
      const isOverQty = this.canUseQtyList.some(
        (item) => item.materialNo === row.row.materialNo && item.canUseQty < 0
      )
      return isOverQty ? 'highlight-row' : ''
    },
    // 剩余发料量不足
    rowSelectClassName(row) {
      const isLower = this.list[this.currentExpandIndex].childList.some(
        (item) => item.overplusSendQty <= 0
      )
      return isLower ? 'lower-row' : ''
    },
    // 小数点问题处理
    getHandleTotalNumber(val) {
      return Math.round(parseFloat(val) * 100000000) / 100000000
    },
    // 总计
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values =
          this.expandCurrent.map((item) => Number(item[column.property])) || []
        if (column.property === 'sumLength' || column.property === 'needQty') {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur)
            if (!isNaN(value)) {
              return this.getHandleTotalNumber(acc + cur)
            } else {
              return this.getHandleTotalNumber(acc)
            }
          }, 0)
          sums[index]
        }
      })
      return sums
    }
  }
}
</script>

<style scoped lang="scss">
/* 表格相关样式 */
.custom-column {
  position: relative;
}

.custom-column .el-button {
  user-select: text;
}

.table-expand {
  padding: 0 10px 0 54px;
  /* 可以根据需要启用以下注释掉的样式 */
  //  border: 1px solid #000;
  //  box-shadow: 5px 0 10px rgba(0, 0, 0, 0.2);
}
.app-container {
  position: relative;
  /* 滑动展开效果 */
  & .slideOpen {
    & .side {
      position: absolute;
      top: 108px;
      right: 0;
      width: 500px;
      height: 100%;
      overflow-y: auto;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
      transition: all 0.3s ease;
    }

    & .operateBtn {
      position: absolute;
      right: 500px;
      top: 300px;

      &:hover {
        cursor: pointer;
      }
    }

    & .main-content {
      margin-right: 500px;
      transition: all 0.3s ease;
    }
  }
}

.card-icon-signed {
  font-size: 45px;
  display: inline-block;
  position: absolute;
  top: 33px;
  left: 70%;
  z-index: 1000;
  cursor: pointer;
}

/* Vue作用域插槽穿透选择器（Vue 3 使用） */
::v-deep .el-input--medium .el-input__inner,
::v-deep .el-select.is-disabled .el-input__inner {
  height: 32px !important;
}

::v-deep .highlight-row {
  background-color: #f56c6c !important;
}

::v-deep .lower-row {
  background: #909399 !important;
}
</style>
