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://127.0.0.1:12233');
      this.socket = socket;
      socket.onerror = function (event) {
        socket = null;
        that.isSocketOpen = false;
        console.log('WebSocket error:', event);

        that.$baseAlert(that.$t2('启动失败，请确认唯品会打印控件已打开', 'components.vipPrint.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 = 'https://vos.vipstatic.com/vip-lbs-printer/printer/vip_printer_setup_0.8.48.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.vipPrint.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.printerName = isPreview ? "" : printer;
          request.task.actionType = isPreview ? "PREVIEW" : "PRINT";
          request.task.traceId = 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": "147258369",
        "task": {
          "actionType": "PRINT",
          "traceId": "Q20220113",
          "storeId": "ST97906995",
          "printerName": "",
          "printParamDTO": {
            "templateUrl": "f4wAyLYO1dr1k+xr6Fcp1kOUo5pva5Cq6XQ1zFKCmw9Ca9rcfgJ7L5g6loB+agx+PDb66Gcn+RZeu4VrU8PGni95ioDF8ZXLh4MyeGpZSpEh+9Q4E+iQuZuK5hlQUf9XoL27F2DnAFX75Vfb9gBl1zGjiFrmewLO0MpkRbzwpAc=",
            "printDatas": [
              {
                "printId": "PT001",
                "printData": "{\"routeCode\":\"310 P115-00 15\",\"receiver.name\":\"Dcp/F0Bvod+neJoHEglxh+DhPwTJ9aKp56kNVd0HIIu+HfepPYFDV2Zz0hGRurXcmovZuzeFl14O2eBWkFKmlQfAr6CNXcZjdbM3F17PwIHQyjuzUiAqJOTN/a4xSjxZ0xzIHoR2N66oNJT5Z7x2jKxTuWZnlnD39uKmi9I2s5s=\",\"sender.address\":\"广东省广州市荔湾区花地街道广新信息大厦\",\"sender.tel\":\"13899999999\",\"sender.name\":\"123联调官方旗舰店\",\"goodsItems\":[{\"goodBrand\":\"123联调官方旗舰店\",\"goodsName\":\"商品名称\",\"goodsQty\":0}],\"transportNo\":\"3120054343259\",\"consolidation\":\"闵行地区包\",\"sender.mobile\":\"\",\"receiver.mobile\":\"\",\"receiver.address\":\"bgyA2X0xRY3a9aaOc2Zux5/3JNDnFa8B6U6pzd6iQaXnumfPrQqFVH6GEGD4Jc8UZYeUsfAE4R0yhPZ2eo3tA651/QNOL51bUANpCW7B1hau8PlFed/UzVrWFdVcSK8Nk1SlwGpo2LqXZ7WSExy+lpSgZzKMV28Deo4RnxOHCL4=\",\"receiver.tel\":\"QbjxlcqFmX9Gz5J+5dYIG9gIHJZjmFUsNzAY3VrAfvLwZHBGN+1pYkEUNekT4mzUWkaayPDbdOhWl9p4v79/FnU5rypr5/tYhiTtRTKmBi+K3KaXxKCG0Gak0Elupijnlleaf69Nm6NkZeyQglSOF7I3YqS6ME+jaz6/q2lsowo=\",\"carrierCode\":\"yunda\",\"proName\":\"P115-00\"}",
                "customData": {
                  "remark": "订单备注",
                  "adtxt": "提示信息",
                  "ext1": "拓展信息1",
                  "ext2": "拓展信息2",
                  "ext3": "拓展信息3"
                }
              },
              {
                "printId": "PT002",
                "printData": "",
                "customData": {
                  "remark": "订单备注",
                  "adtxt": "提示信息",
                  "ext1": "拓展信息1",
                  "ext2": "拓展信息2",
                  "ext3": "拓展信息3"
                }
              },
              {
                "printId": "PT003",
                "printData": "{\"routeCode\":receiver.address\":\"bgyA2X0xRY3a9aaOc2Zux5/3JNDnFa8B6U6pzd6iQaXnumfPrQqFVH6GEGD4Jc8UZYeUsfAE4R0yhPZ2eo3tA651/QNOL51bUANpCW7B1hau8PlFed/UzVrWFdVcSK8Nk1SlwGpo2LqXZ7WSExy+lpSgZzKMV28Deo4RnxOHCL4=\",\"receiver.tel\":\"QbjxlcqFmX9Gz5J+5dYIG9gIHJZjmFUsNzAY3VrAfvLwZHBGN+1pYkEUNekT4mzUWkaayPDbdOhWl9p4v79/FnU5rypr5/tYhiTtRTKmBi+K3KaXxKCG0Gak0Elupijnlleaf69Nm6NkZeyQglSOF7I3YqS6ME+jaz6/q2lsowo=\",\"carrierCode\":\"yunda\",\"proName\":\"P115-00\"}",
                "customData": {
                  "remark": "订单备注",
                  "adtxt": "提示信息",
                  "ext1": "拓展信息1",
                  "ext2": "拓展信息2",
                  "ext3": "拓展信息3"
                }
              }
            ],
            "senderData": {
              "name": "李xx",
              "tel": "1511xxx2798",
              "mobile": "1511xxx2798",
              "address": "浙江省xxx民和路601号"
            }
          }
        }
      };
      request.task.printerName = isPreview ? "" : printer;
      request.task.actionType = isPreview ? "PREVIEW" : "PRINT";
      request.task.traceId = 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 'setPrinter':
          break;
      }
      if (data.status == 'fail') {
        this.$baseAlert(data.msg)
      }
      if (data.previewURL != null) {
        window.open(data.previewURL, '_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;
