<script>
import PictureModule from '../part/picture/picture.vue'
import {getExternalPartCustomerList, getExternalPartCustomerPage} from '../../../api/part/externalPartCustomer'
import {getExternalPartPictureList} from '../../../api/part/externalPartPicture'
import ExternalPart from '../part/external.vue'
import CustomerInfo from '../customer/info.vue'
import {getExternalPartManufacturerList} from '../../../api/part/externalPartManufacturer'
import {
  getLabelFormatUserDefaultList,
  selectLabelFormatUserDefaultListByUserId
} from '../../../api/label/labelFormatUserDefault'
import LinkedFormat from './format/linkedFormat.vue'
import {Decimal} from 'decimal.js'
import {savePrintLabelRecord} from '../../../api/label/printLabelRecord'
import dayjs from 'dayjs'
import {printAlphaHardTagLabel} from '../../../printFormat/alphaHardTagPrintFormat'
import {printAntennaLabel} from '../../../printFormat/antenna'
import {printRF_RFIDLabel} from '../../../printFormat/RF_RFID'

import getLodop from '@/utils/LodopFuncs.js'
import {getTableDefaultListLanguage, getTableUserListLanguage} from '../../../api/table'
import {getCategory, getCategoryList} from '../../../api/category/category'
import QrCode from './QrCode.vue'
import {savePrintRollLabelRecord} from '../../../api/label/printRollLabelRecord'
import {print_roll_label} from '../../../printFormat/roll_label'
import {saveLogisticLabelRecord} from '../../../api/label/LogisticLabelRecord'
import {printLogisticLabel} from '../../../printFormat/logisticLabel'
import {queryExternalLabelTemplate} from '../../../api/part/externalLabelTemplate'
import {download} from '../../../api/oss/oss'
import {savePartInfoByExcel} from '../../../api/part/external'
import {importSerialNumber} from '../../../api/print/print'

const printer = {
  customerNo: '',
  customerName: '',
  partNo: '',
  partDesc: '',
  active: 'Y',
  category: '',
  qtyPerCarton: 0,
  totalShipQty: 0,
  cartonCount: 1,
  manufacturerTime: '',
  manufacturerNo: '',
  moldCode: '',
  serialNumber: '',
  manufacturerRequired: '',
  moldCodeRequired: '',
  serialNumberRequired: '',
  qtyPerRoll: 0,
  rollsPerCarton: 0,
  orderNo: '',
  templateNo:'',
  printLabelType:0,
}
export default {
  name: 'printer',
  components: {QrCode, LinkedFormat, CustomerInfo, ExternalPart, PictureModule},
  props:{
    height:{
      type:Number,
      default:300
    },
  },
  data(){
    return{
      no:1,
      size:50,
      total:0,
      rowSpan: 8,
      printerSetupList:[],
      currentPrinter: '',
      printType: 'alphaHardTag',
      printLoading:false,
      searchPrinter: {
        ...printer
      },
      partCategoryList:[

      ],
      partVisible:false,
      customerVisible:false,
      printerList:[],
      activeName:"picture",
      currentPart:{

      },
      printCurrentPart:{
        ...printer
      },
      printVisible:false,
      pictureList:[],
      printRules:{
        moldCode: [{required: true, message: 'Please input Mold Code', trigger: ['blur','change']}],
        manufacturerNo: [{required: true, message: 'Please input Manufacturer', trigger: ['blur','change']}],
        serialNumber: [{required: true, message: 'Please input Serial Number', trigger: ['blur','change']}],
        qtyPerCarton: [{required: true, message: 'Please input Qty Per Carton', trigger: ['blur','change']}],
        rollsPerCarton: [{required: true, message: 'Please input Rolls Per Carton', trigger: ['blur','change']}],
        qtyPerRoll: [{required: true, message: 'Please input Qty Per Roll', trigger: ['blur','change']}],
        totalShipQty: [{required: true, message: 'Please input Total Ship Qty', trigger: ['blur','change']}],
        cartonCount: [{required: true, message: 'Please input Carton Count', trigger: ['blur','change']}],
        manufacturerTime: [{required: true, message: 'Please input Manufacturer Date', trigger: ['blur','change']}],
        orderNo: [{required: true, message: 'Please input PO', trigger: ['blur','change']}],
        poNo: [{required: true, message: 'Please input PO No', trigger: ['blur','change']}],
        invoiceNo: [{required: true, message: 'Please input Invoice No', trigger: ['blur','change']}],
        unitQtyPerPallet: [{required: true, message: 'Please input Unit Qty Per Pallet', trigger: ['blur','change']}],
        countOfPallets: [{required: true, message: 'Please input Count Of Pallets', trigger: ['blur','change']}],
      },
      columnList:[
        {
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableCustomerNo',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "customerNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "Customer No",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableCustomerName',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "customerName",
          headerAlign: "center",
          align: "left",
          columnLabel: "Customer Name",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TablePartNo',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "partNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "Part No",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TablePartDesc',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "partDesc",
          headerAlign: "center",
          align: "left",
          columnLabel: "Part Description",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableRev',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "rev",
          headerAlign: "center",
          align: "left",
          columnLabel: "Part REV",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableCategory',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "category",
          headerAlign: "center",
          align: "left",
          columnLabel: "Part Category",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableUmName',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "umName",
          headerAlign: "center",
          align: "left",
          columnLabel: "UM",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableFreeInfo',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "freeInfo",
          headerAlign: "center",
          align: "left",
          columnLabel: "Free Info",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableFreeInfo2',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "freeInfo2",
          headerAlign: "center",
          align: "left",
          columnLabel: "OOC",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },
        {
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableTradingMark',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "tradingMark",
          headerAlign: "center",
          align: "left",
          columnLabel: "Trading Mark",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TablePackingWeight',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "packingWeight",
          headerAlign: "center",
          align: "left",
          columnLabel: "Packing Weight",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableWeightUM',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "weightUmName",
          headerAlign: "center",
          align: "left",
          columnLabel: "Weight UM",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },
        {
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004TableActive',
          tableId: "30004Table",
          tableName: "Part Customer Table",
          columnProp: "active",
          headerAlign: "center",
          align: "left",
          columnLabel: "Active",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }
      ],
      pictureColumnList:[
        {
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table2PictureNo',
          tableId: "30004Table2",
          tableName: "外部料号图片信息表",
          columnProp: "certificationNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "Certification Code",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table2PictureDesc',
          tableId: "30004Table2",
          tableName: "外部料号图片信息表",
          columnProp: "pictureDesc",
          headerAlign: "center",
          align: "left",
          columnLabel: "Certification Desc",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 180
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table2CreateBy',
          tableId: "30004Table2",
          tableName: "外部料号图片信息表",
          columnProp: "createBy",
          headerAlign: "center",
          align: "left",
          columnLabel: "Created By",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table2CreateTime',
          tableId: "30004Table2",
          tableName: "外部料号图片信息表",
          columnProp: "createTime",
          headerAlign: "center",
          align: "center",
          columnLabel: "Created Time",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 180
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table2UpdateBy',
          tableId: "30004Table2",
          tableName: "外部料号图片信息表",
          columnProp: "updateBy",
          headerAlign: "center",
          align: "left",
          columnLabel: "Updated By",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table2UpdateTime',
          tableId: "30004Table2",
          tableName: "外部料号图片信息表",
          columnProp: "updateTime",
          headerAlign: "center",
          align: "center",
          columnLabel: "Updated Time",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 180
        },
      ],
      formatColumnList:[
        {
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table3LabelType',
          tableId: "30004Table3",
          tableName: "标签模板信息表",
          columnProp: "labelType",
          headerAlign: "center",
          align: "center",
          columnLabel: "Label Type",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table3FormatId',
          tableId: "30004Table3",
          tableName: "标签模板信息表",
          columnProp: "formatId",
          headerAlign: "center",
          align: "left",
          columnLabel: "Format ID",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 180
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table3FormatDesc',
          tableId: "30004Table3",
          tableName: "标签模板信息表",
          columnProp: "formatDesc",
          headerAlign: "center",
          align: "left",
          columnLabel: "Format Desc",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 180
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table3DefaultFormat',
          tableId: "30004Table3",
          tableName: "标签模板信息表",
          columnProp: "defaultFlag",
          headerAlign: "center",
          align: "center",
          columnLabel: "Default Format",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table3Remark',
          tableId: "30004Table3",
          tableName: "标签模板信息表",
          columnProp: "remark",
          headerAlign: "center",
          align: "left",
          columnLabel: "Remark",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 180
        },{
          userId: this.$store.state.user.name,
          functionId: 30004,
          serialNumber: '30004Table3DefaultPrinterName',
          tableId: "30004Table3",
          tableName: "标签模板信息表",
          columnProp: "defaultPrinterName",
          headerAlign: "center",
          align: "left",
          columnLabel: "Default Printer Name",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 180
        },
      ],
      manufacturerList:[],
      labelFormatList:[],
      base64List:[],
      status:0,

      currentPartLogistic:{
        site:this.$store.state.user.site,
        partNo:'',
        partDesc:'',
        poNo:'',
        unitQtyPerPallet:1,
        countOfPallets:1,
        umName:'',
        customerNo:'',
        invoiceNo:'',
      },
      logisticVisible:false,
      templateList:[],

      printTest:false,

      serialNumberList:[],
      scanSerialNumberList:[],
      serialNumberVisible:false,
      scanObj:{
        serialNumber:'',
      },
      importExcelVisible:false,
      fileList:[],

      importExcelLoading:false,
    }
  },
  watch:{
    currentPart(newVal,oldVal){
      this.getExternalPartPictureList();
      this.selectLabelFormatUserDefaultListByUserId();
    },
    "searchPrinter.customerNo"(newVal,oldVal){
      this.searchPrinter.customerNo = newVal.toUpperCase();
    },
    "searchPrinter.partNo"(newVal,oldVal){
      this.searchPrinter.partNo = newVal.toUpperCase();
    },
    "printCurrentPart.cartonCount"(newVal,oldVal){
      if (newVal && newVal > 0){
        this.printCurrentPart.cartonCount = Math.ceil(newVal)
      }
      this.printCurrentPart.totalShipQty = this.totalShipQty();
    },
    "printCurrentPart.qtyPerRoll"(newVal,oldVal){
      this.printCurrentPart.qtyPerCarton = this.qtyPerCarton();
    },
    "printCurrentPart.rollsPerCarton"(newVal,oldVal){
      this.printCurrentPart.qtyPerCarton = this.qtyPerCarton();
    },
    "printCurrentPart.qtyPerCarton"(newVal,oldVal){
      this.printCurrentPart.totalShipQty = this.totalShipQty();
    },
    printVisible(newVal,oldVal){
      if (newVal === false){
        this.printTest = false;
        this.serialNumberList = [];
      }
    },
    logisticVisible(newVal,oldVal){
      if (newVal === false){
        this.printTest = false;
      }
    },
    serialNumberVisible(newVal,oldVal){
      if (newVal === false){
        this.scanObj.serialNumber = '';
        this.scanSerialNumberList = [];
      }
    },
    importExcelVisible(newVal,oldVal){
      if (newVal === false){
        this.$refs.uploadFile.clearFiles();
        this.importExcelLoading = false;
      }
    },
    printLoading(newVal,oldVal){
      if (newVal === true){
        setTimeout(()=>{
          this.printLoading = false
        },5000)
      }
    }
  },
  methods:{
    rowStyle({row}){
      if (row.site === this.currentPart.site && row.partNo === this.currentPart.partNo && row.customerNo === this.currentPart.customerNo){
        return {background: 'rgb(232,246,246)',}
      }
    },
    handleClick(row){
      this.currentPart = {...row};
    },
    getExternalPartCustomerList(){
      let params = {
        ...this.searchPrinter,
        site:this.$store.state.user.site
      }
      getExternalPartCustomerList(params).then(({data})=>{
        if (data && data.code === 0){
          this.printerList = data.rows;
          if (this.printerList.length > 0){
            this.currentPart = {...this.printerList[0]}
          }
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    getExternalPartPictureList(){
      let params = {
        partNo: this.currentPart.partNo,
        site: this.currentPart.site,
        pictureClassify:'BoxPicture'
      }
      getExternalPartPictureList(params).then(({data})=>{
        if (data && data.code === 0){
          this.pictureList = data.rows;
          this.convertToBase64(this.pictureList.map((item)=>item.pictureUrl))
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    handlePrintLogisticLabel(){
      let labelList = this.labelFormatList.filter((item)=> item.labelType === 'Logistic Label')
      if (labelList.length === 0){
        this.$message.warning("There is no maintenance of print label format")
        return
      }
      this.getExternalPartPictureList();
      this.selectLabelFormatUserDefaultListByUserId();
      this.currentPartLogistic = {
        site:this.currentPart.site,
        partNo:this.currentPart.partNo,
        partDesc:this.currentPart.partDesc,
        poNo:'',
        category:this.currentPart.category,
        unitQtyPerPallet:1,
        countOfPallets:1,
        umName: this.currentPart.umName,
        customerNo:this.currentPart.customerNo,
        invoiceNo:'',
      }
      this.logisticVisible = true;
    },
    handlePrint(status){
      this.printCurrentPart = JSON.parse(JSON.stringify(this.currentPart))
      let labelList = [];
      if (status === 1){
        labelList = this.labelFormatList.filter((item)=> item.labelType === 'Roll Label')
        this.printCurrentPart.rollsPerCarton = 1;
        this.$set(this.printCurrentPart,'orderNo','')
      }else if (status === 0){
        labelList = this.labelFormatList.filter((item)=> item.labelType === 'Shipment Carton')
      }
      if (labelList.length === 0){
        this.$message.warning("There is no maintenance of print label format")
        return
      }
      for (let label of labelList) {
        if (!label.defaultPrinterName){
          this.$message.warning("The default printer name is not set")
          return
        }
      }
      this.status = status;
      this.$set(this.printCurrentPart,'cartonCount',1)
      this.$set(this.printCurrentPart,'manufacturerNo','')
      this.$set(this.printCurrentPart,'totalShipQty',undefined)
      this.$set(this.printCurrentPart,'moldCode','')
      this.$set(this.printCurrentPart,'serialNumber',undefined)
      this.$set(this.printCurrentPart,'manufacturerTime',dayjs().format('YYYY-MM-DD HH:mm:ss'))
      if (this.currentPart.serialNumberRequired === 'Y'){
        this.printCurrentPart.qtyPerRoll = 1;
        this.printCurrentPart.rollsPerCarton = 1;
        this.printCurrentPart.qtyPerCarton = 1;
        this.printCurrentPart.totalShipQty = 1;
      }else {
        this.printCurrentPart.qtyPerCarton = this.currentPart.qtyPerCarton;
        this.printCurrentPart.qtyPerRoll = this.currentPart.qtyPerRoll;
        this.printCurrentPart.rollsPerCarton = this.currentPart.rollsPerCarton;
        this.printCurrentPart.totalShipQty = this.totalShipQty();
      }
      if (this.currentPart.manufacturerRequired === 'Y'){
        // 查询所有的 manufacturer
        this.getExternalPartManufacturerList();
      }
      if (this.currentPart.moldCodeRequired === 'Y'){
        this.printCurrentPart.moldCode = this.currentPart.moldCode;
      }
      if (this.printCurrentPart.category === 'Hardware(Antenna)-Serials'){
        this.$set(this.printCurrentPart,'printLabelType',0)
        this.handleQueryTemplate();
      }
      this.handleQueryCategory();
    },
    handleQueryTemplate(){
      let params = {
        partNo: this.currentPart.partNo,
        site: this.currentPart.site,
      }
      this.templateList = [];
      queryExternalLabelTemplate(params).then(({data})=>{
        if (data && data.code === 0){
          this.templateList = data.rows;
          if (this.templateList.length > 0){
            this.$set(this.printCurrentPart,'templateNo',this.templateList[0].templateNo)
          }
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    handleQueryCategory(){
      // 获取 category
      let params = {
        categoryValue: this.currentPart.category,
      }
      getCategory(params).then(({data})=>{
        if (data && data.code === 0){
          this.$set(this.printCurrentPart,'qtyPerRollLabel',data.data.qtyPerRollLabel)
          this.$set(this.printCurrentPart,'cartonCountLabel',data.data.cartonCountLabel)
          this.$set(this.printCurrentPart,'rollCountLabel',data.data.rollCountLabel)
          this.$set(this.printCurrentPart,'showCartonQtyPerRoll',data.data.showCartonQtyPerRoll)
          this.$set(this.printCurrentPart,'showCartonRollsPerCarton',data.data.showCartonRollsPerCarton)
          this.$set(this.printCurrentPart,'showRollQtyPerRoll',data.data.showRollQtyPerRoll)
          this.$set(this.printCurrentPart,'editQtyPerCarton',data.data.editQtyPerCarton)
          this.printRules.qtyPerRoll[0].message = `Please input ${data.data.qtyPerRollLabel}`
          if (this.status === 0){
            if (data.data.showCartonRollsPerCarton === 'N' && data.data.showCartonQtyPerRoll === 'N'){
              this.rowSpan = 8
            }else if (data.data.showCartonRollsPerCarton === 'N' || data.data.showCartonQtyPerRoll === 'N'){
              this.rowSpan = 6
            }else {
              this.rowSpan = 5
            }
            this.printRules.cartonCount[0].message = `Please input ${data.data.cartonCountLabel}`
          }else {
            if (data.data.showRollQtyPerRoll === 'N'){
              this.rowSpan = 12
            }else {
              this.rowSpan = 8
            }
            this.printRules.cartonCount[0].message = `Please input ${data.data.rollCountLabel}`
          }
          this.getExternalPartPictureList();
          this.selectLabelFormatUserDefaultListByUserId();
          this.printVisible = true;
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    getExternalPartManufacturerList(){
      let params = {
        site: this.currentPart.site,
        partNo: this.currentPart.partNo,
      }
      getExternalPartManufacturerList(params).then(({data})=>{
        if (data && data.code === 0){
          this.manufacturerList = data.rows;
          if (this.manufacturerList.length > 0){
            this.printCurrentPart.manufacturerNo = this.manufacturerList[0].manufacturerNo;
          }
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })

    },
    handlePrintOrSave(){
      if ((this.printCurrentPart.category !== 'Hardware(Antenna)-Serials' || this.$store.state.user.autoSerialNumber !== 'Y') &&this.printCurrentPart.serialNumberRequired === 'Y' && this.serialNumberList.length <= 0){
        this.$message.warning("Please input Serial Number")
        return
      }
      this.$refs.printForm.validate((valid,obj) => {
        if (valid){
          if(this.status === 0){
            this.savePrintLabelRecord();
          }else if (this.status === 1){
            this.savePrintRollLabelRecord();
          }
        }else {
          for (let i = 0; i < Object.keys(obj).length; i++) {
            this.$message.warning(obj[Object.keys(obj)[i]][0].message)
            return
          }
        }
      })
    },
    savePrintLabelRecord(){
      let params = {
        ...this.printCurrentPart,
        serialNumberList:this.serialNumberList.map((item)=>{return item.serialNumber}),
        createBy: this.$store.state.user.name
      }
      this.printLoading = true;
      savePrintLabelRecord(params).then(({data})=>{
        if (data && data.code === 0) {
          let labelList = data.rows
          let icons = this.base64List.map((item)=>{return{icon: item,}})
          for (let i = 0; i < labelList.length; i++) {
            let item = labelList[i];
            let params = {
              qrCode: `(00)${item.partNo}(01)${item.qtyPerCarton}(02)${item.umName}(03)${item.manufacturerDate}(04)${item.serialNumber? item.serialNumber : ''}(05)${item.manufacturerNo? item.manufacturerNo : ''}(06)${item.moldCode? item.moldCode : ''}(07)${item.boxNo? item.boxNo : ''}(08)(09)(10)`,
              ref: item.partNo,
              productRev: item.rev,
              qty: item.qtyPerCarton,
              uom: item.umName,
              desc: item.partDesc,
              rollCount: item.qtyPerRoll,
              date: item.manufacturerDate,
              manufacturer: item.manufacturerNo,
              moldCode: item.moldCode,
              sn: item.serialNumber,
              freeInfo2: item.freeInfo2,
              tradingMark: item.tradingMark,
              weightUmName: item.weightUmName,
              pictureMap:item.pictureMap,
              printLabelType:item.printLabelType,
              templateNo:item.templateNo,
              dateStr:item.dateStr,
              printStr1:item.printStr1,
              printStr2:item.printStr2,
              printStr3:item.printStr3,
              offsetX:item.offsetX,
              offsetY:item.offsetY,
              direction:item.direction,
              showPound:this.$store.state.user.showPound === 'Y'?item.showPound:'N',
            }
            if (item.packingWeight){
              params.weight = new Decimal(item.packingWeight).mul(item.qtyPerCarton).toNumber();
            }
            let qrCodeList = this.$refs.qrCode.init([params.qrCode])
            params.qrCode = qrCodeList[0]

            if (item.printType === 'Alpha/Hard Tag'){
              printAlphaHardTagLabel([params],icons,item.printerName,this.printTest)
            }else if (item.printType === 'Hardware(Antenna)'){
              if (this.printCurrentPart.category === 'Hardware(Antenna)-Serials'){
                printAntennaLabel([params],icons,item.printerName,this.$store.state.user.autoSerialNumber,this.printTest)
              }else {
                printAntennaLabel([params],icons,item.printerName,'N',this.printTest)
              }
            }else if (item.printType === 'RF' || this.currentPart.category === 'RFID'){
              printRF_RFIDLabel([params],icons,item.printerName,this.printTest)
            }
            this.printTest = false
          }
          // let notFound = [];
          // // 打印机集合
          // let labelList = this.labelFormatList.filter((item)=> item.labelType === 'Shipment Carton')
          // for (let label of labelList) {
          //   let prints = data.rows.map((item) => {
          //     let params = {
          //       qrCode: `(00)${item.partNo}(01)${item.qtyPerCarton}(02)${item.umName}(03)${item.manufacturerDate}(04)${item.serialNumber? item.serialNumber : ''}(05)${item.manufacturerNo? item.manufacturerNo : ''}(06)${item.moldCode? item.moldCode : ''}(07)${item.boxNo? item.boxNo : ''}(08)(09)(10)`,
          //       ref: item.partNo,
          //       productRev: item.rev,
          //       qty: item.qtyPerCarton,
          //       uom: item.umName,
          //       desc: item.partDesc,
          //       rollCount: item.qtyPerRoll,
          //       date: item.manufacturerDate,
          //       manufacturer: item.manufacturerNo,
          //       moldCode: item.moldCode,
          //       sn: item.serialNumber,
          //       freeInfo2: item.freeInfo2,
          //       tradingMark: item.tradingMark,
          //       weightUmName: item.weightUmName,
          //       pictureMap:item.pictureMap,
          //       printLabelType:item.printLabelType,
          //       templateNo:item.templateNo,
          //       dateStr:item.dateStr,
          //       printStr1:item.printStr1,
          //       printStr2:item.printStr2,
          //       printStr3:item.printStr3,
          //     }
          //     if (item.packingWeight){
          //       params.weight = new Decimal(item.packingWeight).mul(item.qtyPerCarton).toNumber();
          //     }
          //     return params
          //   });
          //   let qrCodeList = this.$refs.qrCode.init(prints.map((item)=>{
          //     return item.qrCode
          //   }))
          //   for (let i = 0; i < qrCodeList.length; i++) {
          //     prints[i].qrCode = qrCodeList[i]
          //   }
          //   let icons = this.base64List.map((item)=>{return{icon: item,}})
          //   if (!this.printerSetupList.includes(label.defaultPrinterName)) {
          //     notFound.push(label.defaultPrinterName)
          //     continue
          //   }
          //   if (label.printType === 'Alpha/Hard Tag'){
          //     printAlphaHardTagLabel(prints,icons,label.defaultPrinterName)
          //   }else if (label.printType === 'Hardware(Antenna)'){
          //     if (this.printCurrentPart.category === 'Hardware(Antenna)-Serials'){
          //       printAntennaLabel(prints,icons,label.defaultPrinterName,this.$store.state.user.autoSerialNumber)
          //     }else {
          //       printAntennaLabel(prints,icons,label.defaultPrinterName)
          //     }
          //   }else if (label.printType === 'RF' || this.currentPart.category === 'RFID'){
          //     printRF_RFIDLabel(prints,icons,label.defaultPrinterName)
          //   }
          // }
          // if (notFound.length > 0){
          //  this.$message.warning(`The printer ${notFound.join(',')} is not found`)
          // }else {
          //   this.$message.success("Print label success")
          // }
        }else {
          this.$message.warning(data.msg)
        }
        this.printLoading = false;
      }).catch((error)=>{
        this.$message.error(error)
        this.printLoading = false;
      })
    },
    handlePartRowClick(row){
      this.searchPrinter.partNo = row.partNo;
      this.partVisible = false;
    },
    handleCustomerRowClick(row){
      this.searchPrinter.customerNo = row.customerNo;
      this.customerVisible = false;
    },
    closePrintDialog(){
      this.manufacturerList = [];

      this.printCurrentPart = {
        ...printer
      }
      this.$refs.printForm.resetFields();
    },
    selectLabelFormatUserDefaultListByUserId(){
      let params = {
        site:this.currentPart.site,
        partNo:this.currentPart.partNo,
        username:this.$store.state.user.name,
        category:this.currentPart.category,
      }
      getLabelFormatUserDefaultList(params).then(({data})=>{
        if (data && data.code === 0){
          this.labelFormatList = data.rows;
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    handleCartonCount(){
      if (this.printCurrentPart.totalShipQty && this.printCurrentPart.qtyPerCarton && this.printCurrentPart.totalShipQty !== 0 && this.printCurrentPart.qtyPerCarton !== 0){
        this.printCurrentPart.cartonCount = new Decimal(new Decimal(this.printCurrentPart.totalShipQty).div(this.printCurrentPart.qtyPerCarton).toFixed(2)).toSignificantDigits().toNumber();
      }else {
        this.printCurrentPart.cartonCount = 0
      }
    },
    async convertToBase64(fileUrls) {
      this.base64List = []
      for (const fileUrl of fileUrls) {
        const base64Url = await this.getFileAsBase64(fileUrl);
        this.base64List.push(base64Url);
      }
    },
    getFileAsBase64(fileUrl) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'Anonymous';
        img.src = fileUrl;
        img.onload = () => {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0);
          const base64data = canvas.toDataURL('image/jpeg');
          resolve(base64data);
        };
        img.onerror = (error) => {
          reject(error);
        };
      });
    },
    async getTableUserColumn (tableId, columnId) {
      let queryTableUser = {
        userId: this.$store.state.user.name,
        functionId: this.$route.meta.menuId,
        tableId: tableId,
        status: true,
        languageCode: this.$i18n.locale
      }
      await getTableUserListLanguage(queryTableUser).then(({data}) => {
        if (data.rows.length > 0) {
          this.caseTable(data.rows,columnId)
        } else {
          this.getColumnList(tableId, columnId)
        }
      })
    },

    // 获取 tableDefault 列
    async getColumnList (tableId, columnId) {
      let queryTable = {
        functionId: this.$route.meta.menuId,
        tableId: tableId,
        languageCode: this.$i18n.locale
      }
      await getTableDefaultListLanguage(queryTable).then(({data}) => {
        if (data.rows.length > 0) {
          this.caseTable(data.rows,columnId)
        } else {

        }
      })
    },
    caseTable(list,columnId){
      if (list.length > 0){
        switch (columnId) {
          case 1:
            this.columnList = list
            break;
          case 2:
            this.pictureColumnList = list
            break;
          case 3:
            this.formatColumnList = list
            break;
        }
      }
    },
    qtyPerCarton(){
      return new Decimal(this.printCurrentPart.qtyPerRoll).mul(this.printCurrentPart.rollsPerCarton).toNumber()
    },
    totalShipQty(){
      return new Decimal(this.printCurrentPart.qtyPerCarton).mul(this.printCurrentPart.cartonCount).toNumber()
    },
    getCategoryList(){
      let params = {};
      getCategoryList(params).then(({data})=>{
        if (data && data.code === 0){
          this.partCategoryList = data.rows;
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    savePrintRollLabelRecord(){
      // 新增 打印记录
      let params = {
        ...this.printCurrentPart,
        serialNumberList: this.serialNumberList.map((item)=>{
          return item.serialNumber
        }),
      }
      this.printLoading = true;
      // 请求接口
      savePrintRollLabelRecord(params).then(({data})=>{
        if (data && data.code === 0) {
          let labelList = this.labelFormatList.filter((item)=> item.labelType === 'Roll Label')
          let prints = data.rows.map((item) => {
            return {
              qrCode: `(00)${item.partNo}(01)${item.qtyPerRoll}(02)${item.umName}(03)${item.manufacturerDate}(04)${item.serialNumber? item.serialNumber : ''}(05)${item.manufacturerNo? item.manufacturerNo : ''}(06)${item.moldCode? item.moldCode : ''}(07)(08)${item.rollNo}(09)(10)`,
              ref: item.partNo,
              rev: item.rev,
              qty: item.qtyPerRoll,
              uom: item.umName,
              desc: item.partDesc,
              date: item.manufacturerDate,
              manufacturer: item.manufacturerNo,
              moldCode: item.moldCode,
              rollNo: item.rollNo,
              sn: item.serialNumber,
              rollLabelRequired: item.rollLabelRequired,
              serialNumberRequired: item.serialNumberRequired,
              serialNumber: item.serialNumber,
              rollLabelFlag: item.rollLabelFlag,// 判断标签类型
              offsetX:item.offsetX,
              offsetY:item.offsetY,
              direction:item.direction,
            }
          });
          let qrCodeList = this.$refs.qrCode.init(prints.map((item)=>{
            return item.qrCode
          }))
          for (let i = 0; i < qrCodeList.length; i++) {
            prints[i].qrCode = qrCodeList[i]
          }
          let notFound = [];
          for (let label of labelList) {
            if (!this.printerSetupList.includes(label.defaultPrinterName)) {
              notFound.push(label.defaultPrinterName)
              continue
            }
            print_roll_label(prints,label.defaultPrinterName,this.printTest)
          }
          this.printTest = false
          if (notFound.length > 0){
            this.$message.warning(`The printer ${notFound.join(',')} is not found`)
            return
          }
          this.$message.success(data.msg)
        }else {
          this.$message.warning(data.msg)
        }
        this.printLoading = false;
      }).catch((error)=>{
        this.$message.error(error)
        this.printLoading = false;
      })
    },
    loadQrCode(){
      let arr = ['2','4','6','8']
      console.log(this.$refs.qrCode.init(arr))
    },
    getLodopPrinterName(){
      const lodop = getLodop()
      for (let i = 0; i < lodop.GET_PRINTER_COUNT(); i++) {
        this.printerSetupList.push(lodop.GET_PRINTER_NAME(i))
      }
    },
    handleGetExternalPartCustomerPage(){
      let params = {
        ...this.searchPrinter,
        site:this.$store.state.user.site,
        no:this.no,
        size:this.size,
      }
      getExternalPartCustomerPage(params).then(({data})=>{
        if (data && data.code === 0){
          this.printerList = data.rows;
          if (this.printerList.length > 0){
            this.currentPart = {...this.printerList[0]}
          }
          this.total = data.total;
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    handleSizeChange(val){
      this.size = val;
      this.handleGetExternalPartCustomerPage();
    },
    handleCurrentChange(val){
      this.no = val;
      this.handleGetExternalPartCustomerPage();
    },
    handlePrintLogistic(){
      this.$refs.logisticForm.validate((valid,obj) => {
        if (valid){
          this.savePrintLogisticLabel()
        }else {
          let i = 0
          Object.keys(obj).forEach(key=>{
            if (i++ === 0){
              this.$message.warning(obj[key][0].message)
            }
          })
        }
      })
      this.printLoading = false;
    },
    savePrintLogisticLabel() {
      let params = {
        ...this.currentPartLogistic,
        createBy: this.$store.state.user.name,
      }
      this.printLoading = true;
      saveLogisticLabelRecord(params).then(({data})=>{
        if (data && data.code === 0){
          let labelList = this.labelFormatList.filter((item)=> item.labelType === 'Logistic Label')
          for (let i = 0; i < this.currentPartLogistic.countOfPallets; i++) {
            let row = {
              qrCode: `(00)${this.currentPartLogistic.partNo? this.currentPartLogistic.partNo : ''}(01)${this.currentPartLogistic.unitQtyPerPallet? this.currentPartLogistic.unitQtyPerPallet : ''}(02)${this.currentPartLogistic.umName? this.currentPartLogistic.umName : ''}(03)(04)(05)(06)(07)(08)(09)(10)${this.currentPartLogistic.poNo? this.currentPartLogistic.poNo : ''}`,
              partNo:this.currentPartLogistic.partNo,
              partDesc:this.currentPartLogistic.partDesc,
              poNo:this.currentPartLogistic.poNo,
              qty:this.currentPartLogistic.unitQtyPerPallet,
              umName:this.currentPartLogistic.umName,
              invoiceNo:this.currentPartLogistic.invoiceNo,
              offsetX:data.row.offsetX,
              offsetY:data.row.offsetY,
              direction:data.row.direction,
            }
            let qrCodeList = this.$refs.qrCode.init([row.qrCode])
            row.qrCode = qrCodeList[0]
            let notFound = [];
            for (let label of labelList) {
              if (!this.printerSetupList.includes(label.defaultPrinterName)) {
                notFound.push(label.defaultPrinterName)
                continue
              }
              printLogisticLabel([row],label.defaultPrinterName,this.printTest)
            }
            this.printTest = false
            if (notFound.length > 0){
              this.$message.warning(`The printer ${notFound.join(',')} is not found`)
              return
            }
          }
          this.$message.success(data.msg)
        }else {
          this.$message.warning(data.msg)
        }
        this.printLoading = false;
      }).catch((error)=>{
        this.$message.error(error)
        this.printLoading = false;
      })
    },
    handlePrintTest(val){
      this.printTest = true
      if (val === 0){
        this.handlePrintOrSave();
      }else {
        this.handlePrintLogistic();
      }
    },
    handleScan(){
      // 判断是否为空
      if (!this.scanObj.serialNumber){
        this.$message.warning("Please input Serial Number")
        return
      }
      // 判断是否重复
      let map = this.scanSerialNumberList.map((item)=>item.serialNumber)
      if(map.includes(this.scanObj.serialNumber)){
        this.$message.warning("Serial Number already exists")
        return
      }
      this.scanSerialNumberList.push(this.scanObj)
      this.scanObj = {
        serialNumber:''
      }
    },
    deleteSerialNumber(index,type){
      this.$confirm('Are you sure you want to delete Serial Number?', 'Warning', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
        zIndex:3000
      }).then(() => {
        if (type === 'scan'){
          this.scanSerialNumberList.splice(index,1)
        }else if (type === 'end'){
          this.serialNumberList.splice(index,1)
        }
        this.$message.success('success')
      })
    },
    onChange(file, fileList){
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ["xls", "xlsx"];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error("Only Excel files (.xls, .xlsx) are allowed!");
        this.fileList.splice(this.fileList.length - 1, 1);
        return
      }
      this.fileList = fileList;
    },
    downloadTemplate(){
      let params = {
        orderRef1:'println',
        orderRef2:'printlnExcel',
      }
      download(params).then(({data})=>{
        // 不限制文件下载类型
        const blob = new Blob([data], {type: "application/octet-stream"})
        // 下载文件名称
        const fileName = 'SN Template.xlsx'
        // a标签下载
        const linkNode = document.createElement('a')
        // a标签的download属性规定下载文件的名称
        linkNode.download = fileName
        linkNode.style.display = 'none'
        // 生成一个Blob URL
        linkNode.href = URL.createObjectURL(blob)
        document.body.appendChild(linkNode)
        // 模拟在按钮上的一次鼠标单击
        linkNode.click()
        // 释放URL 对象
        URL.revokeObjectURL(linkNode.href)
        document.body.removeChild(linkNode)
      })
    },
    handleImportExcel(){
      if (null == this.fileList || 0 === this.fileList.length) {
        this.$message.error("Please upload the file first!")
        return false
      }
      // 提示将删除之前的数据
      this.$confirm('Do you confirm the upload? If the Serial Number already exists, we will delete it!', 'Warning', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
        zIndex:3000
      }).then(() => {
        // 判断文件是否上传
        if (null == this.fileList || 0 === this.fileList.length) {
          this.$message.error("please select the file you want to upload!")
          return
        }
        const formData = new FormData()
        formData.append("file", this.fileList[0].raw)
        this.importExcelLoading = true;
        importSerialNumber(formData).then(({data}) => {
          if (data && data.code === 0){
            this.serialNumberList = data.rows.map((item)=>{
              return {
                serialNumber:item,
              }
            })
            this.importExcelVisible = false;
          }else {
            this.$message.warning(data.msg)
          }
          this.importExcelLoading = false;
        })
      }).catch(() => {
        this.importExcelLoading = false;
      });
    },
    handleSaveSerialNumber(){
      if (this.scanSerialNumberList.length === 0){
        this.$message.warning("Please input Serial Number")
        return
      }
      this.serialNumberList = [...this.scanSerialNumberList]
      this.$message.success("success")
      this.serialNumberVisible = false
    },
    handleScanSerialNumber(){
      this.scanSerialNumberList = [...this.serialNumberList]
      this.serialNumberVisible = true
    }
  },
  mounted () {
    this.getLodopPrinterName();
  },
  created () {
    // this.getExternalPartCustomerList();
    this.handleGetExternalPartCustomerPage();
    this.getCategoryList();
    this.getTableUserColumn("30004Table",1)
    this.getTableUserColumn("30004Table2",2)
    this.getTableUserColumn("30004Table3",3)
  }
}
</script>

<template>
<div>
  <div style="min-width: 800px;max-width: 1300px">
    <el-form :model="searchPrinter" label-position="top">
      <el-row :gutter="10">
        <el-col :span="3">
          <el-form-item label="Customer No">
            <span slot="label" style="cursor:pointer;" @click="customerVisible=true"><a herf="#">Customer No</a></span>
            <el-input v-model="searchPrinter.customerNo" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="Customer Name">
            <el-input v-model="searchPrinter.customerName" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="Part Active">
            <el-select v-model="searchPrinter.active" style="width: 100%;" placeholder="">
              <el-option label="All" value=""></el-option>
              <el-option label="Active" value="Y"></el-option>
              <el-option label="Not Active" value="N"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label=" ">
            <el-button type="primary" style="width: 60px" @click="handleGetExternalPartCustomerPage">Query</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="3">
          <el-form-item label="Part No">
            <span slot="label" style="cursor:pointer;" @click="partVisible=true"><a herf="#">Part No</a></span>
            <el-input v-model="searchPrinter.partNo" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="Part Description">
            <el-input v-model="searchPrinter.partDesc" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="Part Category">
            <el-select v-model="searchPrinter.category" style="width: 100%;" placeholder="">
              <el-option label="All" value=""></el-option>
              <el-option :label="item.categoryName" :value="item.categoryValue" :key="item.id" v-for="item in partCategoryList"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item label=" ">
            <el-button type="primary" @click="handlePrint(0)">Print-Carton Label</el-button>
            <el-button type="primary" v-if="$store.state.user.autoSerialNumber !== 'Y'" @click="handlePrint(1)" >Print-Roll Label</el-button>
            <el-button type="primary" @click="handlePrintLogisticLabel">Print Logistic Label</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <qr-code ref="qrCode"></qr-code>
  <el-table :data="printerList" @row-click="handleClick" style="width: 100%;margin-top: 10px" border :height="height" :row-style="rowStyle">
    <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>
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page.sync="no"
    :page-sizes="[50,100, 200, 300, 400]"
    :page-size="size"
    layout="sizes, prev, pager, next,total"
    :total="total">
  </el-pagination>
  <el-tabs v-model="activeName">
    <el-tab-pane label="Part Certification" name="picture">
      <picture-module :column-list="pictureColumnList" :height="330" :part="currentPart" @refresh="getExternalPartPictureList" :of-components="true" :data-list="pictureList"></picture-module>
    </el-tab-pane>
    <el-tab-pane label="Linked Format" name="format">
      <linked-format :column-list="formatColumnList" :height="330" :data-list="labelFormatList"></linked-format>
    </el-tab-pane>
  </el-tabs>

  <el-dialog v-drag title="Print Label" :close-on-click-modal="false" @close="closePrintDialog" :visible.sync="printVisible" width="600px" modal-append-to-body>
    <el-form :model="printCurrentPart" ref="printForm" :rules="printRules" label-position="top" >
      <el-row :gutter="10">
        <el-col :span="status === 0? 24:8">
          <el-form-item label="Part No">
            <el-input v-model="printCurrentPart.partNo" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16" v-if="status !== 0">
          <el-form-item label="PO" prop="orderNo" v-if="false" :show-message="false">
            <el-input v-model="printCurrentPart.orderNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="Part Description">
            <el-input v-model="printCurrentPart.partDesc" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" v-if="(status === 0 && printCurrentPart.showCartonQtyPerRoll === 'Y') || (status === 1 && printCurrentPart.showRollQtyPerRoll === 'Y')">
          <el-form-item v-if="printCurrentPart.serialNumberRequired === 'Y'" :label="printCurrentPart.qtyPerRollLabel" :show-message="false">
            <el-input-number :step="0" :min="1" :controls="false" v-model="printCurrentPart.qtyPerRoll" disabled></el-input-number>
          </el-form-item>
          <el-form-item v-else key="qtyPerRoll" :label="printCurrentPart.qtyPerRollLabel" prop="qtyPerRoll" :show-message="false">
            <el-input-number :step="0" :min="1" :controls="false" v-model="printCurrentPart.qtyPerRoll"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" v-if="status === 0 && printCurrentPart.showCartonRollsPerCarton === 'Y'">
          <el-form-item v-if="printCurrentPart.serialNumberRequired === 'Y'" label="Rolls Per Carton" :show-message="false">
            <el-input-number :step="0" :min="1" :controls="false" v-model="printCurrentPart.rollsPerCarton" disabled></el-input-number>
          </el-form-item>
          <el-form-item v-else key="rollsPerCarton" label="Rolls Per Carton" prop="rollsPerCarton" :show-message="false">
            <el-input-number :step="0" :min="1" :controls="false" v-model="printCurrentPart.rollsPerCarton"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" v-if="status === 0">
          <el-form-item v-if="printCurrentPart.serialNumberRequired === 'Y'" label="Qty Per Carton" :show-message="false">
            <el-input-number :step="0" :controls="false" v-model="printCurrentPart.qtyPerCarton" :disabled="printCurrentPart.editQtyPerCarton === 'N'"></el-input-number>
          </el-form-item>
          <el-form-item v-else label="Qty Per Carton" prop="qtyPerCarton" key="qtyPerCarton" :show-message="false">
            <el-input-number :step="0" :controls="false" v-model="printCurrentPart.qtyPerCarton" :disabled="printCurrentPart.editQtyPerCarton === 'N'"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="(status === 0 && rowSpan === 5)? rowSpan-1:rowSpan">
          <el-form-item v-if="printCurrentPart.serialNumberRequired === 'Y' && $store.state.user.autoSerialNumber !== 'Y'" :label="status === 0 ? printCurrentPart.cartonCountLabel:printCurrentPart.rollCountLabel" :show-message="false">
            <el-input-number :step="0" :min="1" :controls="false" v-model="printCurrentPart.cartonCount" disabled></el-input-number>
          </el-form-item>
          <el-form-item v-else key="cartonCount" :label="status === 0 ? printCurrentPart.cartonCountLabel:printCurrentPart.rollCountLabel" prop="cartonCount" :show-message="false">
            <el-input-number :step="0" :min="1" :precision="0" :controls="false" v-model="printCurrentPart.cartonCount"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item v-if="printCurrentPart.serialNumberRequired === 'Y'" label="Total Ship Qty" :show-message="false">
            <el-input-number :step="0" :min="0" :controls="false" v-model="printCurrentPart.totalShipQty" disabled></el-input-number>
          </el-form-item>
          <el-form-item v-else label="Total Ship Qty" prop="totalShipQty" key="totalShipQty" :show-message="false">
            <el-input-number :step="0" :min="0" :controls="false" v-model="printCurrentPart.totalShipQty" disabled></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="printCurrentPart.category !== 'Hardware(Antenna)-Serials' || $store.state.user.autoSerialNumber !== 'Y'">
<!--          <el-form-item v-if="printCurrentPart.serialNumberRequired === 'Y'" key="serialNumber" label="Serial Number" prop="serialNumber" :show-message="false">-->
<!--            <el-input v-model="printCurrentPart.serialNumber"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item v-if="printCurrentPart.serialNumberRequired !== 'Y'" label="Serial Number" :show-message="false">
            <el-input v-model="printCurrentPart.serialNumber" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="Manufacturer Date" prop="manufacturerTime" :show-message="false">
            <el-date-picker type="date"
                            placeholder=" " value-format="yyyy-MM-dd HH:mm:ss" v-model="printCurrentPart.manufacturerTime" style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="printCurrentPart.manufacturerRequired === 'Y'" key="manufacturerNo" label="Manufacturer" prop="manufacturerNo" :show-message="false">
            <el-select v-model="printCurrentPart.manufacturerNo" style="width: 100%" placeholder="">
              <el-option v-for="item in manufacturerList" :key="item.manufacturerNo" :label="item.manufacturerNo" :value="item.manufacturerNo">
                <span style="float: left">{{ item.manufacturerNo }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-else label="Manufacturer" :show-message="false">
            <el-select v-model="printCurrentPart.manufacturerNo" style="width: 100%" disabled placeholder="">
              <el-option v-for="item in manufacturerList" :key="item.manufacturerNo" :label="item.manufacturerNo" :value="item.manufacturerNo">
                <span style="float: left">{{ item.manufacturerNo }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="printCurrentPart.moldCodeRequired === 'Y'" key="moldCode" label="Mold Code" prop="moldCode" :show-message="false">
            <el-input v-model="printCurrentPart.moldCode" ></el-input>
          </el-form-item>
          <el-form-item v-else label="Mold Code" :show-message="false">
            <el-input v-model="printCurrentPart.moldCode" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-if="$store.state.user.autoSerialNumber === 'Y' && printCurrentPart.category === 'Hardware(Antenna)-Serials'">
        <el-col :span="8">
          <el-form-item label="Template">
            <el-select v-model="printCurrentPart.templateNo" style="width: 100%">
              <el-option v-for="item in templateList" :key="item.templateNo" :label="item.templateName" :value="item.templateNo"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="Label Type">
            <el-select v-model="printCurrentPart.printLabelType" style="width: 100%">
              <el-option label="Carton Label & Product Label" :value="0"></el-option>
              <el-option label="Carton Label" :value="1"></el-option>
              <el-option label="Product Label" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-if="printCurrentPart.serialNumberRequired === 'Y' && (printCurrentPart.category !== 'Hardware(Antenna)-Serials' || $store.state.user.autoSerialNumber !== 'Y')">
        <el-col :span="6">
          Serial Number List
        </el-col>
        <el-col :span="14">
          <el-button type="primary" @click="importExcelVisible = true">Import from Excel</el-button>
          <el-button type="primary" @click="handleScanSerialNumber">Individual Serial Number</el-button>
        </el-col>
        <el-col :span="2">
          <div style="text-align: right;color: #00a0e9">Total:</div>
        </el-col>
        <el-col :span="2">
          <div style="color: #00a0e9">{{serialNumberList.length}}</div>
        </el-col>
        <el-col :span="24">
          <el-table :data="serialNumberList" height="200px" border>
            <el-table-column label="Serial Number" prop="serialNumber" min-width="300"></el-table-column>
            <el-table-column min-width="100" label="Action">
              <template slot-scope="{row,$index}">
                <a @click="deleteSerialNumber($index,'end')">Delete</a>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" style="text-align: center; margin-top: 10px">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-button type="primary" icon="el-icon-printer" :loading="printLoading" style="width: 40px;float:left;" @click="handlePrintTest(0)"></el-button>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" :loading="printLoading" style="width: 60px" @click="handlePrintOrSave">Print</el-button>
          <el-button style="width: 60px" @click="printVisible = false">Cancel</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>

  <el-dialog v-drag title="Print Label" :close-on-click-modal="false" :visible.sync="logisticVisible" width="400px">
    <el-form :model="currentPartLogistic" label-position="top" :rules="printRules" ref="logisticForm">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="Part No" :show-message="false">
            <el-input v-model="currentPartLogistic.partNo" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="Part Description" :show-message="false">
            <el-input v-model="currentPartLogistic.partDesc" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="PO No" prop="poNo" :show-message="false">
            <el-input v-model="currentPartLogistic.poNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Invoice No" :show-message="false">
            <el-input v-model="currentPartLogistic.invoiceNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Unit Qty per Pallet" prop="unitQtyPerPallet" :show-message="false">
            <el-input-number :controls="false" :step="0" :min="0" v-model="currentPartLogistic.unitQtyPerPallet"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Count of Pallets" prop="countOfPallets" :show-message="false">
            <el-input-number :controls="false" :step="0" :min="1" v-model="currentPartLogistic.countOfPallets"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" style="text-align: center; margin-top: 10px">
      <el-row :gutter="10">
        <el-col :span="7">
          <el-button type="primary" icon="el-icon-printer" :loading="printLoading" style="width: 40px;float:left;" @click="handlePrintTest(1)"></el-button>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" :loading="printLoading" style="width: 60px" @click="handlePrintLogistic">Print</el-button>
          <el-button style="width: 60px" @click="logisticVisible = false">Cancel</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>

  <el-dialog v-drag title="Individual Serial Number" top="20vh" :visible.sync="serialNumberVisible" append-to-body :close-on-click-modal="false" width="600px">
    <el-form :model="scanObj" label-position="top" @submit.native.prevent>
      <el-form-item label="Serial Number(Press Enter after scanning/input)" :show-message="false">
        <el-input v-model="scanObj.serialNumber" @keyup.enter.native="handleScan"></el-input>
      </el-form-item>
    </el-form>
    <el-table :data="scanSerialNumberList" height="200px" border>
      <el-table-column label="Serial Number" prop="serialNumber" min-width="300"></el-table-column>
      <el-table-column min-width="100" label="Action">
        <template slot-scope="{row,$index}">
          <a @click="deleteSerialNumber($index,'scan')">Delete</a>
        </template>
      </el-table-column>
    </el-table>

    <div style="color: #00a0e9">Total: {{scanSerialNumberList.length}}</div>
    <div slot="footer" style="text-align: center; margin-top: 10px">
      <el-button type="primary" style="width: 60px" @click="handleSaveSerialNumber">Save</el-button>
      <el-button style="width: 60px" @click="serialNumberVisible = false">Cancel</el-button>
    </div>
  </el-dialog>


  <el-dialog v-drag title="Import from Excel" top="20vh" :visible.sync="importExcelVisible" modal-append-to-body :close-on-click-modal="false" width="390px">
    <div style="margin-top: 5px; margin-bottom: 10px">
      <el-button type="primary" @click="downloadTemplate">Download file template</el-button>
    </div>
    <el-upload class="customer-upload" :file-list="fileList" drag action="javascript:void(0);" ref="uploadFile" :limit="1" accept=".xlsx,.xls"
               :on-remove="onChange" :on-change="onChange" :auto-upload="false">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">Drag the file here，or<em> click to upload</em></div>
    </el-upload>
    <div slot="footer" style="text-align: center; margin-top: 10px">
      <el-button type="primary" :loading="importExcelLoading" @click="handleImportExcel">{{importExcelLoading?'Saving...':'Save'}}</el-button>
      <el-button style="width: 60px" @click="importExcelVisible = false">Cancel</el-button>
    </div>
  </el-dialog>

  <el-dialog v-drag title="Select Part" :close-on-click-modal="false" :visible.sync="partVisible">
    <external-part :height="450" :of-components="true" @rowClick="handlePartRowClick"></external-part>
    <div slot="footer" style="text-align: center; margin-top: 10px"></div>
  </el-dialog>
  <el-dialog v-drag title="Select Customer" :close-on-click-modal="false" :visible.sync="customerVisible">
    <customer-info :height="450" :of-components="true" @rowClick="handleCustomerRowClick"></customer-info>
    <div slot="footer" style="text-align: center; margin-top: 10px"></div>
  </el-dialog>

  <div v-show="false">
    <img :src="item" v-for="(item,index) in base64List" :key="index" style="display: none">
  </div>
</div>
</template>

<style scoped>

</style>
