<template>
  <div class="customer-css">
    <div style="display: flex; align-items: center; margin-top: 1px; margin-left: 0px;">
      <div>
        <el-button type="primary" @click="searchTable()">查询</el-button>
        <el-button v-if="searchData.orderStatus === '待包装'" type="primary" @click="newBox()">新增箱</el-button>
        <el-button type="primary" @click="printCartonLabels()" :disabled="selectedBoxes.length <= 0">打印</el-button>
      </div>
      <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;">{{boxingStatistics.boxCount}}</span>
        </span>
        <span style="margin-right: 20px;">
          <span style="color: #606266;">卷标签张数：</span>
          <span style="color: rgb(38, 92, 147); font-weight: bold;">{{boxingStatistics.rollCount}}</span>
        </span>
        <span>
          <span style="color: #606266;">物料总数：</span>
          <span style="color: rgb(38, 92, 147); font-weight: bold;">{{boxingStatistics.rollsCount}}</span>
        </span>
      </span>
    </div>
    <el-table
      :data="dataList"
      :height=searchData.height
      border
      v-loading="dataListLoading"
      @selection-change="handleSelectionChange"
      style="width: 100%; ">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        v-for="(item,index) in columnList" :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"> {{scope.row[item.columnProp]}}</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
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-link style="cursor: pointer" v-if="scope.row.status!=='未封箱'" @click="boxModelOpen(scope.row)">查看</el-link>
          <template v-if="searchData.orderStatus === '待包装'">
            <el-link style="cursor: pointer" v-if="scope.row.status!=='已封箱'"@click="boxModelOpen(scope.row)">装箱</el-link>
            <el-link style="cursor: pointer" v-if="scope.row.status==='未封箱'" @click="fengxiang(scope.row)">封箱</el-link>
            <el-link style="cursor: pointer" v-if="scope.row.status==='已封箱'" @click="chaixiang(scope.row)">拆箱</el-link>
            <el-link style="cursor: pointer" v-if="scope.row.status!=='已封箱'" @click="deleteBox(scope.row)">删除</el-link>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="卷清单"  :visible.sync="boxModelFlag" width="700px" @close="searchTable" style="margin-top: 7px"  v-drag :close-on-click-modal="false">
      <el-form class="sl" inline="inline" label-position="top"  style="margin-left: 7px;margin-top: -5px;">
        <el-row>
          <el-form-item label="销售发货单号">
            <el-input v-model="boxData.orderNo" disabled style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item label="箱号">
            <el-input v-model="boxData.boxNo" disabled style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item label="所在仓库">
            <el-input v-model="boxData.wareHouseID" disabled style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item label="标准装箱数量">
            <el-input v-model="boxData.stdPackingQty" disabled style="width: 130px" class="std-packing-qty-input"></el-input>
          </el-form-item>
        </el-row>
        <el-row v-if="!scanDisabled" style="display: flex; align-items: flex-end;">
          <el-form-item label="扫描装箱">
            <el-input v-model="scanRollNo" ref="scanRollNo" :disabled="scanDisabled" @keyup.enter.native="handleBoxAction" style="width: 200px"></el-input>
          </el-form-item>
<!--          <el-form-item label="操作类型">-->
<!--            <el-radio-group v-model="boxActionType" size="small">-->
<!--              <el-radio-button  label="add">添加</el-radio-button>-->
<!--              <el-radio-button  label="delete">删除</el-radio-button>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
          <el-form-item label="操作类型" >
            <el-radio-group v-model="boxActionType" >
              <el-radio label="add" border>添加</el-radio>
              <el-radio label="delete" border>删除</el-radio>
            </el-radio-group>
          </el-form-item>
          <span style="margin-left: auto; font-size: 14px; display: inline-block; padding-bottom: 5px; white-space: nowrap;">
            <span style="margin-right: 20px;">
              <span style="color: #606266;">卷标签张数：</span>
              <span style="color: rgb(38, 92, 147); font-weight: bold;">{{boxStatistics.rollCount}}</span>
            </span>
            <span>
              <span style="color: #606266;">物料总数：</span>
              <span style="color: rgb(38, 92, 147); font-weight: bold;">{{boxStatistics.totalQty}}</span>
            </span>
          </span>
        </el-row>
      </el-form>
        <el-table
          :height="300"
          :data="modelList"
          stripe
          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="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>
      <el-footer style="height:40px;margin-top: 25px;text-align:center">
        <el-button @click="boxModelFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<script>

import {
  deleteBoxRoll,
  deleteSoReceiveBoxesData,
  newSoReceiveBoxesData, scanBoxRoll,
  searchBoxDetail,
  searchSoReceiveBoxesData, updateBoxStatus
} from '../../../api/boxManage/boxManage'
import CartonLabelPrint from './CartonLabelPrint.vue'
import Vue from 'vue'
import getLodop from '@/utils/LodopFuncs.js'
import QRCode from 'qrcode'

export default {
  components: {

  },
  data() {
    return {
      dataList: [],
      searchData: {
        site: '',
        username: '',
        buNo: '',
        orderNo: '',
        boxType: '',
        orderStatus: '',
        height:'300',
        page: 1,
        limit: 1000
      },
      scanDisabled: false,
      dataListLoading: false,
      currentRow:'',
      columnList: [
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '750001Table2BoxNo',
          tableId: "750001Table2",
          tableName: "装箱清单",
          columnProp: "boxNo",
          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: '750001Table2Status',
          tableId: "750001Table2",
          tableName: "装箱清单",
          columnProp: "status",
          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: '750001Table2RollsQty',
          tableId: "750001Table2",
          tableName: "装箱清单",
          columnProp: "rollsQty",
          headerAlign: "center",
          align: "right",
          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: '750001Table2RollsCount',
          tableId: "750001Table2",
          tableName: "装箱清单",
          columnProp: "rollsCount",
          headerAlign: "center",
          align: "right",
          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: '750001Table2WareHouseID',
          tableId: "750001Table2",
          tableName: "装箱清单",
          columnProp: "wareHouseID",
          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: '750001Table2WareHouseName',
          tableId: "750001Table2",
          tableName: "装箱清单",
          columnProp: "wareHouseName",
          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: '750001Table2CreatedBy',
          tableId: "750001Table2",
          tableName: "装箱清单",
          columnProp: "createdBy",
          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: '750001Table2CreatedDate',
          tableId: "750001Table2",
          tableName: "装箱清单",
          columnProp: "createdDate",
          headerAlign: "center",
          align: "left",
          columnLabel: "创建时间",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
      ],
      modelList:[],
      rollList:[],
      boxData:{
        site:'',
        orderNo:'',
        boxNo:'',
        buNo:'',
        wareHouseID:'',
        rollsQty: 0,
        stdPackingQty: 0, // 标准装箱数量
      },
      scanRollNo:'',
      boxModelFlag: false,
      boxActionType: 'add', // 新增：添加/删除模式
      selectedBoxes: [], // 选中的外箱列表
      boxingStatistics: {
        boxCount: 0,      // 箱标签张数
        rollCount: 0,     // 卷标签张数
        rollsCount: 0     // 物料总数
      }
    }
  },
  computed: {
    // 装箱统计
    boxStatistics() {
      return {
        rollCount: this.modelList.length, // 卷标签张数
        totalQty: this.modelList.reduce((sum, item) => sum + (parseFloat(item.rollQty) || 0), 0) // 物料总数
      };
    }
  },
  methods: {
    //初始化组件的参数
    init(inData) {
      //初始化参数
      this.searchData = JSON.parse(JSON.stringify(inData));
      //刷新表格
      this.searchTable();
    },
    searchTable(){
      searchSoReceiveBoxesData(this.searchData).then(({data}) => {
        //区分请求成功和失败的状况
        if (data && data.code == 0) {
          this.dataList = data.rows
          // 更新统计数据 - 从列表第一条记录中获取
          if (data.rows && data.rows.length > 0) {
            const firstRecord = data.rows[0]
            this.boxingStatistics.boxCount = firstRecord.boxCount || 0
            this.boxingStatistics.rollCount = firstRecord.rollCount || 0
            this.boxingStatistics.rollsCount = firstRecord.rollsCount || 0
          } else {
            this.boxingStatistics.boxCount = 0
            this.boxingStatistics.rollCount = 0
            this.boxingStatistics.rollsCount = 0
          }
        } else {
          this.dataList = [];
          // 清空统计数据
          this.boxingStatistics.boxCount = 0
          this.boxingStatistics.rollCount = 0
          this.boxingStatistics.rollsCount = 0
        }
      });
    },
    newBox(){
      this.$confirm(`确定为此销售发货单新建箱?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let inData={
          site: this.searchData.site,
          createdBy: this.$store.state. user.name,
          buNo: this.searchData.buNo,
          orderNo: this.searchData.orderNo,
          saleOrderNo: this.searchData.saleOrderNo || '', // 销售订单号，用于生成箱号
          boxType: this.searchData.boxType,
          status:'未封箱',
          rollsQty: 0,
        }
        newSoReceiveBoxesData(inData).then(({data}) => {
          if (data && data.code == 0) {
            this.$message.success( '操作成功')
            this.searchTable();
            let data2={
              site: this.searchData.site,
              boxNo: data.boxNo,
              buNo: this.searchData.buNo,
            }
            this.searchBox(data2)
            this.boxModelFlag = true
            this.boxActionType='add'
            this.$nextTick(() => {
              this.$refs.scanRollNo.focus();
            });
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      })
    },
    boxModelOpen(row){
      let inData={
        site: row.site,
        boxNo: row.boxNo,
        buNo: row.buNo,
      }
      this.searchBox(inData)
      if(row.status==='未封箱'){
        this.scanDisabled=false
      }else {
        this.scanDisabled = true
      }
      this.scanRollNo=''
      this.boxModelFlag = true
      this.boxActionType='add'
      this.$nextTick(() => {
        this.$refs.scanRollNo.focus();
      });
    },
    searchBox(inData){
      searchBoxDetail(inData).then(({data}) => {
        if (data && data.code == 0) {
          this.modelList=data.rows
          this.boxData=data.row
        }
      })
    },
    deleteBox(row){
      this.$confirm(`确定删除此箱?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSoReceiveBoxesData(row).then(({data}) => {
          if (data && data.code == 0) {
            this.$message.success( '操作成功')
            this.searchTable();
          } else {
            this.$message.error( data.msg)
          }
        })
      })
    },
    fengxiang(row){
      this.$confirm(`确定封箱?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let inData={
          site: row.site,
          boxNo: row.boxNo,
          buNo: row.buNo,
          id: row.id,
          flag:0,
        }
        updateBoxStatus(inData).then(({data}) => {
          if (data && data.code == 0) {
            this.$message.success( '操作成功')
            this.searchTable();
          }else {
            this.$message.error( data.msg)
          }
        })
      })
    },
    chaixiang(row){
      this.$confirm(`确定封箱?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let inData={
          site: row.site,
          boxNo: row.boxNo,
          buNo: row.buNo,
          id: row.id,
          flag:1,
        }
        updateBoxStatus(inData).then(({data}) => {
          if (data && data.code == 0) {
            this.$message.success( '操作成功')
            this.searchTable();
          }else {
            this.$message.error( data.msg)
          }
        })
      })
    },

    // 多选变化
    handleSelectionChange(val) {
      this.selectedBoxes = val
    },
    // 打印外箱标签 - 纸张尺寸：70mm x 20mm
    async printCartonLabels() {
      if (this.selectedBoxes.length === 0) {
        this.$message.warning('请选择要打印的外箱!')
        return
      }

      const LODOP = getLodop()
      if (!LODOP) {
        this.$message.error('未检测到打印控件，请安装CLodop打印控件!')
        return
      }

      try {
        // 初始化打印
        LODOP.PRINT_INIT('外箱标签打印')

        // 纸张尺寸设置：宽度=700(70mm), 高度=200(20mm)
        LODOP.SET_PRINT_PAGESIZE(0, 700, 200, '')

        // 循环打印每个选中的外箱
        for (let i = 0; i < this.selectedBoxes.length; i++) {
          const box = this.selectedBoxes[i]

          if (i > 0) {
            LODOP.NEWPAGE() // 新页
          }

          // ===== 绘制边框和分隔线 =====
          // 外边框: ADD_PRINT_RECT(上边距, 左边距, 宽度, 高度, 线宽, 线型)
          LODOP.ADD_PRINT_RECT('2mm', '2mm', '66mm', '16mm', 0, 1)

          // 中间竖线(左右分隔): ADD_PRINT_LINE(起点Y, 起点X, 终点Y, 终点X, 线宽, 线型)
          // 优化：竖线在54mm位置，左侧文字52mm，右侧二维码14mm
          LODOP.ADD_PRINT_LINE('2mm', '55mm', '18mm', '55mm', 0, 1)

          // 左侧横线(NO.和Carton No.之间): ADD_PRINT_LINE(起点Y, 起点X, 终点Y, 终点X, 线宽, 线型)
          LODOP.ADD_PRINT_LINE('10mm', '2mm', '10mm', '55mm', 0, 1)

          // ===== 左侧文字信息 =====
          // NO.文字: ADD_PRINT_TEXT(上边距, 左边距, 宽度, 高度, 内容)
          // 文字区域：从3mm到54mm，宽度50mm，字号5，Arial字体紧凑显示
          const text1 = LODOP.ADD_PRINT_TEXT('4.5mm', '3mm', '52mm', '5mm', 'NO:' + (this.searchData.orderNo || ''))
          LODOP.SET_PRINT_STYLEA(text1, "FontName", "Arial")   // 使用Arial，紧凑字体
          LODOP.SET_PRINT_STYLEA(text1, "FontSize", 5)         // 5号字体
          LODOP.SET_PRINT_STYLEA(text1, "Bold", 1)             // 粗体

          // Carton No.文字: ADD_PRINT_TEXT(上边距, 左边距, 宽度, 高度, 内容)
          const text2 = LODOP.ADD_PRINT_TEXT('12.5mm', '3mm', '52mm', '5mm', 'Carton No:' + (box.boxNo || ''))
          LODOP.SET_PRINT_STYLEA(text2, "FontName", "Arial")   // 使用Arial
          LODOP.SET_PRINT_STYLEA(text2, "FontSize", 5)         // 5号字体
          LODOP.SET_PRINT_STYLEA(text2, "Bold", 1)             // 粗体

          // ===== 右侧二维码 =====
          // 二维码: ADD_PRINT_BARCODE(上边距, 左边距, 宽度, 高度, 类型, 内容)
          // 右侧区域：从54mm到68mm(宽14mm)，二维码12mm x 12mm，居中显示
          const qrIndex = LODOP.ADD_PRINT_BARCODE('4mm', '56mm', '12.6mm', '12.6mm', 'QRCode', box.boxNo)
          LODOP.SET_PRINT_STYLEA(qrIndex, "QRCodeVersion", 3)  // 二维码版本3，适中大小
          LODOP.SET_PRINT_STYLEA(qrIndex, "QRCodeErrorLevel", "L")  // M级纠错，平衡大小和容错
        }

        // 执行打印
        //LODOP.PREVIEW()  // 取消注释可预览
        LODOP.PRINT();

      } catch (error) {
        console.error('打印失败:', error)
        this.$message.error('打印失败: ' + error.message)
      }
    },
    handleBoxAction() {
      // const arr = this.scanRollNo.split(';');
      // if (arr.length < 3) {
      //   this.$message.error('扫描的标签格式不正确！');
      //   return;
      // }
      if(this.scanRollNo==null||this.scanRollNo===''){
        this.$message.error('请扫描标签！');
      }
      const inData = {
        site: this.boxData.site,
        buNo: this.boxData.buNo,
        finalRollNo: this.scanRollNo,
        boxNo: this.boxData.boxNo,
      };
      if(this.boxActionType==='add'){
        scanBoxRoll(inData).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('扫描成功');
            this.searchBox({
              site: this.boxData.site,
              boxNo: this.boxData.boxNo,
              buNo: this.boxData.buNo,
            });
            this.scanRollNo = '';
            this.$nextTick(() => {
              this.$refs.scanRollNo.focus();
            });
          } else {
            this.$message.error(data.msg || '扫描失败');
            this.scanRollNo = '';
            this.$nextTick(() => {
              this.$refs.scanRollNo.focus();
            });
          }
        }).catch(() => {
          this.$message.error('网络异常，扫描失败');
          this.scanRollNo = '';
          this.$nextTick(() => {
            this.$refs.scanRollNo.focus();
          });
        });
      }else {

        deleteBoxRoll(inData).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('扫描成功');
            this.searchBox({
              site: this.boxData.site,
              boxNo: this.boxData.boxNo,
              buNo: this.boxData.buNo,
            });
            this.scanRollNo = '';
            this.$nextTick(() => {
              this.$refs.scanRollNo.focus();
            });
          } else {
            this.$message.error(data.msg || '扫描失败');
            this.scanRollNo = '';
            this.$nextTick(() => {
              this.$refs.scanRollNo.focus();
            });
          }
        }).catch(() => {
          this.$message.error('网络异常，扫描失败');
          this.scanRollNo = '';
          this.$nextTick(() => {
            this.$refs.scanRollNo.focus();
          });
        });
      }

    }
  },
  watch: {
    boxActionType() {
      this.$nextTick(() => {
        if (this.$refs.scanRollNo) {
          this.$refs.scanRollNo.focus();
        }
      });
    }
  },
}
</script>

<style scoped lang="scss">

.rq .auto /deep/ .el-form-item__content{
  height: auto;
  line-height: 1.5;
}
/deep/ .el-table__fixed-right-patch {
  display: none !important;
}
.sl .el-radio--medium.is-bordered {
  padding: 2px 5px 0px 5px;
  border-radius: 4px;
  height: 20px;
}
/* 标准装箱数量输入框右对齐 */
.std-packing-qty-input /deep/ .el-input__inner {
  text-align: right;
}
</style>
