<template>
  <div>
    <Navbar
      :title="windowName"
      :is-go-back="true"
    />
    <div
      class="row"
      style="margin-bottom: 15px;"
    >
      <div class="col-md-12">
        <div class="form-inline">
          <div
            v-if="allowPrint"
            class="form-group"
          >
            <label v-if="false" for="select-printer">选择打印机</label>
            <select
              v-if="false"
              id="select-printer"
              v-model="selectedPrinter"
              class="form-control"
              @change="selectedPrinterChanged"
            >
              <option value="" />
              <option
                v-for="printer in printers"
                :key="printer.name"
                :value="printer.name"
              >
                {{ printer.name }}
              </option>
            </select>
          </div>

          <button
            v-if="allowPrint"
            type="button"
            class="btn btn-primary"
            @click="saveAndPrint(allowPrint)"
          >
            保存并打印
          </button>

          <button
            v-if="!allowPrint"
            type="button"
            class="btn btn-primary"
            @click="saveAndPrint(allowPrint)"
          >
            保存
          </button>

          <button
            type="button"
            class="btn btn-danger"
            @click="clear"
          >
            清空界面
          </button>
        </div>
      </div>
    </div>

    <div :id="uuid" />
  </div>
</template>

<script>

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


import CurdWindowService from './CurdWindowService.js';

import CurdWindowResource from '../api/dic/CurdWindowResource.js';
// import DynamicJsLoader from '../base/common/DynamicJsLoader.js';



export default {

  components: {
  },
  data: function () {
    this.curdWindowDto = '';
    this.tabIndex = 0;
    this.hot = '';
    return {
      'windowNo': '',
      'windowName': '',
      'uuid': Uuid.createUUID(),
      'printers': [], // 系统上的打印机
      'selectedPrinter': '',   // 选择的打印机
      'allowPrint': '', // 是否进行打印
      'defaultPrintName': '', // 是否进行打印
    };
  },

  watch: {
    '$route': function (to, from) {
      try {
        this.hot.destroy();
      }
      catch (err) {
        console.error(err);
      }

      this.uuid = Uuid.createUUID();
      this.initView();
    },
  },

  mounted: function () {
    this.uuid = Uuid.createUUID();
    //动态加载handsontable JS 初始化handsontable控件
    // DynamicJsLoader.loadHandsonTable7_1_1(this.initView);
  },

  beforeUnmount: function () {
    // destory handsontable
    try {
      this.hot.destroy();
    }
    catch (err) {
      console.error(err);
    }
  },

  methods: {
    initView: function () {
      var _self = this;
      this.windowNo = this.$route.params.windowNo;
      CurdWindowService.initCurdWindow(this.windowNo).then(successData => {
        let colHeaders = successData.colHeaders;
        let columns = successData.columns;
        let tabDto = successData.tabDto;
        _self.windowName = successData.curdWindowDto.name;
        if (tabDto != null && tabDto.tabGridView != null && tabDto.tabGridView.tabButtons != null) {
          tabDto.tabGridView.tabButtons.forEach(item => {
            if (item.name == '打印' && item.userDefine1 != null) {
              _self.allowPrint = true;
              _self.defaultPrintName = item.userDefine1;
            }
          });
        }

        _self.initSpreadSheet(colHeaders, columns, tabDto);
      }, errorData => {
        Common.processException(errorData);
      });

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

      PrintUtil.getPrinters().then(successData => {
        if (successData != null && successData.length > 0) {
          successData.forEach(item => {
            _self.printers.push(item);
          });
        }

        var selectedPrinterStr = localStorage.getItem('#SelectedPrinter');
        if (selectedPrinterStr != null && selectedPrinterStr.length > 0) {
          _self.selectedPrinter = selectedPrinterStr;
        }else{
          _self.selectedPrinter = '';
        }
      }, errorData => {
        console.log(errorData);
      });
    },

    /**
         * 初始化WEB表格
         */
    initSpreadSheet: function (colHeaders, columns, tabDto) {
      var _self = this;
      // var data = [
      //     { id: -1, data: { organization: { id: -1, displayValue: ['111'], fieldType: 'Key' } } },
      //     { id: -1, data: { organization: { id: -1, displayValue: ['111'], fieldType: 'Key' } } },
      //     { id: -1, data: { organization: { id: -1, displayValue: ['111'], fieldType: 'Key' } } },
      //     { id: -1, data: { organization: { id: -1, displayValue: ['111'], fieldType: 'Key' } } },
      // ]
      _self.$nextTick(function () {
        var container = document.getElementById(_self.uuid);
        _self.hot = new Handsontable(container, {});
        var contextMenu = CurdWindowService.getContextMenu(_self.hot, tabDto);
        var settings = {
          // data: data,
          fixedRowsTop: 1,
          minRows: 100,
          rowHeaders: true,
          colHeaders: colHeaders,
          columns: columns,
          filters: true,
          dropdownMenu: true,
          copyPaste: {
            columnsLimit: 25,
            rowsLimit: 50,
            pasteMode: 'overwrite',
          },
          afterChange: function (changes, source) {
            CurdWindowService.afterChange(_self.hot, changes, source);
            _self.refresh();
          },
          beforeCopy: (data, coords) => {
            CurdWindowService.beforeCopy(_self.hot, tabDto, data, coords);
          },
          contextMenu: contextMenu,
          language: 'zh-CN',
          invalidCellClassName: 'handsontable-cell-error',
          licenseKey: 'non-commercial-and-evaluation',
        };
        _self.hot.updateSettings(settings);


      });
    },

    refresh: function () {
      let _self = this;
      if (window.webTableRefreshTimer != null) {
        clearTimeout(window.webTableRefreshTimer);
        window.webTableRefreshTimer = null;
      }

      window.webTableRefreshTimer = setTimeout(function () {
        _self.hot.render();
        window.webTabRefreshTimer = null;
      }, 100);
    },

    /**
         * 保存并打印
         */
    saveAndPrint: function (isPrint) {
      var _self = this;

      var tabSaveDatas = [];

      //_self.hot.validateCells();

      var rows = [];

      for (var i = 0; i < 100; i++) {
        var data = _self.hot.getSourceDataAtRow(i);
        if (data != null && data.id == -1) {
          rows.push(i);
          var persistenceData = {};
          persistenceData.id = data.id;
          persistenceData.data = data.data;
          persistenceData.changed = true;
          persistenceData.windowNo = _self.windowNo;
          persistenceData.tabIndex = 0;
          var tabSaveData = {
            persistenceData: persistenceData,
          };
                    
          tabSaveDatas.push(tabSaveData);

          // 增加数量的功能
          if(persistenceData.data != null && persistenceData.data.printQuantity != null
                        && persistenceData.data.printQuantity.displayValue != null
                        && persistenceData.data.printQuantity.displayValue[0] != null
                        && persistenceData.data.printQuantity.displayValue[0] != ''){
            var printQuantity = Number(persistenceData.data.printQuantity.displayValue[0]);
            if(printQuantity > 0){
              for(var repeatQuantity = 1; repeatQuantity < printQuantity; repeatQuantity ++){
                tabSaveDatas.push(tabSaveData);
              }
            }
          }
        }
      }

      if (tabSaveDatas == null || tabSaveDatas.length == 0) {
        Notify.error('错误', '无数据可以保存', 3000);
        return;
      }

      _self.hot.validateRows(rows, valid => {
        if (!valid) {
          Notify.error('错误', '红色的单元格的数据存在异常，请把数据填充完整。', 3000);
        } else {
          CurdWindowResource.saveOrUpdateDatas(tabSaveDatas).then(successData => {
            console.log(successData);

            if (isPrint) {
              var url = Common.getApiURL('PrintYMKD/print?recordIds={RecordIds}');
              url = url.replace('{RecordIds}', successData);
              PrintUtil.print(url, _self.defaultPrintName).then(successData => {
                Notify.success('成功', '打印成功', 1000);
              }, errorData => {
                Notify.error('错误', '打印失败', 3000);
              });
            } else {
              Notify.success('成功', '数据保存成功。', 1000);
            }


            //_self.clear();
          }, errorData => {
            console.log(errorData);
            Common.processException(errorData);
          });
        }
      });
    },

    /**
         * 清空界面
         */
    clear: function () {
      // var _self = this;
      // _self.hot.clear();
      // //var datas = [];
      // for (var i = 0; i < 100; i++) {
      //     // var data = _self.hot.getSourceDataAtRow(i);
      //     // if (data != null) {
      //     //     data.id = null;
      //     // }
      //     _self.hot.setDataAtRowProp(i, "id", null, "");
      // }
      // _self.hot.render();
      location.reload();
    },

    /**
         * 选择的打印机发生改变
         */
    selectedPrinterChanged: function () {
      if (this.selectedPrinter != null) {
        localStorage.setItem('#SelectedPrinter', this.selectedPrinter);
      } else {
        localStorage.removeItem('#SelectedPrinter');
      }
    },
  },
};
</script>


<style>
</style>