<template>
  <div>
    <div class="row m-row">
      <div class="col-md-12">
        <div class="form-inline">
          <div class="form-group">
            <label> {{ $t('lang.BarCodeEditPanel.selectPrintTemplate') }}</label>
            <select
              v-model="selected"
              class="form-control"
              @change="setIframeData"
            >
              <option />
              <option
                v-for="template in templates"
                :key="template.name"
                :value="template"
              >
                {{ template.name }}
              </option>
            </select>

            <button
              id="refreshBtn"
              class="btn btn-info"
              @click="refreshData"
            >
              {{ $t('lang.BarCodeEditPanel.refresh') }}
            </button>

            <button
              v-if="selected.name != undefined"
              id="finishBtn"
              class="btn btn-primary"
              @click="showModal"
            >
              {{ $t('lang.BarCodeEditPanel.save') }}
            </button>

            <button
              class="btn btn-default"
              @click="download()"
            >
              {{ $t('lang.BarCodeEditPanel.download') }}
            </button>
          </div>
          <PrintWidget
            :printer-localstorage-id="'#BarCodeEditPanelPrinter'"
            :show-print-button="true"
            @print="print($event)"
          />
        </div>
        <Modal
          v-model:show="modal"
          @ok="saveCustomerTemplate"
        >
          <template #header>
            {{ $t('lang.BarCodeEditPanel.customTemplate') }}
          </template>
          <input
            v-model="templateName"
            autocomplete="off"
            type="text"
            class="form-control"
            placeholder="输入自定义模板名称"
          />
        </Modal>
      </div>
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';

import { PrintUtil } from 'pc-component-v3';
import { Notify, Uuid } from 'pc-component-v3';
import dayjs from 'dayjs';

export default {

  components: {
  },

  data: function () {
    return {
      templates: [],
      selected: {},
      mPrintPage: {},
      templateName: '',
      modal: false,
    };
  },

  watch: {
    'selected': {
      handler: function (val, oldVal) {
        if (val != undefined && val.content != undefined) {
          if (val.content[0] != '{') {
            val.content = val.content.substring(1);
          }
          this.mPrintPage = JSON.parse(val.content);
        } else {
          this.mPrintPage = {};
        }
      },
      deep: true,
    },
  },

  mounted: function () {
    this.load();
  },

  methods: {
    /**
         * 调用iframe的init方法，绘制条码
         */
    setIframeData: function () {
      if (this.selected && this.selected.content) {
        while (this.selected.content.length > 0 && this.selected.content[0] != '{') {
          this.selected.content = this.selected.content.substring(1);
        }
        document.getElementById('mIframe0').contentWindow.init(this.selected.id, this.selected.name, this.selected.content);
      } else {
        this.$nextTick(function () {
          var mIframe0 = document.getElementById('mIframe0');
          if (mIframe0.contentWindow.init != null) {
            mIframe0.contentWindow.init(null, null, null);
          }
        });
      }
    },

    /**
         * 刷新数据
         */
    refreshData: function () {
      this.mPrintPage = {};
      this.load();
    },

    /**
         * 读取PrinterTemplate文件夹下所有的json文件，获取文件名
         */
    load: function () {
      var _self = this;

      $.ajax({
        url: Common.getApiURL('printPageResource/getJsonFileName'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if(data.errorCode != 0) {
            Notify.error('提示', data.errorMessage, false);
            return;
          }
          _self.templates = data.datas;
          if (_self.selected != undefined && _self.selected.name != undefined && _self.templates != undefined && _self.templates.length > 0) {
            for (var i = 0; i < _self.templates.length; i++) {
              if (_self.templates[i].name == _self.selected.name) {
                _self.mPrintPage = JSON.parse(_self.templates[i].content);
              }
            }
          }
          _self.setIframeData();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 保存自定义模板
    saveCustomerTemplate: function () {
      var _self = this;
      var printPageJson = {
        'name': _self.templateName,
        'content': JSON.stringify(_self.mPrintPage),
        'type': _self.selected.type,
        'sourceFileName': _self.selected.name,
        'no': dayjs(new Date()).format('YYYY-MM-DD HH:mm'),
      };

      $.ajax({
        url: Common.getApiURL('printPageResource/saveCustomerPrintTemplate'),
        dataType: 'json',
        type: 'post',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(printPageJson),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          Notify.success('成功', '自定义模板生成成功', 1500);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    showModal: function () {
      this.modal=true;
    },

    /**
         * 下载模板json文件 
         */
    download: function () {
      var _self = this;
      var printData = document.getElementById('mIframe0').contentWindow.getPrintData();
      var fileName = printData.name + '.json';
      printData.name = undefined;
      var content = JSON.stringify(printData.content);
      if (content == '{}') {
        Notify.error('错误', '请先选择模板，再点击下载');
        return;
      }
      var aLink = document.createElement('a');
      var blob = new Blob([content]);
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    },


    /**
         * 打印文件
         */
    print: function (printerName) {
      var _self = this;

      var printData = document.getElementById('mIframe0').contentWindow.getPrintData();
      printData.name = undefined;

      if (printData.content == null || printData.content.printItems == null || printData.content.printItems.length == 0) {
        Notify.error('错误', '打印模板无数据，不能打印。');
        return;
      }

      var content = JSON.stringify(printData.content);
      if (content == null || content == '' || content == '{}') {
        Notify.error('错误', '请先选择模板，再点击下载。');
        return;
      }

      PrintUtil.printPrintPages([printData.content], printerName);
    },
  },
};
</script>

<style scoped>
.m-row {
    margin-bottom: 15px;
}
</style>