<template>
  <div class="form-group">
    <label for="select-printer">{{ $t('lang.PrintWidget.selectPrinter') }}</label>
    <select
      id="select-printer"
      v-model="selectedPrinter"
      class="form-control"
      style="width: 15em"
      @change="selectedPrinterChanged"
    >
      <option value="" />
      <option
        v-for="printer in printers"
        :key="printer.name"
        :value="printer.name"
      >
        {{ printer.name }}
      </option>
    </select>
    <button
      v-if="showPrintButton"
      class="btn btn-default"
      @click="print()"
    >
      {{ $t('lang.PrintWidget.printing') }}
    </button>
  </div>
</template>

<script>

var PrintUtil = require('./PrintUtil.js').default;

export default {
  name: 'PrintWidget',

  components: {
  },
    
  props: {
    // 控件唯一的Id，用于localstorage存储打印机名称
    'printerLocalstorageId':
    {
      type: String,
      default: '',
    }, 
    // 是否显示打印按钮
    'showPrintButton':
    {
      type: Boolean,
      default: false,
    }, 
  },


  emits: ['changePrinter', 'print'],

  data: function () {
    return {
      'printers': [], // 系统上的打印机
      'selectedPrinter': '',   // 选择的打印机
    };
  },



  mounted: function () {
    var _self = this;
    _self.restoreSelectedPrinter();
    PrintUtil.getPrinters().then(successData => {
      if (successData != null && successData.length > 0) {
        successData.forEach(item => {
          _self.printers.push(item);
        });
      }
      _self.restoreSelectedPrinter();
    }, errorData => {
      console.log(errorData);
      _self.restoreSelectedPrinter();
    });
  },

  methods: {

    /**
     * 选择的打印机发生改变，保存打印机的设置
     */
    selectedPrinterChanged: function () {
      this.$emit('changePrinter');
      if (this.selectedPrinter != null) {
        localStorage.setItem(this.key, this.selectedPrinter);
      } else {
        localStorage.removeItem(this.key);
      }
    },

    /**
     * 恢复选择的打印机
     */
    restoreSelectedPrinter: function () {
      var selectedPrinterStr = localStorage.getItem(this.key);
      if (selectedPrinterStr != null && selectedPrinterStr.length > 0) {
        this.selectedPrinter = selectedPrinterStr;
      } else {
        this.selectedPrinter = '';
      }
    },

    /**
     * 打印文件
     */
    print: function () {
      var _self = this;
      this.$emit('print', _self.selectedPrinter);
    },

    /**
     * 获取选择打印机的名称
     */
    getSelectedPrinterName: function () {
      return this.selectedPrinter;
    },

    /**
     * 获取选择打印的类型
     */
    getSelectedPrinterType: function(){
      for(let index = 0; index < this.printers.length; index ++){
        if(this.printers[index].name === this.selectedPrinter){
          return this.printers[index].type;
        }
      }
      return null;
    },

  },
};
</script>

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