/**
 * 打印监听函数
 */
const path=require('path');
const log = require("."+path.sep+"set_log").clog;
const electron = require('electron');
const screen = electron.screen;
const BrowserWindow = electron.BrowserWindow;
const ipcMain = electron.ipcMain;
const print_operation=require("."+path.sep+"print_operation");
const os = require('os');
const fs = require("fs");

let print_monitor={
  printerList_win:null,
  //创建打印列表窗口
  createPrinWindow:function(parent_win,apppath,respath,main,pdf_url){
      printerList_win = new BrowserWindow({
      width: (screen.getPrimaryDisplay().workAreaSize.height / 5) * 2,
      height: (screen.getPrimaryDisplay().workAreaSize.height / 5) * 3,
      fullscreenable: false,
      resizable: false,
      show: false,
      parent: parent_win,
      modal: true,
      title: "选择打印机",
        icon: respath +path.sep+"static"+path.sep+"images"+path.sep+"justar.ico",
      webPreferences: {
        nodeIntegration: true,
        nativeWindowOpen: true,
        //防止require引入失败
        contextIsolation:false
      }
    });
    //加载打印机列表数据监听
    this.loadPrinterList(printerList_win,pdf_url);

    printerList_win.setMenu(null);
    printerList_win.loadFile(apppath+path.sep+"src"+path.sep+"views"+path.sep+"list_printer.html");
    main.registerDevTool(printerList_win);

    //开启打印监听
    this.openPrinting(printerList_win);

    //开启关闭打印列表页面监听
    this.closePrintlistListener(printerList_win);

    //当前打印列表窗口被关闭前监听
    this.closePrintlistWindowListener(printerList_win);
  },
  //开启打印列表页面监听
  openPrinterMonitor:function(parent_win,apppath,respath,main){
    $this=this;
    //审处方调用
    ipcMain.on('list_printer', function (event, pdf_url) {
      $this.createPrinWindow(parent_win,apppath,respath,main,pdf_url)
    });
  },
  //加载打印页面的打印机列表数据监听
  loadPrinterList:function(win,pdf_url){
    win.once('ready-to-show', () => {
      // 加载完成后, 发送打印机列表数据到list_printer.html
      print_operation.getPrinterList().then(listPrinter => {
        return listPrinter
      }).then(listPrinter => {
          let data ={}
          let defaultPrinter;
          //获取打印缓存
          print_url = os.homedir()+path.sep+"AppData/Local/justarData/print/print.json"
          log.info("打印机缓存文件:"+print_url);
          if(fs.existsSync(print_url)){
              fs.readFile(print_url,'utf8',(err,data) =>{
                if(err){
                  log.error("获取打印机缓存失败");
                }else {
                    if(data.search("{") == -1){
                        data = {
                            listPrinter: listPrinter,
                            pdf_url: pdf_url
                        }
                    }else{
                        let printer_json = JSON.parse(data);
                        defaultPrinter = printer_json.printer_name;
                        data = {
                            listPrinter: listPrinter,
                            defaultPrinter: defaultPrinter,
                            pdf_url: pdf_url
                        }
                    }
                  win.show();
                  let json_data =  JSON.stringify(data);
                  log.info("打印机列表数据【"+json_data+"】")
                  win.webContents.send('printerData', json_data);
                }
              })
          }else{
            data = {
              listPrinter: listPrinter,
              pdf_url: pdf_url
            }
            win.show();
            let json_data = JSON.stringify(data)
            log.info("打印机列表数据【"+json_data+"】")
            win.webContents.send('printerData', json_data);
          }

      });
    })
  },

  //开启打印监听
  openPrinting:function(win){
    ipcMain.once('print', function (event, json_data) {
      let data = JSON.parse(json_data)
      log.info("打印开始，打印地址为:【"+json_data+"】")
      print_operation.printing(data.pdf_url, data.printer,win);
    });
  },
  closePrintlistListener:function (win){
    ipcMain.once('close_listPrinter', function (e) {
       win.close();
    });
  },
  //关闭打印列表窗口监听
  closePrintlistWindowListener:function(win) {
    win.on("close", (e) => {
      ipcMain.removeAllListeners('close_listPrinter');
    });
    win.on("close",(e) => {
      ipcMain.removeAllListeners('print');
    });

  }
}
module.exports = print_monitor;