<script>
import ExternalPart from '../part/external.vue'
import CustomerInfo from '../customer/info.vue'
import {getPrintLabelRecordList, getPrintLabelRecordPage} from '../../../api/label/printLabelRecord'
import { printAlphaHardTagLabel} from '../../../printFormat/alphaHardTagPrintFormat'
import SelectionTable from '../../common/selectionTable.vue'
import {getExternalPartPicturePartList} from '../../../api/part/externalPartPicture'
import {printAntennaLabel} from '../../../printFormat/antenna'
import {printRF_RFIDLabel} from '../../../printFormat/RF_RFID'
import {
  getRollPrinterNameList,
  selectLabelFormatUserDefaultPrintListByUserId
} from '../../../api/label/labelFormatUserDefault'
import getLodop from '@/utils/LodopFuncs.js'
import {getTableDefaultListLanguage, getTableUserListLanguage} from '../../../api/table'
import {getPrintRollLabelRecord, getPrintRollLabelRecordPage} from '../../../api/label/printRollLabelRecord'
import QrCode from './QrCode.vue'
import {print_roll_label} from '../../../printFormat/roll_label'

const printRecord = {
  customerNo: '',
  customerName: '',
  partNo: '',
  partDesc: '',
  startDate: '',
  endDate: ''
}
export default {
  name: 'roll',
  components: {QrCode, SelectionTable, CustomerInfo, ExternalPart},
  props: {
    height: {
      type: Number,
      default: 700
    }
  },
  data () {
    return {
      printerSetupList:[],
      customerVisible: false,
      partVisible: false,
      printRecord: {
        ...printRecord
      },
      no:1,
      size: 50,
      total: 0,
      printLabelRecordList: [],
      selectionPrintLabelRecordList: [],
      columnList: [
        {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableRollNo',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'rollNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'Roll No',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableCustomerNo',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'customerNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'Customer No',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 100
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableCustomerName',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          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: 30005,
          serialNumber: '30005TablePartNo',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          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: 30005,
          serialNumber: '30005TablePartDesc',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          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: 30005,
          serialNumber: '30005TableQtyPerRoll',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'qtyPerRoll',
          headerAlign: 'center',
          align: 'right',
          columnLabel: 'Qty Per Roll',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableTotalShipQty',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'totalShipQty',
          headerAlign: 'center',
          align: 'right',
          columnLabel: 'Total Ship Qty',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableCartonCount',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'cartonCount',
          headerAlign: 'center',
          align: 'right',
          columnLabel: 'Roll Count',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableSerialNumber',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'serialNumber',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'Serial Number',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableManufacturerNo',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'manufacturerNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'Manufacturer',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableMoldCode',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'moldCode',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'Mold Code',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableManufacturerDate',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'manufacturerDate',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'Manufacturer Date',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableCreateBy',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'createBy',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'Created By',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        }, {
          userId: this.$store.state.user.name,
          functionId: 30005,
          serialNumber: '30005TableCreateTime',
          tableId: '30005Table',
          tableName: '发货标签记录表',
          columnProp: 'createTime',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'CreateTime',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 140
        }
      ],
    }
  },
  watch:{
    "printRecord.customerNo"(newVal, oldVal){
      this.printRecord.customerNo = newVal.toUpperCase();
    },
    "printRecord.partNo"(newVal, oldVal){
      this.printRecord.partNo = newVal.toUpperCase();
    }
  },
  methods: {
    handlePartRowClick (row) {
      this.printRecord.partNo = row.partNo
      this.partVisible = false
    },
    handleCustomerRowClick (row) {
      this.printRecord.customerNo = row.customerNo
      this.customerVisible = false
    },
    getPrintLabelRecordList () {
      let params = {
        ...this.printRecord,
        site: this.$store.state.user.site,
      }
      getPrintRollLabelRecordPage(params,this.no,this.size).then(({data}) => {
        if (data && data.code === 0) {
          this.printLabelRecordList = data.rows
          this.total = data.total
        } else {
          this.$message.warning(data.message)
        }
      }).catch((error) => {
        this.$message.error(error.message)
      })
    },
    handleSelectionChange (val) {
      this.selectionPrintLabelRecordList = val
    },
    async handlePrintLabel () {
      if (this.selectionPrintLabelRecordList.length === 0) {
        this.$message.warning('please select record')
        return
      }
      let ids = this.selectionPrintLabelRecordList.map((item) => {
        return item.id
      })
      getPrintRollLabelRecord(ids).then(({data})=>{
        if (data && data.code === 0){
          this.handlePrint(data.rows)
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error.message)
      })
    },
    handlePrint(list){
      let params = list.map((item) => {
        return {
          site:item.site,
          partNo:item.partNo,
          customerNo:item.customerNo,
          username:this.$store.state.user.name,
          rollNo:item.rollNo,
          category:item.category,
        }
      })
      getRollPrinterNameList(params).then(({data})=>{
        if (data && data.code === 0){
          for (let i = 0; i < this.selectionPrintLabelRecordList.length; i++) {
            let record = this.selectionPrintLabelRecordList[i]
            let printerNameList = data.rows[i].filter((item)=> item.labelType === 'Roll Label')
            let arr = []
            arr.push(record)
            for (let j = 0; j < printerNameList.length; j++) {
              arr = arr.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}`,
                  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,
                }
              })
              let qrCodeList = this.$refs.qrCode.init(arr.map((item)=>{
                return item.qrCode
              }))
              for (let i = 0; i < qrCodeList.length; i++) {
                arr[i].qrCode = qrCodeList[i]
              }
              print_roll_label(arr,printerNameList[j].defaultPrinterName)
            }
            this.$message.success(data.msg)
          }
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error.message)
      })

    },
    printLabel(pictureList,formatList){
      let prints = this.selectionPrintLabelRecordList.map((item) => {
        return {
          qrCode: `(00)${item.partNo}(01)${item.qtyPerCarton}(02)${item.umName}(03)${item.manufacturerDate}(04)${item.serialNumber}(05)${item.manufacturerNo}(06)${item.moldCode}(07)${item.boxNo}(08)`,
          ref: item.partNo,
          qty: item.qtyPerCarton,
          productRev: item.rev,
          uom: item.umName,
          desc: item.partDesc,
          rollCount: item.qtyPerRoll,
          date: item.manufacturerDate,
          manufacturer: item.manufacturerNo,
          moldCode: item.moldCode,
          sn: item.serialNumber,
        }
      })
      let notFound = [];
      for (let i = 0; i < prints.length; i++) {
        let print = prints[i]
        let dataList = []
        dataList.push(print);
        // 获取模板数量
        let format = formatList[i]
        let base64List = pictureList[i].map((item)=>{return {icon:item}})

        for (let formatElement of format) {
          let str = formatElement.split('(type)')
          if (!this.printerSetupList.includes(str[0])) {
            if (notFound.includes(str[0])){
              continue
            }
            notFound.push(str[0])
            continue
          }
          if (str[1] === 'Alpha/Hard Tag'){
            printAlphaHardTagLabel(dataList,base64List,str[0])
          }else if (str[1] === 'Hardware(Antenna)'){
            printAntennaLabel(dataList,base64List,str[0])
          }else if (str[1] === 'RF' || str[1] === 'RFID'){
            printRF_RFIDLabel(dataList,base64List,str[0])
          }
        }
      }
      this.$refs.table.clearSelection()
      if (notFound.length > 0){
        this.$message.warning(`The printer ${notFound.join(',')} is not found`)
      }else {
        this.$message.success("Print label success")
      }
    },
    handleSizeChange(val){
      this.size = val
      this.getPrintLabelRecordList()
    },
    handleCurrentChange(val){
      this.no = val
      this.getPrintLabelRecordList()
    },
    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;
        }
      }
    },
  },
  mounted () {
    const lodop = getLodop()
    for (let i = 0; i < lodop.GET_PRINTER_COUNT(); i++) {
      this.printerSetupList.push(lodop.GET_PRINTER_NAME(i))
    }
  },
  created () {
    // this.getPrintLabelRecordList()
    this.getTableUserColumn('30006Table',1)
  },
}
</script>

<template>
  <div>
    <div style="min-width: 600px;max-width: 1000px">
      <el-form :model="printRecord" label-position="top">
        <el-row :gutter="20">
          <el-col :span="4">
            <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="printRecord.customerNo" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Customer Name">
              <el-input v-model="printRecord.customerName" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="11">
                <el-form-item label="Created Time">
                  <el-date-picker
                    v-model="printRecord.startDate"
                    style="width: 100%;"
                    type="date"
                    placeholder=" ">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label=" ">
                  <div style="text-align: center"><i class="el-icon-right"></i></div>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label=" ">
                  <el-date-picker
                    v-model="printRecord.endDate"
                    style="width: 100%;"
                    type="date"
                    placeholder=" ">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="4">
            <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="printRecord.partNo" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="Part Description">
              <el-input v-model="printRecord.partDesc" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label=" ">
              <el-button type="primary" style="width: 60px" @click="getPrintLabelRecordList">Query</el-button>
              <el-button type="primary" style="width: 60px" @click="handlePrintLabel">Print</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-table :data="printLabelRecordList" ref="table" @selection-change="handleSelectionChange"
              style="width: 100%;margin-top: 10px" border :height="height">
      <el-table-column type="selection" width="55" fixed="left" align="center"></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>
    <div>
      <selection-table :size="selectionPrintLabelRecordList.length" :total="total"></selection-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">
      </el-pagination>
    </div>
    <qr-code ref="qrCode"></qr-code>
    <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>
</template>

<style scoped>

</style>
