let modules = {};
modules = {
  data() {
    return {
      option: {},
      showWrap: false,
      isSocketOpen: false,
      printerVal: null,
      printerList: [],
      socket: null,
      defaultPrinter: null
    };
  },
  mounted() {
  },
  methods: {
    dialogClose() {
      this.showWrap = false;
      let socket = this.socket;
      socket && socket.close();
      this.socket = null;
      this.isSocketOpen = false;
      this.$emit('update:visiable', false);
    },
    openWebSocket() {
      const that = this;
      if (this.socket) {
        this.socket.close();
        this.socket = null;
      }
      let socket = new WebSocket('ws://127.0.0.1:13528');
      this.socket = socket;
      socket.onerror = function (event) {
        socket = null;
        that.isSocketOpen = false;
        that.$baseAlert(that.$t2('启动失败，请确认菜鸟打印控件已打开', 'components.cnPrint.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://cainiao-oss-sh-read.oss-cn-shanghai.aliyuncs.com/waybill-print/multiplatform-client/cainiao-x-print.dmg?spm=a219a.7386653.0.0.7697669aoaEa3n&file=cainiao-x-print.dmg' :
        'http://cloudprint.cainiao.com/cloudprint/client/CNPrintSetup.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.cnPrint.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 || {};
          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':
          this.onAfterPrint();
          break;
        case 'notifyPrintResult':
          break;
        case 'setPrinterConfig':
          break;
      }
      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;
