<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"
          @click="handleGenerateSupport"
        >新增支援</el-button>
        <el-button
          size="mini"
          type="primary"
          :loading="signLoading"
          :disabled="queryParams.syntheticalStatus!== 1"
          @click="handleSign"
        >生成发料单</el-button>
        <el-button
          v-hasPermi="['wms:synthetical-send-master:update']"
          size="mini"
          type="primary"
          :loading="printLoading"
          @click="handleRepair"
        >标签补打</el-button>
        <el-button
          size="mini"
          type="primary"
          :loading="printLoading"
          @click="handleBatchRepair"
        >批量打印</el-button>
      </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="7">
          <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 label="供应商" prop="supplierCode">
            <el-input v-if="queryDisabled" v-model="queryParams.supplierName" />
            <PrepareSupplerSelect v-else v-model="queryParams.supplierCode" @change="supplerChange" />

          </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="4">
          <el-form-item label="备料状态" prop="syntheticalStatus">
            <DictSelect
              v-show="$route.query.masterId !== null && $route.query.masterId !== undefined"
              v-model="queryParams.syntheticalStatus"
              placeholder="请选择备料状态"
              dict-type="WMS_MATERIAL_PREPARATION_STATUS"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row
        :gutter="10"
      >
        <el-col :span="8">
          <el-form-item v-show="$route.query.masterId !== null && $route.query.masterId !== undefined" label="签收状态" prop="signStatus">
            <DictSelect v-model="queryParams.signStatus" placeholder="请选择签收状态" dict-type="WMS_SIGN_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"
          @select="select"
          @select-all="selectAll"
          @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-form>
              <el-table
                ref="expandTables"
                v-loading="supportLoading"
                :data="row.childList || []"
                border
                :row-key="$index + ''"
                size="mini"
                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"
                  width="150"
                  show-overflow-tooltip
                />
                <el-table-column
                  label="用料清单"
                  align="center"
                  prop="workOrderBomNo"
                  width="130"
                  show-overflow-tooltip
                />
                <el-table-column
                  label="bom规格"
                  align="center"
                  prop="bomModel"
                  width="120"
                  show-overflow-tooltip
                />
                <el-table-column
                  label="物料规格"
                  align="center"
                  prop="materialModels"
                  show-overflow-tooltip
                />
                <el-table-column
                  label="需求数量"
                  align="center"
                  prop="needQty"
                />
                <el-table-column
                  label="本次发料量"
                  align="center"
                  prop="nowSendQty"
                >
                  <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"
                />
              </el-table>
            </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
            width="130"
          />
          <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" />
    <!-- 打印标签 -->
    <PrintTemplate ref="packingLabelPrinitTemplate" :print-data="printData" />

  </div>
</template>

<script>
import { getMasterDetail } from '@/api/wms/inLibrary/productionPreparation'
import { createSysthicalSend, CreateConfirmSend } from '@/api/wms/inLibrary/outsourcePreparation'
import { getWorkOrderBomPage, getResourcePage, updateAllSynthetical, getMaterialTotalList } from '@/api/wms/orders/productMaterials'
import IssueSupport from './IssueSupport.vue'
import SignScan from './SignScan.vue'
import { getLodop } from '@/plugins/lodopFuncs'
import { handlePrint } from '@/utils/lodop'
import PrintTemplate from '@/views/wms/incoming/register/components/PrintTemplate.vue'
import { getLabelPrintData, getBatchLabelPrintData } from '@/api/wms/incoming/register'
// 已备内容
import PreparedContent from './PreparedContent.vue'
// 供应商下拉列表
import PrepareSupplerSelect from './PrepareSupplerSelect.vue'

export default {
  name: 'ProductionPreparation',
  components: {
    IssueSupport,
    SignScan,
    PrintTemplate,
    PreparedContent,
    PrepareSupplerSelect
  },
  data() {
    return {
      printData: [],
      currentRowKey: null,
      printStyle: `
        <style>
          table {
            width:100%;
            margin: 0 auto;
            border: 1px solid #000000;
            border-collapse: collapse;
            page-break-after:always;
            font-size: 12px;
            table-layout: fixed;
          }

          th, td {
            border: 1px solid #000000;
          }
          td {
            width:100%;
            word-break:keep-all;/* 不换行 */
            white-space:nowrap;/* 不换行 */
            overflow:hidden;/* 内容超出宽度时隐藏超出部分的内容 */
            text-overflow:ellipsis;
          }
        </style>
      `,
      // 遮罩层
      loading: false,
      supportLoading: false,
      addSupportDisable: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用料清单（投料单）列表
      list: [],
      supportList: [],
      // 是否显示弹出层
      open: false,
      currentRows: [],
      expandCurrent: [],
      // 签收加载
      signLoading: false,
      printLoading: false,
      // 是否显示已备料内容
      isOpen: false,
      // 保存的列表
      saveList: [],
      // 禁用修改
      saveDisable: false,
      // 查看查询禁用
      queryDisabled: false,
      expandMaterialNo: null,
      expandTest: true,
      // 发料支援表列表
      resourceList: [],
      // 可应答量list
      canUseQtyList: [],
      // 展开的index
      currentExpandIndex: null,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        materialNo: null,
        materialName: null,
        supplierCode: null
      },
      // 主表ID
      masterId: '',
      qtySum: null,
      qtyRaws: null,
      compareItemQty: null,
      totalQtys: null
    }
  },
  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
    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 => {
        // this.list = response.data.body
        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.queryParams.supplierCode = response.data.head.supplierName || ''
        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 !== null && this.queryParams.masterId !== undefined && 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('outshould', items.shouldPrepareQty)
        this.compareItemQty = localStorage.getItem('outshould')
        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
        })
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        orderType: undefined,
        erpId: undefined,
        erpOrderNo: undefined,
        erpOrderTime: undefined,
        status: undefined,
        workErpId: undefined,
        workOrderNo: undefined,
        workDetailErpId: undefined,
        productCode: undefined,
        productUnit: undefined,
        productName: undefined,
        productModel: undefined,
        productAmount: undefined,
        departmentNo: undefined,
        remark: undefined,
        erpMdtime: undefined,
        erpMark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    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.queryParams.supplierCode = this.queryParams.supplierCode
      if (this.queryParams.supplierCode === undefined || this.queryParams.supplierCode === null) {
        this.$modal.msgWarning('请现在选择供应商!')
        return
      }
      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 { id, workOrderNo, workOrderBomNo, materialModels, needQty, materialNo, materialName, nowSendQty, id: wmsProductionWorkOrderBomDetailId } = item
          const detailSupport = []
          const findIndex = this.list[this.currentExpandIndex].childList.findIndex(i => (i.id === id || i.wmsProductionWorkOrderBomDetailId === id))
          if (findIndex > -1) {
            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 {
            this.list[this.currentExpandIndex].childList.push({ id, workOrderNo, workOrderBomNo, needQty, materialModels, materialNo, materialName, nowSendQty, detailSupport, wmsProductionWorkOrderBomDetailId })
            // 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((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 = 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() {
      if (this.list.length <= 0) {
        this.$modal.msgWarning('请先选择支援明细!')
        return
      }
      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,
        prepareType: 1,
        supplierCode: this.queryParams.supplierCode,
        id: this.masterId,
        detail: rowList
      }
      createSysthicalSend(params).then(res => {
        this.masterId = res.data
        this.$modal.msgSuccess('创建成功!')
        this.$emit('commitComplete')
        this.getList()
        this.resourceList = []
        // this.$tab.closeOpenPage()
        // this.$router.go(-1)
      })
    },
    getOnlyRowKey(row) {
      return row.id
    },
    // 选中的
    handleSelectionChange(val) {
      this.currentRows = val
    },
    // 选中的
    handleSelectionExpand(val) {
      this.expandCurrent = val
    },
    select(selection, row) {
      if (selection.length > 1) {
        const delRow = selection.shift()
        this.$refs.multipleTable.toggleRowSelection(delRow, false)
      }
    },
    selectAll(selection) {
      if (selection.length > 1) {
        selection.length = 1
      }
    },
    // 删除支援
    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.$route.query.masterId !== undefined && this.$route.query.masterId !== null
      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.$modal.msgSuccess('保存成功!')
          this.getList()
          this.queryParams.remark = ''
          this.queryParams.signEmployee = ''
          localStorage.removeItem('outshould')
        })
      } 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'
      generateSupport.queryParams.supplierCode = this.queryParams.supplierCode
      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)
            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()
    },
    // 生成发料单
    handleSign() {
      // this.$refs.signScan.signId = this.queryParams.id
      // this.$refs.signScan.codeOpen = true
      const params = {
        id: this.queryParams.id
      }
      this.signLoading = true
      CreateConfirmSend(params).then(res => {
        this.$modal.msgSuccess('操作成功!')
        this.getList()
        this.$tab.closeOpenPage()
        this.$router.go(-1)
      }).finally(() => {
        this.signLoading = false
      })
    },
    // 批量打印
    async handleBatchRepair() {
      if (this.currentRows.length <= 0) {
        this.$modal.msgWarning('请先选择您要打印的数据!')
        return
      }
      try {
        const batchParams = {
          wmsSyntheticalSendDetailId: this.currentRows[0].id
        }
        const batchData = await getBatchLabelPrintData(batchParams)
        const { data } = batchData
        this.printData.push(...data)
        this.$nextTick(() => {
          let timer = setTimeout(() => {
            const el = this.$refs.packingLabelPrinitTemplate.$el
            const elItems = el.querySelectorAll('.print-item')
            const LODOP = getLodop()
            if (LODOP === undefined) {
              this.$alert('请先安装C-LODOP插件,下载地址为' + 'http://www.c-lodop.com/download.html')
              return
            }
            LODOP.SET_PRINT_PAGESIZE(1, '60mm', '50mm')
            // LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', 'Full-Page')
            elItems.forEach(item => {
              LODOP.NewPage()
              // LODOP.ADD_PRINT_HTM('0', '0', '100%', '100%', item.innerHTML + this.printStyle)
              LODOP.ADD_PRINT_HTM('5mm', '4mm', '54mm', '45mm', item.innerHTML + this.printStyle)
            })
            handlePrint(LODOP)
            this.printData = []
            clearTimeout(timer)
            timer = null
          }, 600)
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 标签补打
    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
      }
      try {
        const printParams = {
          qrCode: this.currentRows[0].wmsLabelMasterId
        }
        const printDetailData = await getLabelPrintData(printParams)
        const { data: productsDetails } = printDetailData
        this.printData.push(...productsDetails)
        this.$nextTick(() => {
          let timer = setTimeout(() => {
            const el = this.$refs.packingLabelPrinitTemplate.$el
            const elItems = el.querySelectorAll('.print-item')
            const LODOP = getLodop()
            if (LODOP === undefined) {
              this.$alert('请先安装C-LODOP插件,下载地址为' + 'http://www.c-lodop.com/download.html')
              return
            }
            LODOP.SET_PRINT_PAGESIZE(1, '60mm', '50mm')
            // LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', 'Full-Page')
            elItems.forEach(item => {
              LODOP.NewPage()
              // LODOP.ADD_PRINT_HTM('0', '0', '100%', '100%', item.innerHTML + this.printStyle)
              LODOP.ADD_PRINT_HTM('5mm', '4mm', '54mm', '45mm', item.innerHTML + this.printStyle)
            })
            handlePrint(LODOP)
            this.printData = []
            clearTimeout(timer)
            timer = null
          }, 600)
        })
      } catch (error) {
        console.log(error)
      }
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      const newData = this.list.map((item, index) => {
        const filterData = this.list.filter(ele => {
          return item.materialNo === ele.materialNo
        })
        const dataIndex = this.list.findIndex(eleIndex => {
          return item.materialNo === eleIndex.materialNo
        })
        if (index === dataIndex) {
          item.rowspan = filterData.length
        } else {
          item.rowspan = 0
        }
        return newData
      })
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
        return {
          rowspan: row.rowspan,
          colspan: 1
        }
      } else {
        return false
      }
    },
    // 展开已备料内容
    handleShowPrepared(row) {
      const { id } = row
      this.$refs.preparedContent.queryParams.wmsSyntheticalSendDetailId = id
      this.isOpen = true
      this.$refs.preparedContent.getList()
    },
    handleOpenTask() {
      this.isOpen = !this.isOpen
    },
    // 供应商下拉选择
    supplerChange(v) {
      console.log(v)
    },
    // 获取可应答量
    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 result = arr1Sum - this.compareItemQty
      const params =
        [
          {
            materialNo: canList[0].materialNo,
            totalQty: result
          }
        ]
      const { data } = (await getMaterialTotalList(params))
      this.canUseQtyList = data
    },
    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
      })
    },
    // 应答量不足预警
    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.nowSendQty > item.overplusSendQty)
      return isLower ? 'lower-row' : ''
    }

  }
}
</script>
<style scoped>
/* 表格使用了插槽复制的 */
.custom-column {
  position: relative;
}
.custom-column .el-button {
  user-select: text;
}
.table-expand {
  /* border: 1px solid #000; */
  /* box-shadow: 0 0 10px rgba(0, 0, 0, .2); */
  padding: 0 10px;
}
.app-container {
  position: relative;
}
.slideOpen .side {
  position: absolute;
  top: 20%;
  right: 0;
  width: 500px;
  height: 100%;
  overflow-y: auto;
  box-shadow: 0 0 10px rgba(0, 0, 0, .2);
  transition: all .3s;
}
.slideOpen .operateBtn {
  position: absolute;
  right: 500px;
  top: 300px;
}
.slideOpen .operateBtn:hover {
  cursor: pointer;
}
.slideOpen .main-content {
  margin-right: 500px;
  transition: all .3s;
}
.slideOpen .operateBtn {
  position: absolute;
  right: 850px;
  top: 300px;
}
.slideOpen .operateBtn:hover {
  cursor: pointer;
}
.card-icon-signed {
  font-size: 45px;
  display: inline-block;
  position: absolute;
  top: 33px;
  left: 70%;
  z-index: 1000;
  cursor: pointer;
}
::v-deep.el-input--medium .el-input__inner {
  height: 32px!important;
}
::v-deep .el-select .el-input.is-disabled .el-input__inner {
  height: 32px !important;
}
::v-deep .highlight-row {
  background-color: #F56C6C !important;
}
::v-deep .lower-row {
  background: #909399 !important;
}
</style>

