import { updateRecipeStatus } from "@/api/decoct/recipe";
import { updatePrintStatus } from "@/api/prescription/prescriptionCore";
export default {
  data: function () {
    return {
        //{"value":"USB","label":"USB","disabled":false},{"value":"SERIAL","label":"串口","disabled":false},{"value":"NET","label":"网口","disabled":false}
        models: [],
        conModel: 'USB',
        isPortModel: true,
        connected: false,
        /** 网口配置 */
        websock: null,
        /** USB配置 */
        webusb: null,
        /** 串口配置 */
        webserial: null,
        form: {
            selectName: '未连接',
            socketAddr: '127.0.0.1',
            socketPort: 8003,
            printData: ''
        },
        recipeId: '',
        auditId: '',
        deployId: '',
        printType: ''
    }
  },
  created() {
    //验证是否支持各类通信类型
    if (!'usb' in navigator) {
      console.error('WebUSB API is not supported!')
      // this.models.push({ "value": "USB", "label": "USB", "disabled": true })
    } else {
        // this.models.push({ "value": "USB", "label": "USB", "disabled": false })
    }
    // this.modelChange()
  },
  methods: {
    async modelChange(value, type) {
      const that = this;
      that.form.printData = value
      that.printType = type
      // debugger
      console.log('[navigator.usb]', navigator.usb);
      //添加事件监听
      await navigator.usb.addEventListener('connect', event => {
          //重新连接成功
          that.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 => {
        console.log('getDevices',devices);
          if (devices.length > 0) {
              //找到前面选择的一个USB
              that.webusb = devices[0];
              that.form.selectName = devices[0].productName;
              //打开usb
              that.openWebUsb();
          }else{

            this.choicePort()
          }
      });
    },
    async choicePort() {
      const that = this;
      // return
      await navigator.usb.requestDevice({ filters: [] })
          .then(usb => {
              // 业务逻辑处理
              that.webusb = usb;
              that.form.selectName = usb.productName;
              that.openWebUsb();
          }).catch(error => {
              console.error("choicePort：" + error);
          });
    },
    async openWebUsb() {
      await this.webusb.open();
      await this.webusb.selectConfiguration(1);
      await this.webusb.claimInterface(0);
      console.log(' this.webusb ', this.webusb.claimInterface(0) )
      console.log("USB准备就绪，可以进行读写");
      this.connected = true;
      this.sendPrint()
    },
    async sendPrint() {
      if (this.form.printData.trim().length == 0) {
          this.$message.error('打印内容不能为空')
          return;
      }
      const printData = encodeToGb2312(this.form.printData)
      const testprint = gpTool.hexStringToByteArray(printData)
      const data = Array.from(testprint)
      const encodedCmds = new ArrayBuffer(data.length)
      var dataView = new DataView(encodedCmds)
      for (var j = 0; j < data.length; j++) {
          dataView.setUint8(j, data[j]);
      }
      await this.writePrintData(encodedCmds)
    },
    async writePrintData(encodedCmds) {
      //const encodedCmds = new Uint8Array(new TextEncoder().encode(this.form.printData))
      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);
          return
      }
      this.$message.success("发送打印成功");
      this.setPrintStatus()
    },
    setPrintStatus() {
      if(this.printType == 'recipe'){
        updateRecipeStatus({
          id: this.recipeId,
        });
      }else if(this.printType == 'audit'){
        updatePrintStatus({
          isPrint: "1",
          id: this.auditId,
        });
      }else if(this.printType == 'deploy') {
        updatePrintStatus({
          isPrint: "1",
          id: this.deployId,
        });
      }
    }
  },
}
