/**
* 存货打印
*/

<template>
  <div
    class="container-fluid"
    style="height: calc(100vh);"
  >
    <Navbar
      title="打印"
      :is-go-back="false"
    />

    <PrintWidget
      ref="printWidget"
      :printer-localstorage-id="'#CommonPrinterPrinter'"
      @change-printer="changePrinter"
    />

    <button
      v-if="displayEpcWriter"
      class="btn btn-default"
      @click="$refs.printEpc.show()"
    >
      再次打印
    </button>

    <button
      v-if="display"
      class="btn btn-info"
      @click="printAgain"
    >
      再次打印
    </button>

    <PrintEpc ref="printEpc" />

    <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: {
    
  },
  data: function () {
    this.Common = Common;
    return {
      printApi: '',
      recordIds: [],
      display: false,//其他打印机
      displayEpcWriter: false,//发卡机
      printPages: [],//打印缓存数据
      loading: false,
    };
  },


  /**
     * 获取URL中的参数，接口的地址printApi，以及待打印数据的集合recordIds
     */
  mounted: function () {
    var _self = this;
    // 获取URL中的参数，接口的地址printApi，以及待打印数据的集合recordIds
    let printApi = Common.getRouteParam('printApi');
    let recordIdsStr = Common.getRouteParam('recordIds');
    if (printApi == null || printApi.trim() == '') {
      Notify.error('错误', 'URL中缺少参数printApi。');
      return;
    }

    _self.printApi = printApi;

    if (recordIdsStr == null || recordIdsStr.trim() == '') {
      Notify.error('错误', 'URL中缺少参数recordIds。');
      return;
    }

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

    var recordIdsTemp = recordIdsStr.split(',');
    if (recordIdsTemp == null || recordIdsTemp.length == 0) {
      Notify.error('错误', 'URL中参数recordIds错误，不是数组类型(举例:1,2,3)。');
      return;
    } else {
      recordIdsTemp.forEach(function (recordIdTemp) {
        _self.recordIds.push(Number(recordIdTemp));
      });
    }

    _self.windowCloseInterval = window.setTimeout(function () {
      window.close();
    }, 300000);

    $('body').click(function (e) {
      if (_self.windowCloseInterval != null) {
        window.clearTimeout(_self.windowCloseInterval);
        _self.windowCloseInterval = null;
      }
    });

    _self.windowCloseInterval = window.setTimeout(function () {
      _self.$nextTick(function () {
        _self.queryPrintPages();
      });
    }, 500);

    // 判断显示哪个按钮
    _self.getDisplayButton();
  },

  methods: {

    /**
         * 再次打印（针对除发卡机以外的其他打印机）
         * @author LeiGuoXian
         * @date 2020-08-03
         */
    printAgain: function () {
      var _self = this;
      if (_self.printPages.length == 0) {
        Notify.error('错误', '请先打印', false);
        return;
      }
      _self.print(_self.printPages);
    },

    /**
         * 当选择的是发卡机时显示再次打印按钮（白色）
         * 当选择的是其他打印设备时显示再次打印按钮（蓝色）
         * @author LeiGuoXian
         * @date 2020-08-03
         */
    changePrinter: function () {
      var _self = this;
      _self.getDisplayButton();
    },
    /**
         * 查询打印数据
         */
    queryPrintPages: function () {
      var _self = this;
      let selectedPrinter = _self.$refs.printWidget.getSelectedPrinterName();
      if (selectedPrinter == null || selectedPrinter.length == 0) {
        Notify.error('提示', '请先选择打印机。', false);
        return;
      }

      //清空
      _self.printPages.splice(0, _self.printPages.length);

      _self.loading=true;

      $.ajax({
        url: Common.getApiURL(_self.printApi),
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(_self.recordIds),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
          _self.loading=true;
        },
        success: function (datas) {
          _self.loading=false;
          _self.printPages = datas;
          _self.print(datas);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
         * 打印PrintPages
         */
    print: function (printPages) {
      var _self = this;
      let selectedPrinter = _self.$refs.printWidget.getSelectedPrinterName();
      if (selectedPrinter == 'EpcWriter' || selectedPrinter == 'JwEpcWriter') {
        _self.$refs.printEpc.printPrintPages(printPages);
      } else {
        var contents = [];
        printPages.forEach(function (item) {
          var printItem = {
            id: null,
            name: null,
            content: item,
          };
          console.log(printItem);
          if (printItem.content == null || printItem.content.printItems == null || printItem.content.printItems.length ==
                        0) {
            Notify.error('错误', '打印模板无数据，不能打印。');
            return;
          }
          var content = JSON.stringify(printItem.content);
          if (content == null || content == '' || content == '{}') {
            Notify.error('错误', '请先选择模板，再点击下载。');
            return;
          }
          contents.push(printItem.content);
        });
        PrintUtil.printPrintPages(contents, selectedPrinter);
      }
    },

    /**
         * 判断显示哪个按钮
         * @author LeiGuoXian
         * @date 2020-08-03
         */
    getDisplayButton: function () {
      var _self = this;
      if (_self.$refs.printWidget.getSelectedPrinterName() == null || _self.$refs.printWidget.getSelectedPrinterName().length == 0) {
        this.displayEpcWriter = false;
        this.display = false;
        return;
      }
      if (_self.$refs.printWidget.getSelectedPrinterName() == 'EpcWriter') {
        this.displayEpcWriter = true;
        this.display = false;
      } else {
        this.displayEpcWriter = false;
        this.display = true;
      }
    },
  },
};
</script>
