<template>
  <div class="print-list-container">
    <!-- 打印机选择弹窗 -->
    <div v-if="showPrinterModal" class="modal-overlay-print">
      <div class="modal-content" @click.stop>
        <div class="form-group-print">
            <label>打印机列表：</label>
            <Select style="padding-top: 20px;" class="form-control" @on-change="changePrinter" clearable>
              <!-- <Option value="">请选择打印机</option> -->
              <Option 
                v-for="printer in printerList" 
                :key="printer.id" 
                :value="printer.id"
              >
                {{ printer.name }}{{ printer.isDefault ? ' (默认)' : '' }}
              </option>
            </select>
          </div>
          <div class="printer-info" v-if="selectedPrinter !== ''">
            <p><strong>选中打印机：</strong>{{ selectedPrinter }}</p>
          </div>

        <div class="modal-footer">
          <Button type="default" class="btn btn-secondary" @click="closePrinterModal">取消</Button>
          <Button type="primary" class="btn btn-primary" @click="confirmPrinterSelection">确认选择</Button>
        </div>
        <div class="printer-info" v-if="message !== ''">
            <p><strong>错误信息：</strong>{{ message }} <a href="http://www.lodop.net/download.html" target="_blank">点击下载</a></p>
          </div>
      </div>
    </div>


    <!-- 隐藏的iframe用于加载printList.html -->
    <iframe 
      ref="printListFrame" 
      :src="IframeUrl" 
      style="width: 100%;display: none;"
      @load="onPrintListLoaded"
    ></iframe>
  </div>
</template>

<script>
const R3 = window.R3;
const { network ,urlSearchParams} = R3;
export default {
  name: 'PrintList',
  data() {
    return {
      // 打印机相关
      showPrinterModal: true,
      printerList: [],
      selectedPrinter: '',
      printerUtils: null,
      IframeUrl: '/iframe/PrintVue/printList.html',
      message:'',
      // 模版相关
      showTemplateModal: false,
      selectedTemplate: '',
      
      // 回调函数
      printerCallback: null,
      templateCallback: null
    }
  },
  mounted() {
    // this.selectedPrinter = document.querySelector('#DEFAULTPRINT input').value;
    this.initDefaultPrinter();
    this.initPrintUtils();
  },
  methods: {
    initDefaultPrinter(){
     // 获取模版默认打印机
      let { itemId} = this.$route.params;
      network.post('/p/cs/print/template/default/print',urlSearchParams({
        templateId:itemId
      })).then(res => {
        console.log(res.data,'========1212==')
        this.selectedPrinter = res.data.data;
      })
    },
    // 初始化打印工具
    initPrintUtils() {
      const iframe = this.$refs.printListFrame;

      if (iframe) {
        iframe.onload = () => {
          try {
            // 获取iframe中的PrintUtils
            this.printerUtils = iframe.contentWindow.PrintUtils;
             console.log(this.printerUtils, 'this.printerUtils============')
            if (this.printerUtils) {
               this.loadPrinterList();
            }
          } catch (error) {
            console.error('PrintUtils 加载失败:', error);
          }
        };
      }
    },
    changePrinter(val){
      if(val!== undefined){
        this.selectedPrinter = this.printerList[val].name;
        console.log(val,this.printerList[val].name, 'this.selectedPrinter============')
      }else{
        this.selectedPrinter = '';
      }
    },
    // printList.html 加载完成
    onPrintListLoaded() {
      this.initPrintUtils();
    },

    // 打开打印机选择弹窗
    openPrinterModal(callback) {
      this.printerCallback = callback;
      this.showPrinterModal = true;
      this.selectedPrinter = '';
      this.loadPrinterList();
    },

    // 关闭打印机选择弹窗
    closePrinterModal(type) {
      this.showPrinterModal = false;
      this.printerCallback = null;
      this.$emit('closeActionDialog', type);
    },

    // 加载打印机列表
    loadPrinterList() {
      if (this.printerUtils) {
        this.printerUtils.getSystemPrinters((result) => {
          console.log(result, 'result=========12121212=====')
          if (result.success) {
            this.printerList = result.data;
            console.log('打印机列表加载成功:', this.printerList);
          } else {
            this.message = result.message;
            console.error('打印机列表加载失败:', result.message);
            if (result.error === 'LODOP_NOT_INSTALLED') {
              this.message = 'LODOP未安装，请先安装LODOP打印控件';
              this.$message.error('LODOP未安装，请先安装LODOP打印控件');
              // this.printerUtils.showLodopInstallReminder();
            } else {
              this.message = '获取打印机列表失败';

              this.$message.error(`获取打印机列表失败: ${result.message}`);
            }
          }
        });
      } else {
        console.error('PrintUtils 未初始化');
        this.$message.error('打印工具未初始化，请刷新页面重试');
      }
    },

    // 确认打印机选择
    confirmPrinterSelection() {
      if (this.selectedPrinter !== '') {
        this.getTemplateSetList(this.selectedPrinter);
        setTimeout(() => {
          this.closePrinterModal();
        }, 300);
      }
    },

    // 获取打印机名称
    getPrinterName(printerId) {
      const printer = this.printerList.find(p => p.id === printerId);
      return printer ? printer.name : '';
    },

    // 打开模版选择弹窗
    openTemplateModal(callback) {
      this.templateCallback = callback;
      this.showTemplateModal = true;
      this.selectedTemplate = '';
    },

    // 关闭模版选择弹窗
    closeTemplateModal() {
      this.showTemplateModal = false;
      this.templateCallback = null;
    },

    // 确认模版选择
    confirmTemplateSelection() {
      if (this.selectedTemplate !== '') {
        const selectedTemplateInfo = this.templateList.find(t => t.id === this.selectedTemplate);
        if (this.templateCallback && typeof this.templateCallback === 'function') {
          this.templateCallback({
            success: true,
            data: selectedTemplateInfo
          });
        }
        this.closeTemplateModal();
      }
    },

    // 获取模版名称
    getTemplateName(templateId) {
      const template = this.templateList.find(t => t.id === templateId);
      return template ? template.name : '';
    },

    // 获取模版描述
    getTemplateDescription(templateId) {
      const template = this.templateList.find(t => t.id === templateId);
      return template ? template.description : '';
    },

    // 对外暴露的方法
    selectPrinter(callback) {
      this.openPrinterModal(callback);
    },

    selectTemplate(callback) {
      this.openTemplateModal(callback);
    },

    // 获取模版集列表
    getTemplateSetList(data) {
      // 查找DEFAULTPRINT id下面的input并赋值
      const panelForm = document.querySelector('.panelForm');
      const defaultPrintInput = document.querySelector('#DEFAULTPRINT input');
      if (defaultPrintInput) {
        // 设置input的值
        defaultPrintInput.value = data
        defaultPrintInput.dispatchEvent(new Event('input', { bubbles: true }));
        defaultPrintInput.dispatchEvent(new Event('change', { bubbles: true }));
      } 
      if(panelForm.__vue__){     
        console.log(panelForm.__vue__,'panelForm.__vue__============')   
        const formchangeData = Object.assign(panelForm.__vue__.formChangeData,{
          DEFAULTPRINT: data
        });
        const formChangeDataLabel = Object.assign(panelForm.__vue__.formChangeDataLabel,{
          DEFAULTPRINT: 'DEFAULTPRINT'
        });

        panelForm.__vue__.$parent.formChange(formchangeData,formChangeDataLabel, panelForm.__vue__.formChangeDataLabel);
        document.querySelector('#actionMODIFY').click();
      }
    }
  }
}
</script>

<style scoped>
.print-list-container {
  position: relative;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

/* .modal-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 500px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
} */

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.form-group-print {
  margin-bottom: 20px;
}

.printer-info,
.template-info {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #007bff;
}

.printer-info p,
.template-info p {
  margin: 5px 0;
  color: #555;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #eee;
  /* background-color: #f8f9fa; */
}
</style>
