<template>
  <div>
    <el-dialog
      title="标签打印"
      width="40%"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="auto">
        <el-collapse v-model="activeNames">
          <el-collapse-item title="物料信息：" name="1">
            <el-form-item label="编码" prop="id">
              <el-input v-model="dataForm.id" disabled placeholder="编码不可修改"></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="materialName">
              <el-input v-model="dataForm.materialName" placeholder="名称"></el-input>
            </el-form-item>
            <el-form-item label="图号" prop="mapNumber">
              <el-input v-model="dataForm.mapNumber" placeholder="图号"></el-input>
            </el-form-item>
            <el-form-item label="规格" prop="productSpec">
              <el-input v-model="dataForm.productSpec" placeholder="规格"></el-input>
            </el-form-item>
            <el-form-item label="批次" prop="batchNumber">
              <el-input v-model="dataForm.batchNumber" placeholder="批次"></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="cnt">
              <el-input-number v-model="dataForm.cnt" :min="1" label="数量"></el-input-number>
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="打印设置：" name="2">
            <el-row>
              <el-form-item label="通信模式">
                <el-select v-model="conModel" placeholder="请选择通信模式" @change="modelChange">
                  <el-option v-for="item in models" :key="item.value" :disabled="item.disabled"
                             :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="端口信息" v-show="isPortModel">
                <el-col style="width: 300px">
                  <el-input type="text" placeholder="请选择端口" :disable="true" v-model="form.selectName" :readonly="true" />
                </el-col>
                <el-col style="width: 100px;margin-left: 20px;">
                  <el-button type="primary" @click="choicePort">选择端口</el-button>
                </el-col>
              </el-form-item>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <span slot="footer">
        <el-button @click="onChose">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()" v-reClick>确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {createNew} from '@/utils/print-js/tsc'
import {getDataView} from '@/utils/print-js/function'
export default {
  name: 'print-label',
  data () {
    return {
      visible: false,
      activeNames: ['1', '2'],
      dataForm: { },
      conModel: 'USB',
      isPortModel: true,
      connected: false,
      /** 网口配置 */
      websock: null,
      /** USB配置 */
      webusb: null,
      /** 串口配置 */
      webserial: null,
      form: {
        selectName: '未连接',
        socketAddr: '127.0.0.1',
        socketPort: 8003,
        printData: ''
      },
      models: [{ 'value': 'USB', 'label': 'USB', 'disabled': false }],
      dataRule: { }
    }
  },
  methods: {
    async init (row) {
      this.visible = true
      this.dataForm = {
        ...row,
        productSpec: row.productSpec ? row.productSpec : '/',
        batchNumber: row.batchNumber ? row.batchNumber : '/',
        mapNumber: row.mapNumber ? row.mapNumber : '/',
        cnt: row.cnt ? row.cnt : 0
      }
      // this.models.push({ 'value': 'USB', 'label': 'USB', 'disabled': false })
    },
    validateField (type) {
      this.$refs.dataForm.validateField(type)
    },
    onChose () {
      this.visible = false
      this.$emit('onChose')
    },
    async modelChange (value) {
      const that = this
      if (value === 'USB') {
        that.isPortModel = true
        // 添加事件监听
        await navigator.usb.addEventListener('connect', event => {
          // 重新连接成功
          this.webusb = event.device
          that.form.selectName = event.device.productName
          that.$message.success('USB连接成功')
          that.openWebUsb()
        })
        await navigator.usb.addEventListener('disconnect', event => {
          // 断开连接成功
          that.form.selectName = '未连接'
          that.connected = false
          that.$message.error('USB连接断开')
        })
        await navigator.usb.getDevices().then(devices => {
          if (devices.length > 0) {
            // 找到前面选择的一个USB
            that.webusb = devices[0]
            that.form.selectName = devices[0].productName
            // 打开usb
            that.openWebUsb()
          }
        })
      } else {
        this.isPortModel = false
      }
    },
    async openWebUsb () {
      await this.webusb.open()
      await this.webusb.selectConfiguration(1)
      await this.webusb.claimInterface(0)
      console.log('USB准备就绪，可以进行读写')
      this.connected = true
    },
    async choicePort () {
      const that = this
      if (that.conModel === 'USB') {
        await navigator.usb.requestDevice({ filters: [] })
          .then(usb => {
            // 业务逻辑处理
            that.webusb = usb
            that.form.selectName = usb.productName
            that.openWebUsb()
          }).catch(error => {
            console.error('choicePort：' + error)
          })
      } else {
        that.$message.error('请选择通信模式')
      }
    },
    async sendPrint () {
      // 标签模式
      const command = createNew()
      // console.log(command)
      command.setSize(43, 30)
      command.setGap(20, 0)
      command.setCls()
      let start = 5
      let len = 28
      // command.setText(50, 10, "TSS24.BF2", 0, 0, "打印测试") // 文本
      command.setText(50, start, 'TSS24.BF2', 0, 0, '名称:' + this.dataForm.materialName) // 文本
      command.setText(50, start + len, 'TSS24.BF2', 0, 0, '图号:' + this.dataForm.mapNumber) // 文本
      command.setText(50, start + 2 * len, 'TSS24.BF2', 0, 0, '规格:' + this.dataForm.productSpec) // 文本
      command.setText(50, start + 3 * len, 'TSS24.BF2', 0, 0, '批次:' + this.dataForm.batchNumber) // 文本
      command.setText(50, start + 4 * len, 'TSS24.BF2', 0, 0, '数量:' + this.dataForm.cnt) // 文本
      // command.setText(50, 130, "TSS24.BF2", 0, 0, "检  字 号：101029") // 文本
      // command.setText(50, 180, "TSS24.BF2", 0, 0, "原材料炉批号：YXL-83829") // 文本
      // command.setText(50, 170, "TSS24.BF2", 0, 0, "备注：这是一个备注") // 文本
      // command.setBar(50, start + 5 * len, '128', 64, 1, 2, 4, this.dataForm.id) // 条形码
      command.setQR(50, start + 5 * len, 'H', 3, 'A', this.dataForm.id.toString()) // 二维码
      command.setPagePrint()
      await this.writePrintData(getDataView(command.getData()))
    },
    async writePrintData (encodedCmds) {
      if (this.conModel === 'USB') {
        try {
          await this.webusb.transferOut(
            this.webusb.configuration.interfaces[0].alternate.endpoints.find(obj => obj.direction === 'out').endpointNumber, encodedCmds
          )
        } catch (error) {
          this.$message.error('发送失败，请确认是否正常链接打印机')
          // 如果任何操作失败，我们可以认为设备连接可能存在问题
          console.error('sendPrint：', error)
        }
      }
      this.$message.success('发送打印成功')
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 打印
          this.sendPrint()
          this.onChose()
          this.$emit('addOne', this.dataForm)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
