let modules = {};
modules = {
  data() {
    return {
      option: {},
      showWrap: false,
      isSocketOpen: false,
      printerVal: null,
      printerList: [],
      socket: null,
      defaultPrinter: null
    };
  },
  mounted() {
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  },
  methods: {
    dialogClose() {
      this.showWrap = false;
      let socket = this.socket;
      socket && socket.close();
      this.socket = null;
      this.isSocketOpen = false;
      this.$emit('update:visiable', false);
    },
    openWebSocket() {
      if (this.isSocketOpen) {
        return
      }
      const that = this;
      if (this.socket) {
        this.socket.close();
        this.socket = null;
      }
      let socket = new WebSocket('ws://localhost:14528');
      this.socket = socket;
      socket.onerror = function (event) {
        socket = null;
        that.isSocketOpen = false;
        console.log('WebSocket error:', event);

        that.$baseAlert(that.$t2('启动失败，请确认小红书打印控件已打开', 'components.xhsPrint.startFailMsg'));
      };
      socket.onopen = function (event) {
        that.isSocketOpen = true;
        // 监听消息
        socket.onmessage = function (event) {
          that.defaultPrinter = JSON.parse(event.data).defaultPrinter;
          that.subscribe(JSON.parse(event.data));
        };
        // 监听Socket的关闭
        socket.onclose = function (event) {
          that.isSocketOpen = false;
          socket = null;
        };
        that.getPrints();
      };
    },
    showMsgBox: function () {
      this.showWrap = true;
      this.openWebSocket();
    },
    download() {
      let isMac = this.getIsMac();
      let url = isMac ?
        'https://xhswaybill-printer-1251524319.cos.ap-shanghai.myqcloud.com/XHPrintTool/prod/win/xiaohongshu-mac.dmg' :
        'https://xhswaybill-printer-1251524319.cos.ap-shanghai.myqcloud.com/XHPrintTool/prod/win/xiaohongshu-win.exe';
      window.open(url);
    },
    getIsMac() {
      let agent = navigator.userAgent.toLowerCase();
      let isMac = /macintosh|mac os x/i.test(navigator.userAgent);
      /* if(agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0){
          alert("这是一个windows32位系统");
      }
      if(agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0){
          alert("这是一个windows64位系统");
      }
      if(isMac){
          alert("这是一个mac系统");
      }*/
      return isMac;
    },
    selectPrint(isPreView) {
      if (!isPreView && !this.printerVal) {
        this.$baseAlert(this.$t2('请选择打印机', 'components.xhsPrint.selectPrinterTip'));
        return;
      }
      this.openWebSocket();
      this.doPrint2(this.printerVal, isPreView);
    },
    doPrint2: function (printer, isPreview) {
      let param = this.option.getParam();
      param.condition.printer = printer;
      param.condition.preview = isPreview;
      this.$http({
        url: this.option.prefix + '/export_ins/export',
        method: `post`,
        data: param,
        isLoading: true,
        success: res => {
          let request = res.objx.data || {};

          request.task.preview = isPreview;
          request.task.printer = isPreview ? "" : printer;
          // request.task.previewType = "pdf"
          request.task.taskID = this.getUUID(8, 16);

          Object.assign(request, this.getRequestObject("print"))
          console.log('pdd-json:', request);
          this.socket.send(JSON.stringify(request));
          this.option.callback && this.option.callback(param, request);
        }
      });
    },
    doPrint1: function (printer, isPreview) {
      let request = {
        "cmd": "print",
        "requestID": "123456789",
        "version": "1.0",
        "task": {
          "taskID": "1",
          "preview": false,
          "printer": "",
          "previewType": "pdf",
          "firstDocumentNumber": 10,
          "totalDocumentCount": 100,
          "documents": [
            {
              "documentID": "10000001",
              "contents": [
                {
                  "encryptedData": "AES:DTqwa4Jcu6uPlUpnjBJ0PXI59KFw16QDENY6G8e27nuu1N9ovmjmqKkxZVFO/nxpI/qUQHUcR6AA8u3kxiDIn39m3Cote2og2AM8EHqigfUgkFTtRL8GzmAUGLJ1WWfeGqexNXXXAQ6r4ykSpBoHn7Wk4mZRG3Zw1skMw/doRGHBEt6WArUx0HKb9Yd3XdZIyvB5RejvtC7mHKt+J0YEsVPmPrAsxE3gZaWeJejtoHBLk1kwBADsG7EVbawFchHeMbFuhPhjNKBZ9tYp+f+UuAPetrbqJ2xwlaf3FT7kgqc90C9QYYzhhdjy973ygmApEE4kLWQjYrZyc7Gh66iOjMOZFPlSu2UkL1KsLEUWR1WVUD7DGyqDjnxrWDhsp03cT2F5x2QqgMZiloBfRgA6NiVQaLWNfCaNhhAJLp81zXS7EAyYbJ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vHSb5F+0sBFrn5tMn7RbFooMQHLla9x01vmwswOosKdFDdWGBvW/gLjUamquzCC8ogET7KNYknSbeWCPYEitgKw8Y1oqZjtj+1QK+y1opo5TZZuh+jVVI/+6vgqH94v6bzZfTDTNW7B+aasaJnWziVGLO3dJSWq4vQcTCAU4uu34bJ0eV1vE0MMgUtzesGQ7KTGT9ftR0ilHSyK3Ec55x5Nq3+1KDfgWR0PBNOUH2ls1s9dDaejUVDfIm+s4JNbKTTYz66zmxupgqu11enr6h3RyaEI/cfmm6y",
                  "signature": "MD:DWZH1DbnDNfH6muKGiwJ/A==",
                  "templateURL": "http://cloudprint.cainiao.com/template/standard/644703",
                  "ver": "waybill_print_xiaohongshu_secret"
                },
                {
                  "data": {
                    "item": [
                      "iphone14 红色 256G/1",
                      "iphone14 黑色 256G/1"
                    ],
                    "order": [
                      "P680942792256239451"
                    ],
                    "buyerMemo": [
                      "买家：打包注意点,尽快送达"
                    ],
                    "sellerMemo": [
                      "卖家：请及时签收"
                    ]
                  },
                  "templateURL": "https://cloudprint.cainiao.com/template/standard/629505/24"
                }
              ]
            }
          ]
        }
      };
      request.task.preview = isPreview;
      request.task.printer = isPreview ? "" : printer;
      // request.task.previewType = "pdf"
      request.task.taskID = this.getUUID(8, 16);

      Object.assign(request, this.getRequestObject("print"))
      this.socket.send(JSON.stringify(request));
      this.option.callback && this.option.callback(param, request);
    },
    subscribe: function (data) {
      let that = this;
      switch (data.cmd) {
        case 'getPrinters':
          that.printerList = data.printers;
          that.printerVal = data.defaultPrinter;
          break;
        case 'print':
          console.log('pdd-response:', data);
          this.onAfterPrint();
          break;
        case 'notifyPrintResult':
          break;
        case 'setPrinter':
          break;
      }
      if (data.status == 'failed') {
        this.$baseAlert(data.msg)
      }
      if (data.previewURL != null) {
        window.open(data.previewURL, '_blank');
      }
      if (data.previewImage != null && data.previewImage.length) {
        window.open(data.previewImage[0], '_blank');
      }

    },
    onAfterPrint() {
      let config = this.option.config;
      let template = this.option.template;
      config.onAfterPrint && config.onAfterPrint(template, this.dialogClose)
    },
    getPrints: function () {
      this.getPrintList(); //打印机列表
    },
    getExpressCompaniesPrinter: function () {
      let express_companies_printer = localStorage.getItem('rmt_set_express_companies_printer');
    },
    getPrinterConfig: function () {
      let socket = this;
      let request = this.getRequestObject('getPrinterConfig');
      request.printer = 'KM-118';
      if (socket.readyState === 1) {
        socket.send(JSON.stringify(request));
      }
    },
    setPrinterConfig: function () {
      let request = this.getRequestObject('setPrinterConfig');
      request.printer = {
        name: 'KM-118',
        needTopLogo: true
      };
      if (socket.readyState === 1) {
        socket.send(JSON.stringify(request));
      }
    },
    getPrintList: function () {
      let socket = this.socket;
      if (!socket) {
        return;
      }
      let request = this.getRequestObject('getPrinters');

      if (socket.readyState === 1) {
        socket.send(JSON.stringify(request));
      }
    },
    getRequestObject: function (cmd) {
      let request = new Object();
      request.requestID = this.getUUID(8, 16);
      request.version = '1.0';
      request.cmd = cmd;
      return request;
    },
    getUUID: function (len, radix) {
      let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
      let uuid = [],
        i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join('');
    }
  }
};
export default modules;
