<template>
  <div class="customer-css" >
    <!--  查询时间和产品  -->
    <el-form :inline="true" label-position="top" label-width="100px" style="margin-top: 0px;" @submit.native.prevent="getMainData">
      <el-row>
        <el-col :span="24" style="">
          <el-form-item :label="'BU:'">
            <el-input v-model="searchData.buNo" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'销售出库单号:'">
            <el-input v-model="searchData.orderNo" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'客户编号:'">
            <el-input v-model="searchData.customerId" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'客户名称:'">
            <el-input v-model="searchData.customerName" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'单据状态'">
            <el-select multiple collapse-tags v-model="searchData.orderStatusList" clearable style="width: 160px">
              <el-option label="待包装" value="待包装"></el-option>
              <el-option label="待检验" value="待检验"></el-option>
              <el-option label="已出库" value="已出库"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="'是否送检'">
            <el-select v-model="searchData.inspectionFlag" clearable style="width: 100px">
              <el-option label="是" value="Y"></el-option>
              <el-option label="否" value="N"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="' '" >
            <el-button class="customer-bun-min" type="primary" @click="getMainData" style="">查询</el-button>
            <el-button @click="exportExcel()" type="primary" style="margin-left: 2px">{{'导出'}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      :height="height"
      :data="mainDataList"
      border
      ref="mainTable"
      highlight-current-row
      @row-click="changeData"
      v-loading="dataListLoading"
      style="margin-top: 0px; width: 100%;">
      <el-table-column
        v-for="(item,index) in columnArray1" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden && item.columnProp !== 'inspectionFlag'"> {{scope.row[item.columnProp]}}</span>
          <span v-if="!item.columnHidden && item.columnProp === 'inspectionFlag'"> {{scope.row[item.columnProp] === 'Y' ? '是' : scope.row[item.columnProp] === 'N' ? '否' : ''}}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="80"
        label="操作">
        <template slot-scope="scope">
          <el-link v-if="scope.row.orderStatus === '待包装'" style="cursor: pointer" @click="handleComplete(scope.row)">送检</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <el-pagination style="margin-top: 0px"
                   @size-change="sizeChangeHandle"
                   @current-change="currentChangeHandle"
                   :current-page="pageIndex"
                   :page-sizes="[20, 50, 100, 200, 500]"
                   :page-size="pageSize"
                   :total="totalPage"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-tabs v-model="activeName" style="margin-top: 0px; width: 99%;" @tab-click="tabClick" class="customer-tab" type="border-card">
      <el-tab-pane label="扫描装盒" name="cases">
        <el-form v-if="currentRow.orderStatus === '待包装'" label-position="top" style="margin-left: 2px; display: flex; align-items: center;">
          <el-button type="primary" size="small" @click="openCaseDialog">新增</el-button>
          <el-button type="danger" size="small" @click="deleteCaseRecord">删除</el-button>
          <span style="margin-left: auto; font-size: 14px; display: flex; align-items: center;">
            <span style="margin-right: 20px;">
              <span style="color: #606266;">盒标签张数：</span>
              <span style="color: rgb(38, 92, 147); font-weight: bold;">{{casesStatistics.boxCountCases}}</span>
            </span>
            <span style="margin-right: 20px;">
              <span style="color: #606266;">卷标签张数：</span>
              <span style="color: rgb(38, 92, 147); font-weight: bold;">{{casesStatistics.boxCountRolls}}</span>
            </span>
            <span>
              <span style="color: #606266;">物料总数：</span>
              <span style="color: rgb(38, 92, 147); font-weight: bold;">{{casesStatistics.totalQty}}</span>
            </span>
          </span>
        </el-form>
        <el-table
          ref="caseTable"
          :data="casesList"
          :height="height - 30"
          border
          @selection-change="handleCaseSelectionChange"
          style="width: 100%;">
          <el-table-column
            type="selection"
            width="55"
            align="center">
          </el-table-column>
          <el-table-column
            prop="casesNo"
            header-align="center"
            align="center"
            min-width="120"
            label="盒标签">
          </el-table-column>
          <el-table-column
            prop="rollNo"
            header-align="center"
            align="center"
            min-width="120"
            label="卷标签">
          </el-table-column>
          <el-table-column
            prop="rollQty"
            header-align="center"
            align="right"
            min-width="100"
            label="卷数量">
          </el-table-column>
          <el-table-column
            prop="partNo"
            header-align="center"
            align="left"
            min-width="120"
            label="物料编码">
          </el-table-column>
          <el-table-column
            prop="partDesc"
            header-align="center"
            align="left"
            min-width="200"
            label="物料名称">
          </el-table-column>
          <el-table-column
            prop="createDate"
            header-align="center"
            align="center"
            min-width="160"
            label="创建时间">
          </el-table-column>
          <el-table-column
            prop="createBy"
            header-align="center"
            align="center"
            min-width="100"
            label="创建人">
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="扫描装箱" name="boxing">
        <boxing ref="boxing"></boxing>
      </el-tab-pane>
      <el-tab-pane label="装箱清单" name="rollDetail">
        <el-table
          :data="rollList"
          :height="height - 20"
          border
          style="width: 100%;">
          <el-table-column
            prop="orderId"
            header-align="center"
            align="center"
            min-width="60"
            label="序号">
          </el-table-column>
          <el-table-column
            prop="boxNo"
            header-align="center"
            align="center"
            min-width="100"
            label="箱号">
          </el-table-column>
          <el-table-column
            prop="finalRollNo"
            header-align="center"
            align="center"
            min-width="100"
            label="卷号">
          </el-table-column>
          <el-table-column
            prop="partNo"
            header-align="center"
            align="left"
            min-width="100"
            label="物料编码">
          </el-table-column>
          <el-table-column
            prop="rollQty"
            header-align="center"
            align="right"
            min-width="100"
            label="数量">
          </el-table-column>
          <el-table-column
            prop="receivedDate"
            header-align="center"
            align="center"
            min-width="100"
            label="装箱日期">
          </el-table-column>
          <el-table-column
            prop="receivedBy"
            header-align="center"
            align="left"
            min-width="100"
            label="装箱人">
          </el-table-column>
          <el-table-column
            prop="batchNo"
            header-align="center"
            align="left"
            min-width="100"
            label="合约号">
          </el-table-column>
          <el-table-column
            prop="wareHouseID"
            header-align="center"
            align="left"
            min-width="100"
            label="仓库">
          </el-table-column>
          <el-table-column
            prop="locationId"
            header-align="center"
            align="left"
            min-width="100"
            label="库位">
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="扫描装托" name="pallet">
        <pallet ref="pallet"></pallet>
      </el-tab-pane>
    </el-tabs>

    <!-- 盒清单新增对话框 -->
    <el-dialog title="装盒扫描" :visible.sync="caseDialogVisible" width="70%" :close-on-click-modal="false" @close="closeCaseDialog">
      <el-form :inline="true" label-position="top" style="margin-left: 7px;margin-top: -5px;" @submit.native.prevent>
        <el-form-item label="卷标签">
          <el-input ref="rollNoInput" v-model="caseForm.rollNo" @keyup.enter.native="scanCaseRoll" placeholder="请扫描卷标签" style="width: 200px"></el-input>
        </el-form-item>
        <span style="margin-left: 20px; font-size: 14px; display: inline-block; margin-top: 20px;">
          <span style="color: #606266;">需求数量：</span>
          <span style="color: rgb(38, 92, 147); font-weight: bold;">{{currentRow.requiredQty || 0}}</span>
        </span>
        <span style="margin-left: 20px; font-size: 14px; display: inline-block; margin-top: 20px;">
          <span style="color: #606266;">盒标签张数：</span>
          <span style="color: rgb(38, 92, 147); font-weight: bold;">{{caseStatistics.casesCount}}</span>
        </span>
        <span style="margin-left: 20px; font-size: 14px; display: inline-block; margin-top: 20px;">
          <span style="color: #606266;">卷标签张数：</span>
          <span style="color: rgb(38, 92, 147); font-weight: bold;">{{caseStatistics.rollCount}}</span>
        </span>
        <span style="margin-left: 20px; font-size: 14px; display: inline-block; margin-top: 20px;">
          <span style="color: #606266;">物料总数：</span>
          <span style="color: rgb(38, 92, 147); font-weight: bold;">{{caseStatistics.totalQty}}</span>
        </span>
      </el-form>
      <!-- 中部分：扫描列表 -->
      <el-table
          ref="caseRollTable"
          :data="caseRollList"
          border
          height="300"
          @selection-change="handleCaseRollSelectionChange"
          style="width: 100%; margin-top: 10px;">
        <el-table-column
            type="selection"
            width="55"
            header-align="center"
            align="center">
        </el-table-column>
        <el-table-column
            type="index"
            label="序号"
            width="50"
            header-align="center"
            align="right">
        </el-table-column>
        <el-table-column
            prop="casesNo"
            label="盒标签"
            min-width="120"
            header-align="center"
            align="left">
        </el-table-column>
        <el-table-column
            prop="rollNo"
            label="卷标签"
            min-width="120"
            header-align="center"
            align="left">
        </el-table-column>
        <el-table-column
            prop="rollQty"
            label="卷数量"
            min-width="100"
            header-align="center"
            align="right">
        </el-table-column>
        <el-table-column
            prop="partNo"
            label="物料编码"
            min-width="120"
            header-align="center"
            align="left">
        </el-table-column>
        <el-table-column
            prop="partDesc"
            label="物料名称"
            min-width="200"
            header-align="center"
            align="left">
        </el-table-column>
        <el-table-column
            prop="batchNo"
            label="合约号"
            min-width="120"
            header-align="center"
            align="left">
        </el-table-column>
        <el-table-column
            label="操作"
            width="80"
            header-align="center"
            align="center">
          <template slot-scope="scope">
            <el-link style="cursor: pointer" @click="deleteRollFromList(scope.$index)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-footer style="height:35px;margin-top: 15px;text-align:center">
        <el-button type="primary" :loading="printLoading" @click="printCaseRolls">打印</el-button>
        <el-button type="primary" @click="applyCaseScan">应用</el-button>
        <el-button type="success" @click="saveCaseScan">保存</el-button>
        <el-button @click="closeCaseDialog">关闭</el-button>
      </el-footer>
    </el-dialog>

  </div>
</template>

<script>
/*组件*/


import excel from "@/utils/excel-util.js";
import boxing from "./com_saleBoxManage_boxing.vue"
import pallet from "./com_saleBoxManage_pallet.vue"
import {
  searchRollForOrderNo,
  searchSoReceiveCasesData,
  deleteSoReceiveCasesData,
  validateAndScanCaseRoll,
  saveCaseRollList,
  searchOutboundNotificationWithDetail,
  searchOutboundNotificationWithDetailByPage,
  updateOrderStatus
} from '../../../api/boxManage/boxManage'
import { callUspPartLabelTemplate } from '@/api/wms/wms'
import getLodop from '@/utils/LodopFuncs.js'
import labelPrintTemplates from '@/mixins/labelPrintTemplates.js'


export default {
  mixins: [labelPrintTemplates],
  data() {
    return {
      functionId: this.$route.meta.menuId,
      height: 200,
      currentRow: {},
      selectedCaseRolls: [], // 装盒对话框中选中的卷标签
      printLoading: false,   // 打印loading
      searchData:{
        orderNo:'',
        customerId:'',
        orderType:'销售出库',
        orderStatus: '',
        orderStatusList: ['待包装'],
        inspectionFlag: '',
        buNo:'',
        customerName:'',
        site:this.$store.state.user.site,
        userName:this.$store.state.user.name,
        page: 1,
        limit: 10,
      },
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      tagNo:'',
      rollList:[],
      mainDataList:[],
      dataListLoading: false,
      activeName: 'cases',
      // 盒清单相关数据
      casesList: [],
      casesStatistics: {
        boxCountCases: 0,  // 盒标签张数
        boxCountRolls: 0,  // 卷标签张数
        totalQty: 0        // 物料总数
      },
      caseDialogVisible: false,
      caseForm: {
        casesNo: '',
        rollNo: '',
        site: this.$store.state.user.site,
        buNo: '',
        notifyNo: '',
        partNo: ''
      },
      caseRollList: [],
      caseStatistics: {
        casesCount: 0,
        rollCount: 0,
        totalQty: 0
      },
      selectedCaseRecords: [],
      columnArray1: [
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1BU',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "buNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "BU",
          columnWidth: '60',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1OrderNo',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "orderNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "销售出库单号",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1OrderStatus',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "orderStatus",
          headerAlign: "center",
          align: "left",
          columnLabel: "通知单状态",
          columnWidth: '80',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1InspectionFlag',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "inspectionFlag",
          headerAlign: "center",
          align: "center",
          columnLabel: "是否送检",
          columnWidth: '80',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1CustomerId',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "customerId",
          headerAlign: "center",
          align: "left",
          columnLabel: "客户编号",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1CustomerName',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "customerName",
          headerAlign: "center",
          align: "left",
          columnLabel: "客户名称",
          columnWidth: '240',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1CustomerAbb',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "customerAbb",
          headerAlign: "center",
          align: "left",
          columnLabel: "客户简称",
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1RequiredOutboundDate',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "requiredOutboundDate",
          headerAlign: "center",
          align: "left",
          columnLabel: "要求发货日期",
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1RelatedOrderNo',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "relatedOrderNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "销售订单号",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1RelatedOrderLineNo',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "relatedOrderLineNo",
          headerAlign: "center",
          align: "right",
          columnLabel: "销售订单行号",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1PartNo',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "partNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "物料编码",
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1PartDesc',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "partDesc",
          headerAlign: "center",
          align: "left",
          columnLabel: "物料名称",
          columnWidth: '200',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1OutBatchNo',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "outBatchNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "合约号",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1OrderQty',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "orderQty",
          headerAlign: "center",
          align: "right",
          columnLabel: "销售订单数量",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1RequiredQty',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "requiredQty",
          headerAlign: "center",
          align: "right",
          columnLabel: "要求发货数量",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1AvailableStock',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "availableStock",
          headerAlign: "center",
          align: "right",
          columnLabel: "可用库存",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1RollQty',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "rollQty",
          headerAlign: "center",
          align: "right",
          columnLabel: "已扫描数量",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1UnScanQty',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "unScanQty",
          headerAlign: "center",
          align: "right",
          columnLabel: "未扫描数量",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table1Unit',
          tableId: "750001Table1",
          tableName: "销售发货清单",
          columnProp: "unit",
          headerAlign: "center",
          align: "left",
          columnLabel: "单位",
          columnWidth: '80',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
      ],
      exportName: '销售出库单'+this.dayjs().format('YYYYMMDDHHmmss'),
    }
  },
  /*组件*/
  components: {
    boxing,
    pallet
  },

  mounted() {
    this.$nextTick(() => {
      this.height = ( window.innerHeight - 220)/2;
    })
  },
  methods: {

    getMainData(){
      this.dataListLoading = true
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex
      this.searchData.orderStatus = this.searchData.orderStatusList.join(',')
      searchOutboundNotificationWithDetailByPage(this.searchData).then(({data}) => {
        if (data.code === 0) {
          this.mainDataList = data.page.list
          this.totalPage = data.page.totalCount
          //判断是否全部存在数据
          if (this.mainDataList && this.mainDataList.length > 0) {
            //设置选中行
            this.$refs.mainTable.setCurrentRow(this.mainDataList[0])
            this.changeData(this.mainDataList[0])
          } else {
            this.changeData(null)
          }
        }
        this.dataListLoading = false
      }).catch(() => {
        this.dataListLoading = false
      })
    },
    tabClick(tab, event){
      this.refreshCurrentTabTable()
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getMainData()
    },

    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getMainData()
    },
    changeData(row){
      this.currentRow=JSON.parse(JSON.stringify(row))
      this.refreshCurrentTabTable ();
    },
    refreshCurrentTabTable(){
      if (this.currentRow === '' || this.currentRow === null) {
        this.currentRow = {
          site: '',
          buNo: '',
          supplierNo: ''
        }
      }
      if(this.activeName==='boxing'){
        this.refreshBoxingTable();
      }
      if(this.activeName==='pallet'){
        this.refreshPalletTable();
      }
      if(this.activeName==='rollDetail'){
        this.refreshRollsTable();
      }
      if(this.activeName==='cases'){
        this.refreshCasesTable();
      }
    },
    async exportExcel() {
      this.searchData.limit = -1
      this.searchData.page = 1
      excel.exportTable({
        url: "/boxForNotification/searchOutboundNotificationWithDetail",
        columnMapping:  this.columnArray1,//可以直接用table，不需要的列就剔除
        mergeSetting: [],//需要合并的列
        params: this.searchData,
        fileName: this.exportName+".xlsx",
        rowFetcher: res => res.data.rows,
        columnFormatter: [],
        dropColumns: [],//需要剔除的列，例如dropColumns: ["netWeight"]，即剔除净重列
      });
    },
    refreshBoxingTable(){
      // 检查是否有有效的当前行数据
      if (!this.currentRow || !this.currentRow.orderNo) {
        return;
      }
      this.$nextTick(() => {
        if (!this.$refs.boxing) {
          return;
        }
        let inData={
          site: this.currentRow.site,
          buNo: this.currentRow.buNo,
          orderNo: this.currentRow.orderNo,
          boxType: this.currentRow.orderType,
          height:Number(this.height)-25,
          orderStatus: this.currentRow.orderStatus
        }
        this.$refs.boxing.init(inData)
      })
    },
    refreshPalletTable(){
      this.$nextTick(() => {
        // 检查组件引用是否存在
        if (!this.$refs.pallet) {
          return;
        }
        // 检查 init 方法是否存在且是函数
        if (typeof this.$refs.pallet.init !== 'function') {
          return;
        }

        // 准备初始化数据，即使没有选中行也要初始化组件
        let inData={
          site: this.currentRow ? this.currentRow.site : '',
          buNo: this.currentRow ? this.currentRow.buNo : '',
          orderNo: this.currentRow ? this.currentRow.orderNo : '',
          palletType: this.currentRow ? this.currentRow.orderType : '',
          height: Number(this.height)-25,
          orderStatus: this.currentRow ? this.currentRow.orderStatus : ''
        }
        this.$refs.pallet.init(inData)
      })
    },
    refreshRollsTable(){
      let templateData = {
        site: this.currentRow.site,
        buNo: this.currentRow.buNo,
        orderNo: this.currentRow.orderNo,
      }
      searchRollForOrderNo(templateData).then(({data}) => {
        this.rollList = data.rows
      })
    },

    // ===== 盒清单相关方法 =====
    refreshCasesTable(){
      let templateData = {
        site: this.currentRow.site,
        buNo: this.currentRow.buNo,
        notifyNo: this.currentRow.orderNo,
      }
      searchSoReceiveCasesData(templateData).then(({data}) => {
        this.casesList = data.rows || []
        // 更新统计数据 - 从列表第一条记录中获取
        if (data.rows && data.rows.length > 0) {
          const firstRecord = data.rows[0]
          this.casesStatistics.boxCountCases = firstRecord.boxCountCases || 0
          this.casesStatistics.boxCountRolls = firstRecord.boxCountRolls || 0
          this.casesStatistics.totalQty = firstRecord.totalQty || 0
        } else {
          this.casesStatistics.boxCountCases = 0
          this.casesStatistics.boxCountRolls = 0
          this.casesStatistics.totalQty = 0
        }
      })
    },

    openCaseDialog(){
      if(!this.currentRow || !this.currentRow.orderNo){
        this.$message.warning('请先选择一条出库单记录')
        return
      }
      this.caseDialogVisible = true
      this.resetCaseForm()
      // 对话框打开后自动聚焦到卷标签输入框
      this.$nextTick(() => {
        this.$refs.rollNoInput.focus()
      })
    },

    resetCaseForm(){
      this.caseForm = {
        casesNo: '',
        rollNo: '',
        site: this.currentRow.site,
        buNo: this.currentRow.buNo,
        notifyNo: this.currentRow.orderNo,
        partNo: ''
      }
      this.caseRollList = []
      this.selectedCaseRolls = []
      this.updateCaseStatistics()
    },

    async scanCaseRoll(){
      // 校验必填项
      if(!this.caseForm.rollNo){
        this.$message.warning('请扫描卷标签')
        return
      }

      // 将卷标签值赋给盒标签（casesNo = rollNo）
      this.caseForm.casesNo = this.caseForm.rollNo

      // 从当前行获取物料编码
      let partNo = this.currentRow.partNo || ''
      this.caseForm.partNo = partNo

      try {
        const {data} = await validateAndScanCaseRoll(this.caseForm)
        if(data && data.code === 0){
          // 后端现在返回的是集合，需要遍历所有记录
          const rollList = data.rollInfo || []

          if(rollList.length === 0){
            this.$message.warning('未查询到卷数据')
            this.caseForm.rollNo = ''
            this.$refs.rollNoInput.focus()
            return
          }

          // 检查卷标签是否重复（根据 site 和 rollNo）
          const duplicateRolls = []
          const newRolls = []

          rollList.forEach(rollInfo => {
            // 检查当前列表中是否已存在相同 site 和 rollNo 的记录
            const isDuplicate = this.caseRollList.some(item =>
              item.site === this.caseForm.site && item.rollNo === rollInfo.rollNo
            )

            if (isDuplicate) {
              duplicateRolls.push(rollInfo.rollNo)
            } else {
              newRolls.push(rollInfo)
            }
          })

          // 如果有重复的卷标签，提示用户
          if (duplicateRolls.length > 0) {
            this.$message.warning(`以下卷标签已存在，不能重复添加：${duplicateRolls.join(', ')}`)
          }

          // 只添加不重复的卷到列表最前面（后扫描的在上面）
          newRolls.forEach(rollInfo => {
            this.caseRollList.unshift({
              casesNo: this.caseForm.casesNo,
              rollNo: rollInfo.rollNo,
              rollQty: rollInfo.rollQty,
              partNo: rollInfo.partNo,
              partDesc: rollInfo.partDesc,
              batchNo: rollInfo.batchNo,
              notifyNo: this.caseForm.notifyNo,
              site: this.caseForm.site,
              buNo: this.caseForm.buNo
            })
          })

          // 更新统计信息
          this.updateCaseStatistics()

          // 重置输入框，准备下一次扫描
          this.caseForm.casesNo = ''
          this.caseForm.rollNo = ''

          // 光标回到卷标签输入框，继续扫描
          this.$nextTick(() => {
            this.$refs.rollNoInput.focus()
          })

          // 提示添加成功（仅显示实际添加的记录数）
          if (newRolls.length > 0) {
            this.$message.success(`扫描成功，添加了 ${newRolls.length} 条记录`)
          }
        } else {
          this.$message.error(data.msg || '扫描失败')
        }
      } catch (error) {
        this.$message.error(error.msg || '扫描失败，请检查')
        // 清空卷标签输入框
        this.caseForm.rollNo = ''
        this.$refs.rollNoInput.focus()
      }
    },

    updateCaseStatistics(){
      // 盒数量 = 去重的盒标签数量
      const uniqueCases = new Set(this.caseRollList.map(item => item.casesNo))
      this.caseStatistics.casesCount = uniqueCases.size

      // 卷数量 = 列表行数
      this.caseStatistics.rollCount = this.caseRollList.length

      // 物料总数 = 所有行的卷数量求和
      this.caseStatistics.totalQty = this.caseRollList.reduce((sum, item) => {
        return sum + (parseFloat(item.rollQty) || 0)
      }, 0)
    },

    // 从扫描列表中删除某一行
    deleteRollFromList(index){
      this.$confirm('确定删除这条扫描记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.caseRollList.splice(index, 1)
        this.updateCaseStatistics()
        this.$message.success('删除成功')
      }).catch(() => {})
    },

    async applyCaseScan(){
      if(this.caseRollList.length === 0){
        this.$message.warning('请先扫描卷标签')
        return
      }

      // 校验数量
      if(!await this.validateCaseQty()){
        return
      }

      // 应用：保存但不关闭对话框，重置输入框、计数和列表
      this.saveCaseData(false)
    },

    async saveCaseScan(){
      if(this.caseRollList.length === 0){
        this.$message.warning('请先扫描卷标签')
        return
      }

      // 校验数量
      if(!await this.validateCaseQty()){
        return
      }

      // 保存：保存后关闭对话框
      this.saveCaseData(true)
    },

    // 校验盒清单数量不能超过要求发货数量
    async validateCaseQty(){
      // 获取当前主信息行的要求发货数量
      const requiredQty = parseFloat(this.currentRow.requiredQty) || 0
      if(requiredQty === 0){
        this.$message.warning('要求发货数量为0，无需装箱')
        return false
      }

      // 计算新扫描的数据总量
      const newScanQty = this.caseRollList.reduce((sum, item) => {
        return sum + (parseFloat(item.rollQty) || 0)
      }, 0)

      // 查询已保存的盒清单数据，计算已装箱的总数量
      try {
        let templateData = {
          site: this.currentRow.site,
          buNo: this.currentRow.buNo,
          notifyNo: this.currentRow.orderNo,
        }
        const {data} = await searchSoReceiveCasesData(templateData)
        const existingQty = (data.rows || []).reduce((sum, item) => {
          // 只统计相同物料的数量
          if(item.partNo === this.currentRow.partNo){
            return sum + (parseFloat(item.rollQty) || 0)
          }
          return sum
        }, 0)

        // 总数量 = 已装箱数量 + 新扫描数量
        const totalQty = existingQty + newScanQty

        if(totalQty > requiredQty){
          this.$message.error(`装箱数量超出限制！要求发货数量：${requiredQty}，本次扫描：${newScanQty}，总计：${totalQty}`)
          return false
        }

        return true
      } catch (error) {
        this.$message.error('校验数量失败，请重试')
        return false
      }
    },

    async saveCaseData(closeDialog){
      try {
        const {data} = await saveCaseRollList(this.caseRollList)
        if(data && data.code === 0){
          this.$message.success('保存成功')

          if(closeDialog){
            // 关闭对话框
            this.closeCaseDialog()
          } else {
            // 应用：重置表单继续扫描
            this.resetCaseForm()
            this.$nextTick(() => {
              this.$refs.caseNoInput.focus()
            })
          }

          // 刷新盒清单列表
          this.refreshCasesTable()
        } else {
          this.$message.error(data.msg || '保存失败')
        }
      } catch (error) {
        this.$message.error(error.msg || '保存失败')
      }
    },

    closeCaseDialog(){
      this.caseDialogVisible = false
      this.resetCaseForm()
    },

    handleCaseSelectionChange(selection){
      this.selectedCaseRecords = selection
    },

    // 装盒对话框中卷标签选择变化
    handleCaseRollSelectionChange(selection){
      this.selectedCaseRolls = selection
    },

    // 打印选中的卷标签
    async printCaseRolls(){
      if(this.selectedCaseRolls.length === 0){
        this.$message.warning('请先选择要打印的卷标签')
        return
      }

      this.printLoading = true
      try {
        // 1. 获取 LODOP 打印控件
        const LODOP = getLodop()
        if (!LODOP) {
          this.$message.error('无法连接到打印控件，请确保已安装并启动 CLodop！')
          this.printLoading = false
          return
        }

        // 2. 获取默认打印机
        const printerCount = LODOP.GET_PRINTER_COUNT()
        if (printerCount <= 0) {
          this.$message.error('未检测到打印机，请确保已安装并连接打印机！')
          this.printLoading = false
          return
        }

        // 3. 循环调用存储过程获取打印参数并打印
        for (const rollItem of this.selectedCaseRolls) {
          const params = {
            site: this.currentRow.site,
            buNo: this.currentRow.buNo,
            menuID: this.$route.meta.menuId,
            relatedOrderNo: this.currentRow.orderNo,
            relatedOrderLineNo: this.currentRow.relatedOrderLineNo || '',
            documentNo: this.currentRow.orderNo,
            partNo: rollItem.partNo,
            labelNo: '',
            rollNo: rollItem.rollNo
          }

          const {data: printData} = await callUspPartLabelTemplate(params)
          if (printData && printData.code === 0 && printData.row) {
            const labelData = printData.row

            // 初始化打印任务
            LODOP.PRINT_INIT('卷标签打印_' + rollItem.rollNo)
            LODOP.SET_PRINT_MODE("PRINT_NOCOLLATE", true)

            // 根据 labelNo 调用不同的打印方法
            if (labelData.labelNo === 'A001') {
              await this.printLabelA001(LODOP, labelData, false)
            } else if (labelData.labelNo === 'A002') {
              this.printLabelA002(LODOP, labelData, false)
            } else if (labelData.labelNo === 'A003') {
              this.printLabelA003(LODOP, labelData, false)
            } else if (labelData.labelNo === 'A004') {
              this.printLabelA004(LODOP, labelData, false)
            } else {
              console.warn(`未知的标签模板：${labelData.labelNo}，跳过该标签`)
              continue
            }

            // 执行打印
            LODOP.PRINT()
            console.log(`标签已发送打印, 卷号: ${rollItem.rollNo}`)
          } else {
            console.warn(`获取卷号 ${rollItem.rollNo} 的打印参数失败`)
          }
        }

        this.$message.success('打印任务已发送！')
      } catch (error) {
        console.error('打印标签失败:', error)
        this.$message.error('打印标签失败: ' + (error.message || '请重试'))
      } finally {
        this.printLoading = false
      }
    },

    async deleteCaseRecord(){
      if(this.selectedCaseRecords.length === 0){
        this.$message.warning('请先选择要删除的记录')
        return
      }

      this.$confirm('确定删除选中的记录吗？删除后将恢复库存卷的装盒状态', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          for(let record of this.selectedCaseRecords){
            await deleteSoReceiveCasesData({
              id: record.id,
              site: record.site,
              buNo: record.buNo
            })
          }
          this.$message.success('删除成功')
          this.refreshCasesTable()
        } catch (error) {
          this.$message.error(error.msg || '删除失败')
        }
      }).catch(() => {})
    },

    // 处理完成操作
    async handleComplete(row){
      this.$confirm('是否包装完成？完成后将创建检验任务', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(async () => {
        try {
          const {data} = await this.$http({
            url: this.$http.adornUrl('/boxForNotification/completePacking'),
            method: 'post',
            data: this.$http.adornData({
              site: row.site,
              buNo: row.buNo,
              orderNo: row.orderNo,
              partNo: row.partNo,
              customerId: row.customerId,
              relatedOrderNo: row.relatedOrderNo,
              relatedOrderLineNo: row.relatedOrderLineNo,
              requiredQty: row.requiredQty,
              orderQty: row.orderQty
            })
          })
          if(data && data.code === 0){
            this.$message.success('包装完成，检验任务已创建')
            // 刷新列表
            this.getMainData()
          } else {
            this.$message.error(data.msg || '操作失败')
          }
        } catch (error) {
          this.$message.error(error.msg || '操作失败，请重试')
        }
      }).catch(() => {
        // 用户点击了"否"，不做任何操作
      })
    },
  },
  created() {
    //查询报表的类型
    this.getMainData();
  },


}
</script>

<!--当前页面的标签样式-->
<style scoped lang="scss">

/deep/ .customer-tab .el-tabs__content {
  padding: 5px !important;
}


</style>
