import {defaultElementTypeProvider, hiprint} from '../../index'
// import {providers, providerList} from './providers'
// import panel from './panel'
import printData from './print-data'
import printPreview from './preview'
import jsonView from "../json-view.vue";
import fontSize from "./font-size.js";
import scale from "./scale.js";

import templateJson1 from './templateJson1'
import templateJson2 from './templateJson2'
// disAutoConnect();
let modules;
let hiprintTemplate;
modules = {
  components: {printPreview, jsonView},
  props: {
    printJson: {
      type:Object
    }
  },
  data() {
    return {
      visible: false,
      template: null,
      curPaper: {
        type: 'A4',
        width: 210,
        height: 296.6
      },
      paperTypes: {
        /*'A3': {
          width: 420,
          height: 296.6
        },*/
        'A4': {
          width: 210,
          height: 296.6
        },
        /*'A5': {
          width: 210,
          height: 147.6
        },
        'B3': {
          width: 500,
          height: 352.6
        },
        'B4': {
          width: 250,
          height: 352.6
        },
        'B5': {
          width: 250,
          height: 175.6
        }*/
      },
      // 自定义纸张
      paperPopVisible: false,
      paperWidth: '220',
      paperHeight: '80',
      // 缩放
      scaleValue: 1,
      scaleMax: 5,
      scaleMin: 0.5,
      // 导入导出json
      jsonIn: '',
      jsonOut: '',
    }
  },
  computed: {
    curPaperType() {
      let type = 'other'
      let types = this.paperTypes
      for (const key in types) {
        let item = types[key]
        let {width, height} = this.curPaper
        if (item.width === width && item.height === height) {
          type = key
        }
      }
      return type
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let printJson = this.printJson || {
        "panels": [
          {
            "index": 0,
            "name": "默认面板名称",
            "paperType": "A4",
          }
        ]
      };
      this.initCurPaper(printJson);
      hiprint.init({
        providers: [new defaultElementTypeProvider()]
      });
      // 还原配置
      hiprint.setConfig();
      // 替换配置
      hiprint.setConfig({
        optionItems: [
          fontSize,
          scale,
          function () {
            function t() {
              this.name = "zIndex";
            }

            return t.prototype.css = function (t, e) {
              if (t && t.length) {
                if (e) return t.css('z-index', e);
              }
              return null;
            }, t.prototype.createTarget = function () {
              return this.target = $('<div class="hiprint-option-item">\n        <div class="hiprint-option-item-label">\n        元素层级2\n        </div>\n        <div class="hiprint-option-item-field">\n        <input type="number" class="auto-submit"/>\n        </div>\n    </div>'), this.target;
            }, t.prototype.getValue = function () {
              var t = this.target.find("input").val();
              if (t) return parseInt(t.toString());
            }, t.prototype.setValue = function (t) {
              this.target.find("input").val(t);
            }, t.prototype.destroy = function () {
              this.target.remove();
            }, t;
          }(),
        ],
        movingDistance: 2.5,
        text: {
          tabs: [
            // 隐藏部分
            {
              // name: '测试', // tab名称 可忽略
              options: [] // 必须包含 options
            },// 当修改第二个 tabs 时,必须把他之前的 tabs 都列举出来.
            {
              name: '样式', options: [
                {
                  name: 'scale',
                  after: 'transform', // 自定义参数，插入在 transform 之后
                  hidden: false
                },
              ]
            }
          ],
          supportOptions: [
            {
              name: 'styler',
              hidden: true
            },
            {
              name: 'scale', // 自定义参数，supportOptions 必须得添加
              after: 'transform', // 自定义参数，插入在 transform 之后
              hidden: false
            },
            {
              name: 'formatter',
              hidden: true
            },
          ]
        },
        image: {
          tabs: [
            {
              // 整体替换
              replace: true,
              name: '基本', options: [
                {
                  name: 'field',
                  hidden: false
                },
                {
                  name: 'src',
                  hidden: false
                },
                {
                  name: 'fit',
                  hidden: false
                }
              ]
            },
          ],
        }
      });
      // eslint-disable-next-line no-undef
      hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
      $('#hiprint-printTemplate').empty();
      let that = this;
      this.template = hiprintTemplate = new hiprint.PrintTemplate({
        template: printJson,
        // 图片选择功能
        onImageChooseClick: (target) => {
          // 测试 3秒后修改图片地址值
          setTimeout(() => {
            // target.refresh(url,options,callback)
            // callback(el, width, height) // 原元素,宽,高
            // target.refresh(url,false,(el,width,height)=>{
            //   el.options.width = width;
            //   el.designTarget.css('width', width + "pt");
            //   el.designTarget.children('.resize-panel').trigger($.Event('click'));
            // })
            target.refresh("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAtAAAAIIAQMAAAB99EudAAAABlBMVEUmf8vG2O41LStnAAABD0lEQVR42u3XQQqCQBSAYcWFS4/QUTpaHa2jdISWLUJjjMpclJoPGvq+1WsYfiJCZ4oCAAAAAAAAAAAAAAAAAHin6pL9c6H/fOzHbRrP0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0u/SY9LS0tLS0tLS0tLS0n+edm+UlpaWlpaWlpaWlpaW/tl0Ndyzbno7/+tPTJdd1wal69dNa6abx+Lq6TSeYtK7BX/Diek0XULSZZrakPRtV0i6Hu/KIt30q4fM0pvBqvR9mvsQkZaW9gyJT+f5lsnzjR54xAk8mAUeJyMPwYFH98ALx5Jr0kRLLndT7b64UX9QR/0eAAAAAAAAAAAAAAAAAAD/4gpryzr/bja4QgAAAABJRU5ErkJggg==", {
              // auto: true, // 根据图片宽高自动等比(宽>高?width:height)
              // width: true, // 按宽调整高
              // height: true, // 按高调整宽
              real: true // 根据图片实际尺寸调整(转pt)
            })
          }, 3000)
          // target.getValue()
          // target.refresh(url)
        },
        // 自定义可选字体
        // 或者使用 hiprintTemplate.setFontList([])
        // 或元素中 options.fontList: []
        fontList: [
          {title: '微软雅黑', value: 'Microsoft YaHei'},
          {title: '黑体', value: 'STHeitiSC-Light'},
          {title: '思源黑体', value: 'SourceHanSansCN-Normal'},
          {title: '王羲之书法体', value: '王羲之书法体'},
          {title: '宋体', value: 'SimSun'},
          {title: '华为楷体', value: 'STKaiti'},
          {title: 'cursive', value: 'cursive'},
        ],
        dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
        history: true, // 是否需要 撤销重做功能
        onDataChanged: (type, json) => {
          console.log(type); // 新增、移动、删除、修改(参数调整)、大小、旋转
          console.log(json); // 返回 template
        },
        onUpdateError: (e) => {
          console.log(e);
        },
        settingContainer: '#PrintElementOptionSetting',
        paginationContainer: '.hiprint-printPagination',
        defaultPanelName: '默认面板名称',
        onPanelAddClick: (panel, createPanel) => {
          panel.name = '新面板' + (panel.index + 1);
          /*that.$message.success('弹出个东西,让你们知道,在这里可以自定义面板名称');
          that.$notification.success({
            placement: 'topRight',
            message: '弹出个东西,让你们知道,在这里可以自定义面板名称',
            description: '自定义面板名称',
          });*/
          createPanel(panel);
        },
      });
      hiprintTemplate.design('#hiprint-printTemplate', {grid: true});
      console.log(hiprintTemplate);
      // 获取当前放大比例, 当zoom时传true 才会有
      this.scaleValue = hiprintTemplate.editingPanel.scale || 1;


    },
    initCurPaper(printJson) {
      if (printJson && printJson.panels && printJson.panels.length) {
        let width = printJson.panels[0].width;
        let height = printJson.panels[0].height;
        let type = 'other';
        let types = this.paperTypes;
        for (const key in types) {
          let item = types[key];
          // let {width, height} = this.curPaper
          if (item.width === width && item.height === height) {
            type = key;
          }
        }
        this.paperWidth = width;
        this.paperHeight = height;
        this.curPaper = {type: type, width: width, height: height};
      }
    },
    /**
     * 设置纸张大小
     * @param type [A3, A4, A5, B3, B4, B5, other]
     * @param value {width,height} mm
     */
    setPaper(type, value) {
      try {
        if (Object.keys(this.paperTypes).includes(type)) {
          this.curPaper = {type: type, width: value.width, height: value.height};
          hiprintTemplate.setPaper(value.width, value.height);
        } else {
          this.curPaper = {type: 'other', width: value.width, height: value.height};
          hiprintTemplate.setPaper(value.width, value.height);
        }
      } catch (error) {
        this.$message.error(`操作失败: ${error}`);
      }
    },
    otherPaper() {
      let value = {}
      value.width = this.paperWidth;
      value.height = this.paperHeight;
      this.paperPopVisible = false;
      this.setPaper('other', value);
    },
    changeScale(big) {
      let scaleValue = this.scaleValue;
      if (big) {
        scaleValue += 0.1;
        if (scaleValue > this.scaleMax) scaleValue = 5;
      } else {
        scaleValue -= 0.1;
        if (scaleValue < this.scaleMin) scaleValue = 0.5;
      }
      if (hiprintTemplate) {
        // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
        hiprintTemplate.zoom(scaleValue);
        this.scaleValue = scaleValue;
      }
    },
    rotatePaper() {
      if (hiprintTemplate) {
        hiprintTemplate.rotatePaper();
      }
    },
    preView() {
      // 测试, 点预览更新拖拽元素
      hiprint.updateElementType('defaultModule.text', (type) => {
        type.title = '这是更新后的元素';
        ;
        return type;
      });
      // 测试, 通过socket刷新打印机列表； 默认只有连接的时候才会获取到最新的打印机列表
      hiprint.refreshPrinterList((list) => {
        console.log('refreshPrinterList');
        console.log(list);
      });
      // 测试, 获取IP、IPV6、MAC地址、DNS
      // 参数格式：
      // 1. 类型（ip、ipv6、mac、dns、all、interface、vboxnet）
      // 2. 回调 data => {addr, e}  addr: 返回的数据 e:错误信息
      // 3. 其他参数 ...args
      hiprint.getAddress('ip', (data) => {
        console.log('ip');
        console.log(data);
      })
      hiprint.getAddress('ipv6', (data) => {
        console.log('ipv6');
        console.log(data);
      })
      hiprint.getAddress('mac', (data) => {
        console.log('mac');
        console.log(data);
      })
      hiprint.getAddress('dns', (data) => {
        console.log('dns');
        console.log(data);
      })
      hiprint.getAddress('all', (data) => {
        console.log('all');
        console.log(data);
      })
      // 各个平台不一样, 用法见: https://www.npmjs.com/package/address
      hiprint.getAddress('interface', (data) => {
        console.log('interface')
        console.log(data)
      }, 'IPv4', 'eth1');
      this.$refs.preView.show(hiprintTemplate, printData);
    },
    onlyPrint() {
      let hiprintTemplate = this.$print(undefined, panel, printData, {}, {
        styleHandler: () => {
          let css = '<link href="http://hiprint.io/Content/hiprint/css/print-lock.css" media="print" rel="stylesheet">';
          return css
        }
      });
      console.log(hiprintTemplate);
    },
    onlyPrint2() {
      let that = this;
      if (window.hiwebSocket.opened) {
        let hiprintTemplate = this.$print2(undefined, panel, printData, {
          printer: '', title: 'Api单独打印',
          styleHandler: () => {
            // let css = '<link href="http://hiprint.io/Content/hiprint/css/print-lock.css" media="print" rel="stylesheet">';
            let css = '<style>.hiprint-printElement-text{color:red !important;}</style>'
            return css
          }
        });
        let key = 'Api单独直接打印';
        hiprintTemplate.on('printSuccess', function () {
          that.$notification.success({
            key: key,
            placement: 'topRight',
            message: key + ' 打印成功',
            description: 'Api单独直接打印回调',
          });
        });
        return;
      }
      this.$message.error('客户端未连接,无法直接打印');
    },
    print() {
      if (window.hiwebSocket.opened) {
        const printerList = hiprintTemplate.getPrinterList();
        console.log(printerList);
        hiprintTemplate.print2(printData, {printer: '', title: 'hiprint测试打印'});
        return;
      }
      this.$message.error('客户端未连接,无法直接打印');
    },
    clearPaper() {
      try {
        hiprintTemplate.clear();
        this.setPaper('A4', this.paperTypes['A4']);
        hiprintTemplate.update({
          "panels": [
            {
              "index": 0,
              "name": 1,
              "paperType": "A4",
              "height": 297,
              "width": 210,
              "paperHeader": 0,
              "paperFooter": 841.8897637795277,
              "printElements": [],
              "paperNumberLeft": 568.5,
              "paperNumberTop": 820.5,
              "watermarkOptions": {}
            }
          ]
        });
      } catch (error) {
        this.$message.error(`操作失败: ${error}`);
      }
    },
    ippPrintAttr() {
      // 不知道打印机 ipp 情况， 可通过 '客户端' 获取一下
      const printerList = hiprintTemplate.getPrinterList();
      console.log(printerList)
      if (!printerList.length) return;
      let p = printerList[0];
      console.log(p);
      // 系统不同， 参数可能不同
      let url = p.options['printer-uri-supported'];
      // 测试 获取 ipp打印 支持参数
      hiprint.ippPrint({
        url: url,
        // 打印机参数： {version,uri,charset,language}
        opt: {},
        action: 'Get-Printer-Attributes', // 获取打印机支持参数
        // ipp参数
        message: null,
      }, (res) => {
        // 执行的ipp 任务回调 / 错误回调
        console.log(res);
      }, (printer) => {
        // ipp连接成功 回调 打印机信息
        console.log(printer);
      })
    },
    ippPrintTest() {
      // 不知道打印机 ipp 情况， 可通过 '客户端' 获取一下
      const printerList = hiprintTemplate.getPrinterList();
      console.log(printerList);
      if (!printerList.length) return;
      let p = printerList[0];
      console.log(p);
      // 系统不同， 参数可能不同
      let url = p.options['printer-uri-supported'];
      // 测试 打印文本
      hiprint.ippPrint({
        url: url,
        // 打印机参数： {version,uri,charset,language}
        opt: {},
        action: 'Print-Job',
        // ipp参数
        message: {
          "operation-attributes-tag": {
            "requesting-user-name": "hiPrint", // 用户名
            "job-name": "ipp Test Job", // 任务名
            "document-format": "text/plain" // 文档类型
          },
          // data 需为 Buffer (客户端简单处理了string 转 Buffer), 支持设置 encoding
          // data 需为 Buffer (客户端简单处理了string 转 Buffer), 支持设置 encoding
          // data 需为 Buffer (客户端简单处理了string 转 Buffer), 支持设置 encoding
          // 其他 Uint8Array/ArrayBuffer   默认仅 使用 Buffer.from(data)
          // 其他 Uint8Array/ArrayBuffer   默认仅 使用 Buffer.from(data)
          // 其他 Uint8Array/ArrayBuffer   默认仅 使用 Buffer.from(data)
          // 其他 Uint8Array/ArrayBuffer   默认仅 使用 Buffer.from(data)
          data: 'test test test test test test test',
          encoding: 'utf-8' // 默认可不传
        }
      }, (res) => {
        // 执行的ipp 任务回调 / 错误回调
        console.log(res);
      }, (printer) => {
        // ipp连接成功 回调 打印机信息
        console.log(printer);
      })
    },
    // 自定义 ipp 请求
    ippRequestTest() {
      const printerList = hiprintTemplate.getPrinterList();
      console.log(printerList);
      if (!printerList.length) return;
      let p = printerList[0];
      console.log(p);
      // 系统不同， 参数可能不同
      let url = p.options['printer-uri-supported'];
      // 详见： https://www.npmjs.com/package/ipp
      hiprint.ippRequest({
        url: url,
        // 传入的数据 ipp.serialize 后 未做任何处理  打印内容 需要 Buffer
        // 传入的数据 ipp.serialize 后 未做任何处理  打印内容 需要 Buffer
        // 传入的数据 ipp.serialize 后 未做任何处理  打印内容 需要 Buffer
        data: {
          "operation": "Get-Printer-Attributes",
          "operation-attributes-tag": {
            // 测试发现 Request下列3个必须要有
            "attributes-charset": "utf-8",
            "attributes-natural-language": "zh-cn",
            "printer-uri": url
          }
        }
      }, (res) => {
        // 执行的ipp 任务回调 / 错误回调
        console.log(res);
      })
    },
    ippRequestPrint() {
      const printerList = hiprintTemplate.getPrinterList();
      console.log(printerList);
      if (!printerList.length) return;
      let p = printerList[0];
      console.log(p);
      // 系统不同， 参数可能不同
      let url = p.options['printer-uri-supported'];
      let str = "ippRequestPrint ippRequestPrint ippRequestPrint";
      let array = new Uint8Array(str.length);
      for (var i = 0; i < str.length; i++) {
        array[i] = str.charCodeAt(i);
      }
      let testData = array.buffer;
      // 详见： https://www.npmjs.com/package/ipp
      hiprint.ippRequest({
        url: url,
        // 传入的数据 ipp.serialize 后 未做任何处理  打印内容 需要 Buffer
        // 传入的数据 ipp.serialize 后 未做任何处理  打印内容 需要 Buffer
        // 传入的数据 ipp.serialize 后 未做任何处理  打印内容 需要 Buffer
        data: {
          "operation": "Print-Job",
          "operation-attributes-tag": {
            // 测试发现 Request下列3个必须要有
            "attributes-charset": "utf-8",
            "attributes-natural-language": "zh-cn",
            "printer-uri": url,
            "requesting-user-name": "hiPrint", // 用户名
            "job-name": "ipp Request Job", // 任务名
            "document-format": "text/plain" // 文档类型
          },
          data: testData
        }
      }, (res) => {
        // 执行的ipp 任务回调 / 错误回调
        console.log(res);
      })
    },
    updateJson() {
      if (hiprintTemplate) {
        try {
          hiprintTemplate.update(JSON.parse(this.jsonIn));
        } catch (e) {
          this.$message.error(`更新失败: ${e}`);
        }
      }
    },
    exportJson() {
      if (hiprintTemplate) {
        this.jsonOut = JSON.stringify(hiprintTemplate.getJson() || {});
      }
    },
    setElsAlign(e) {
      hiprintTemplate.setElsAlign(e);
    },
    setElsSpace(h) {
      hiprintTemplate.setElsSpace(10, h);
    },
    getSelectEls() {
      let els = hiprintTemplate.getSelectEls();
      console.log(els);
    },
    updateFontSize() {
      hiprintTemplate.updateOption('fontSize', 12);
    },
    updateFontWeight() {
      hiprintTemplate.updateOption('fontWeight', 'bolder');
    },
    getJson() {
      return hiprintTemplate.getJson() || {};
    },
    /*importDefaultTemplate() {
      this.initCurPaper(panel);
      let curPaper = this.curPaper;
      this.setPaper(curPaper.type, {
        width: curPaper.width,
        height: curPaper.height,
      });
      hiprintTemplate.update(panel)
    },*/
    importDefaultTemplate1() {
      this.initCurPaper(templateJson1);
      let curPaper = this.curPaper;
      this.setPaper(curPaper.type, {
        width: curPaper.width,
        height: curPaper.height,
      });
      hiprintTemplate.update(templateJson1)
    },
    importDefaultTemplate2() {
      this.initCurPaper(templateJson2);
      let curPaper = this.curPaper;
      this.setPaper(curPaper.type, {
        width: curPaper.width,
        height: curPaper.height,
      });
      hiprintTemplate.update(templateJson2)
    }
  }
};
export default modules;
