<template>
  <div>
    <div class="row m-row">
      <div class="col-md-12">
        <div class="form-inline">
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.selectPrintTemplate") }}</label>
            <select v-model="selected" class="form-control" @change="setIframeData">
              <option />
              <option
                v-for="template in templates"
                :key="template.id"
                :value="template"
              >
                {{ template.name }}
              </option>
            </select>
            <button id="refreshBtn" class="btn btn-info" @click="refreshData">
              {{ $t("lang.CustomerBarCodeEditPanel.refresh") }}
            </button>
            <button
              v-if="selected"
              id="finishBtn"
              class="btn btn-primary"
              @click="saveData"
            >
              {{ $t("lang.CustomerBarCodeEditPanel.save") }}
            </button>
            <button
              v-if="selected"
              id="deleteBtn"
              class="btn btn-danger"
              @click="deleteData"
            >
              {{ $t("lang.CustomerBarCodeEditPanel.delete") }}
            </button>
            <button v-if="selected" class="btn btn-default" @click="upload()">
              {{ $t("lang.CustomerBarCodeEditPanel.upload") }}
            </button>
            <button v-if="selected" class="btn btn-default" @click="download()">
              {{ $t("lang.CustomerBarCodeEditPanel.download") }}
            </button>
            <button
              v-if="selected"
              class="btn btn-default"
              :disabled="selected.isDefault"
              @click="setDefault()"
            >
              {{ $t("lang.CustomerBarCodeEditPanel.setAsDefaultTemplate") }}
            </button>
            <button
              v-if="selected"
              class="btn btn-default"
              @click="generateInSubClient()"
            >
              {{ $t("lang.CustomerBarCodeEditPanel.distributedToSubsidiaries") }}
            </button>
            <button v-if="selected" class="btn btn-default" @click="openEdit()">
              {{ $t("lang.CustomerBarCodeEditPanel.edit") }}
            </button>
          </div>
          <PrintWidget
            :printer-localstorage-id="'#CustomerBarCodeEditPanelPrinter'"
            :show-print-button="true"
            @print="print($event)"
          />
        </div>
      </div>
    </div>

    <Modal v-model:show="modal" @ok="edit">
      <template #header>
        {{ $t("lang.CustomerBarCodeEditPanel.editTemplate") }}
      </template>
      <div>
        <div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.templateName") }}</label>
            <input v-model="templateName" autocomplete="off" type="text" class="form-control" />
          </div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.templateNumber") }}</label>
            <input v-model="templateNo" autocomplete="off" type="text" class="form-control" />
          </div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.templateType") }}</label>
            <select v-model="selectedTemplateType" class="form-control">
              <option />
              <option value="EAM\固定资产">固定资产</option>
              <option value="WMS\仓库物料">仓库物料</option>
              <option value="WMS\仓库货位">仓库货位</option>
              <option value="BASE\系统用户">系统用户</option>
              <option value="MES\生产物料">生产物料</option>
            </select>
          </div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.extraData") }}</label>
            <select v-model="selectedExtraData" class="form-control">
              <option />
              <option value="Single_Product_Management">单品管理</option>
              <option value="Batch_Management">批量管理</option>
            </select>
          </div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.sqlStatement") }}</label>
            <textarea v-model="sqlClause" type="text" rows="8" class="form-control" />
          </div>
        </div>
      </div>
    </Modal>
    <Modal v-model:show="modal2" :show-canel-button="false" :show-ok-button="false">
      <template #header>
        {{ $t("lang.CustomerBarCodeEditPanel.uploadTemplate") }}
      </template>
      <div>
        <div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.templateName") }}</label>
            <input v-model="uploadTemplateName" autocomplete="off" type="text" class="form-control" />
          </div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.templateNumber") }}</label>
            <input v-model="uploadTemplateNo" autocomplete="off" type="text" class="form-control" />
          </div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.templateType") }}</label>
            <select v-model="uploadTemplateType" class="form-control">
              <option />
              <option v-for="template in types" :key="template.id" :value="template.name">
                {{ template.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>{{ $t("lang.CustomerBarCodeEditPanel.templateContent") }}</label>
            <textarea
              v-model="uploadTemplateContent"
              class="form-control"
              rows="8"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <button type="button" class="btn btn-info" @click="cancelModal">
          {{ $t("lang.CustomerBarCodeEditPanel.cancel") }}
        </button>
        <button type="button" class="btn btn-primary" @click="saveUploadTemplate">
          {{ $t("lang.CustomerBarCodeEditPanel.determine") }}
        </button>
      </template>
    </Modal>
    <Loading v-if="loading" />
  </div>
</template>

<script>

import Common from '../common/Common.js';
import { PrintUtil } from 'pc-component-v3';
import { Notify, Uuid } from 'pc-component-v3';


export default {

  components: {
    
  },
  props: [],

  data: function () {
    return {
      selected: {},
      mPrintPage: {},
      templates: [],
      templateName: '',
      templateNo: '',
      uploadTemplateContent: '',
      uploadTemplateName: '',
      uploadTemplateNo: '',
      uploadTemplateType: '',
      types: [],
      sqlClause: '',
      selectedTemplateType: null, //选中的模板类型
      selectedExtraData: null, //选中的自定义设置
      loading: false,
      modal: false,
      modal2: false,
    };
  },

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

  mounted: function () {
    this.loadData();
    this.loadTypes();
  },

  methods: {
    /**
     * 调用iframe的init方法，绘制条码
     */
    setIframeData: function () {
      var _self = this;
      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('mIframe1')
          .contentWindow.init(null, this.selected.name, this.selected.content);

        var content = _self.selected.content;
        var printPage = JSON.parse(content);
        _self.sqlClause = printPage.sqlClause;
      } else {
        this.$nextTick(function () {
          var mIframe1 = document.getElementById('mIframe1');
          if (
            mIframe1 != null &&
            mIframe1.contentWindow != null &&
            mIframe1.contentWindow.init != null
          ) {
            mIframe1.contentWindow.init(null, null, null);
          }
        });
      }
    },

    // 隐藏模态框
    cancelModal: function () {
      this.modal2 = false;
    },

    /**
     * 读取PrinterTemplate文件夹下所有的json文件，获取文件名
     */
    loadTypes: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('printPageResource/getJsonFileName'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.types = data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 保存上传模板
    saveUploadTemplate: function () {
      var _self = this;
      if (_self.uploadTemplateName == null || _self.uploadTemplateName.trim() == '') {
        Notify.error('错误', '请填写模板名称');
        return;
      }
      if (_self.uploadTemplateNo == null || _self.uploadTemplateNo.trim() == '') {
        Notify.error('错误', '请填写模板编号');
        return;
      }
      if (_self.uploadTemplateType == null || _self.uploadTemplateType.trim() == '') {
        Notify.error('错误', '请填写模板类型');
        return;
      }
      if (
        _self.uploadTemplateContent == null ||
        _self.uploadTemplateContent.trim() == ''
      ) {
        Notify.error('错误', '请填写模板内容');
        return;
      }
      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('printPageResource/uploadCustomerPrintTemplate'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: {
          name: _self.uploadTemplateName,
          no: _self.uploadTemplateNo,
          type: _self.uploadTemplateType,
          content: _self.uploadTemplateContent,
        },
        success: function (data) {
          _self.loading=false;
          _self.refreshData();
          _self.modal2 = false;
          Notify.success('成功', '上传模板成功', true);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 上传
    upload: function () {
      this.uploadTemplateConent = '';
      this.modal2 = true;
    },

    /**
     * 刷新界面
     */
    refreshData: function () {
      this.mPrintPage = {};
      this.loadData();
    },

    /**
     * 加载自定义模板
     */
    loadData: function () {
      var _self = this;

      _self.mPrintPage = {};

      _self.templates.splice(0, _self.templates.length);

      var oldSelected = _self.selected;

      $.ajax({
        url: Common.getApiURL('printPageResource/loadCustomerTemplate'),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if(data.errorCode != 0) {
            Notify.error('提示', data.errorMessage, false);
          }
          _self.templates = data.datas;

          if (
            oldSelected != undefined &&
            oldSelected.name != undefined &&
            _self.templates != undefined &&
            _self.templates.length > 0
          ) {
            for (var i = 0; i < _self.templates.length; i++) {
              if (_self.templates[i].id == oldSelected.id) {
                _self.mPrintPage = JSON.parse(_self.templates[i].content);
                _self.selected = _self.templates[i];
              }
            }
          }

          _self.setIframeData();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 保存数据
     */
    saveData: function () {
      var _self = this;

      var printData = document.getElementById('mIframe1').contentWindow.getPrintData();

      var printPageJson = {
        templateId: this.selected.id,
        printPage: printData.content,
        isDefault: this.selected.isDefault,
        name: this.selected.name,
        no: this.selected.no,
        type: this.selectedTemplateType,
        extraData: this.selectedExtraData,
      };
      printPageJson.printPage.sqlClause = this.sqlClause;
      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('printPageResource/updateCustomerPrintTemplate'),
        dataType: 'json',
        type: 'post',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(printPageJson),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function () {
          _self.loading=false;
          Notify.success('成功', '保存成功', 1500);
          _self.refreshData();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 删除数据
     */
    deleteData: function () {
      var _self = this;
      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('printPageResource?templateId=' + _self.selected.id),
        type: 'post',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          this.mPrintPage = {};
          _self.loading=false;
          Notify.success('成功', '删除自定义模板成功', 1500);
          _self.loadData();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 下载模板json文件
     */
    download: function () {
      var _self = this;
      var printData = document.getElementById('mIframe1').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();
    },
    /**
     * 设置默认模板
     */
    setDefault: function () {
      this.selected.isDefault=true;
      this.saveData();
    },
    /**
     * 下发到子公司
     */
    generateInSubClient: function () {
      var _self = this;
      if (_self.selected.id == null || _self.selected.id == undefined) {
        Notify.error('错误', '请先选择要下发的模板', true);
        return;
      }
      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('printPageResource/generateInSubClient'),
        type: 'post',
        data: {
          customerPrintTemplateId: _self.selected.id,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading=false;
          Notify.success('成功', '模板下发到子公司成功', 1500);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    /**
     * 打开编辑模板模态框
     */
    openEdit: function () {
      var _self = this;
      if (_self.selected.id == null || _self.selected.id == undefined) {
        Notify.error('错误', '请先选择要编辑的模板', true);
        return;
      }
      _self.templateName = _self.selected.name;
      _self.templateNo = _self.selected.no;
      _self.selectedTemplateType = _self.selected.type;
      _self.selectedExtraData = _self.selected.extraData;
      var content = _self.selected.content;
      var printPage = JSON.parse(content);
      _self.sqlClause = printPage.sqlClause;
      this.modal = true;
    },
    /**
     * 编辑模板
     */
    edit: function () {
      this.selected.name = this.templateName;
      this.selected.no = this.templateNo;
      this.selected.sqlClause = this.sqlClause;
      this.saveData();
    },

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

      var printData = document.getElementById('mIframe1').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>
