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('wss://127.0.0.1:18653');
      this.socket = socket;
      socket.onerror = function (event) {
        socket = null;
        that.isSocketOpen = false;
        console.log('WebSocket error:', event);
        that.$baseAlert(that.$t2('启动失败，请确认拼多多打印控件已打开', 'components.pddPrint.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 = 'http://meta.pinduoduo.com/api/one/app/v1/lateststable?appId=com.xunmeng.pddprint&platform=windows&subType=main';
      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.pddPrint.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.taskID = this.getUUID(8, 16);
          if (isPreview) {
            request.task.previewType = "image";
          }
          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 = {
        "ERPId": "3245a7db41bf45f787f00a45eb784875",
        "ISVName": "ETW电商管理系统",
        "cmd": "print",
        "requestID": "90E064371",
        "task": {
          "documents": [
            {
              "contents": [
                {
                  "encryptedData": "nCGXTLX57Gy747SrsozPkywPsv/CN4Dg93AB5VW7aOYlGo3aM7Dwcs/BWlGXR1RgplnsD78RiIGqME4WX1PxpMfMaQUxSbmwnLgOfJRHyJjRd8+Lgu4NQcBsd6lwrhPzDGeTC3dFKUw1Of/mWMiVJjFQRZD2cC4RdGJjwtPynZnIN5ll/ON45pcIMLqRn1LOyvrq3QgMMIQKkNhmxU9ZrRmm9ZOpGYbMP1jvQaz6lo3ko/bHuvB49v1NBSrkR3MGPnEF4JPcQ+YZVFkyaWKeTbQJppjzGFOJSLlxrF4RfgHnnoHfkyD7gLv/x0+NvrVyOePXdbxirg18EvhE2kPjp9cZhgHzsW8Qz1HGZwuyOAiC874g4Ptz4/8k2WneMNgxQahtRJeBsyLnpaubhK0UsFd+17ZUQ5A++5tD1FNhKFH5f91DN1Oo1JQmUxOSK7nagtx0PITnfDnEkYDVhGnoDpzRqL6KjZ7XcaWVOvLAfP3nX94UzW8QvpB6BlHKsCAQJ1uiRVO59pvemXOAimd6W54+0lhCgdKhpgKYC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r1lKfoazDfnpuVW4q0Y0ghYFQer0zbRRGkl9n01HG2N8=",
                  "templateUrl": "https://file-link.pinduoduo.com/sf_one",

                  "ver": "11"
                }

              ],
              "documentID": "55200106498692151"
            }
          ],
          "notifyType": [
            "print"
          ],
          "preview": true,
          "previewType": "image",
          "printer": "Microsoft Print to PDF",
          "taskID": "032818431"
        },
        "version": "1.0"
      };
      request.task.preview = isPreview;
      request.task.printer = isPreview ? "" : printer;
      request.task.taskID = this.getUUID(8, 16);
      if (isPreview) {
        request.task.previewType = "image";
      }
      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;
          break;
        case 'getPrinterConfig':
          break;
        case 'print':
          console.log('pdd-response:', data);
          this.onAfterPrint();
          break;
        case 'PrintResultNotify':
          console.log('pdd-PrintResultNotify-response:', data);
          break;
        case 'setPrinterConfig':
          break;
      }
      if (data.status == 'failed' && data.msg) {
        this.$baseAlert(data.msg)
      }
      /*if (!!data.previewURL) {
        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;
