const windowStateKeeper =require( 'electron-window-state')
// Modules to control application life and create native browser window
const {app, BrowserWindow,ipcMain,Tray,Menu,dialog,globalShortcut } = require('electron')
const fs = require("fs")
const path = require("path")


var urlConfig = require("./url.config");
console.log(urlConfig)
var url =urlConfig .url
var type = urlConfig.type;
//获取mac地址的js
const getMac = require('getmac')

//网络请求
const request = require("request");

//登陆状态
let logined = false;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let tray;
let settings = {};;
let isWin = process.platform === 'win32';
let isOsx = process.platform === 'darwin';
global.account = {
    accountId: ''
    ,realName:''
}
//托盘菜单
var lable = '切换为'+(type=='1'?'正式版':'测试版');
let trayMenu = [
    {
        label: `打开`,
        click() {
            mainWindow.show();
        }
    },
    {
      label:lable,
        click(){
            var data = {"type":"1","url": "http://192.168.3.203:8087/"}
            if(type==1){
                var data = {"type":"2","url": "http://202.106.159.90/"}
            }

            fs.writeFile(path.join(app.getPath('userData'), '/url.config.json'),JSON.stringify(data),function(){
                app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
                app.quit();
            })

        }
    },
    {
        type: 'separator'
    },
    {
        label: '退出',
        selector: 'terminate:',
        click() {
            logined = false;
            mainWindow = null;
            tray.destroy();
            tray = null;
            app.quit();
        }
    }
];

const icon = __dirname+'/src/assets/images/applogo.png';
//Windows系统托盘
function createTray() {
    if (!isOsx) {
        // Always show the tray icon on windows
        settings.showOnTray = true;
    }

    if (settings.showOnTray) {
        if (tray ) {
            return;
        }

        let contextmenu = Menu.buildFromTemplate(trayMenu);
        // Init tray icon
                tray = new Tray(icon);

                tray.on('right-click', () => {
                    tray.popUpContextMenu();
                });

                tray.on('click', () => {
                   mainWindow.show();
                });
        tray.setContextMenu(contextmenu);
    } else {
        if (!tray) return;
        tray.destroy();
        tray = null;
    }
}

function updateTray() {

    trayMenu.splice(1,1)
    let contextmenu1 = Menu.buildFromTemplate(trayMenu);
    if (!tray) {
        tray = new Tray(icon);
    }
    tray.setContextMenu(contextmenu1);
}

//创建应用窗口方法
function createWindow () {
    var mainWindowState = windowStateKeeper({
        defaultWidth: 715,
        defaultHeight: 400,
    });
  // Create the browser window.
  mainWindow = new BrowserWindow({
      x: mainWindowState.x,
      y: mainWindowState.y,
      width: 730,
      height: 420,
      minWidth: 400,
      minHeight: 350,
  })
    mainWindow.setResizable(false);
  // 当窗口被关闭时判断用户是否登陆来决定是否退出应用
  mainWindow.on('close', function (e) {
      console.log(logined)
      if (!logined) {
          mainWindow = null;
          app.quit();
      } else {
          e.preventDefault();
          mainWindow.hide();
      }
  })

    ipcMain.on('print-getList', (event, deviceName) => {
        const printers = mainWindow.webContents.getPrinters();
        event.returnValue= printers;

    })

    ipcMain.on('print-start', (event, deviceName) => {
        console.info('deviceName>>>>'+deviceName)
        const printers = mainWindow.webContents.getPrinters();
        console.info(printers)
        printers.forEach(element => {
            if (element.name === deviceName) {
                console.log(element);
            }
            if (element.name === deviceName && element.status != 0) {
                console.info('print-error', deviceName + '打印机异常');
                event.returnValue = false;
            }
            event.returnValue = true;
        });
    })


    //登陆成功请求跳转
    ipcMain.on('asynchronous-message', (event, arg) => {
        logined = true;
        updateTray();
        mainWindow.setResizable(true);
        mainWindow.setSize(mainWindowState.width, mainWindowState.height);
        mainWindowState.manage(mainWindow);
        mainWindow.loadFile('src/index.html')
    })

    //注册账号请求跳转
    ipcMain.on('asynchronous-zhuce', (event, arg) => {
        mainWindow.setResizable(true);
        mainWindow.setSize(mainWindowState.width, mainWindowState.height);
        mainWindowState.manage(mainWindow);
        mainWindow.loadFile('registered.html')
    })

    //注册序列号
    ipcMain.on('asynchronous-reg', (event, arg) => {
        getMac.getMac(function(err, macAddress){
            request.post({url:'http://202.106.159.90/client/selectBySerialNumber', form: {serialNumber:arg,macAddress:macAddress}}, function(err,res,body){
                var  by= JSON.parse(body);
                if(by.status==1){
                    mainWindow.loadFile('login.html')
                }
                event.returnValue = by
            })
        })

    })

    //下载文件
    ipcMain.on('download', (event, arg) => {
        mainWindow.webContents.downloadURL(arg);
    })


    mainWindow.webContents.session.on('will-download', (e, item) => {
        const totalBytes = item.getTotalBytes();
        //监听下载过程，计算并设置进度条进度
        item.on('updated', () => {
            mainWindow.setProgressBar(item.getReceivedBytes() / totalBytes);
        });
        //监听下载结束事件
        item.on('done', (e, state) => {
            //如果窗口还在的话，去掉进度条
            if (!mainWindow.isDestroyed()) {
                mainWindow.setProgressBar(-1);
            }
            //下载被取消或中断了
            if (state === 'interrupted') {
                dialog.showErrorBox('下载失败', `文件 ${item.getFilename()} 因为某些原因被中断下载`);
            }
            //下载完成
            if (state === 'completed') {
                dialog.showMessageBox({type:'info',title :'消息',message :'下载完成'})
            }
        });
    });

    createTray()
}

app.on('ready', ()=>{
        //判断软件是否被激活
        // getMac.getMac(function(err, macAddress){
        //     console.info(macAddress)
        //     request.post({url:'http://202.106.159.90/client/selectByMacAddress', form: {macAddress:macAddress}}, function(err,res,body){
        //         if(err){
        //             console.info(err)
        //         }
        //         var  by= JSON.parse(body);
                createWindow()
        //         if(by.status==1){
        //             console.info(mainWindow.getSize())
                    mainWindow.loadFile('login.html')
        //         }else{
        //             //如没有进入激活窗口
        //             mainWindow.loadFile('serialNumber.html')
        //         }
        //     })
        // })
})

app.on('activate', function () {
    if (!mainWindow.isVisible()) {
        mainWindow.show();
    }
})
