const { app, BrowserWindow, ipcMain, Menu, crashReporter, globalShortcut } = require('electron');
const path = require('path');
const fs = require('fs')
const PlatAPI = require('./modules/PlatAPI.js');
const trayApi = require('./modules/trayApi.js');
const DialogAPI = require('./modules/DialogAPI.js');
const { session } = require('electron');
const { fstat } = require('fs');
let commandLine = [];
for (let index = 0; index < commandLine.length; index++) {
	try {
		if (commandLine[index]["名称"] == undefined) {
			app.commandLine.appendSwitch(commandLine[index]["值"]);
		} else {
			app.commandLine.appendSwitch(commandLine[index]["名称"], commandLine[index]["值"]);
		}
	} catch (error) {

	}
}
let WindowDependent = [undefined];//窗口数组对象
let WindowDependentTitle = [""];//窗口数组对应标题
let WindowData = [48, 48, 48, 48, "邻几-体彩兑奖3.0", true, "", "${ camera }", false, undefined, "2", {}, false, ""];
if (WindowData[7] == "1") {
	const { systemPreferences } = require('electron')
	const microphone = systemPreferences.askForMediaAccess('microphone');
	const camera = systemPreferences.askForMediaAccess('camera');
}
app.commandLine.appendSwitch('disable-web-security');//同源策略关闭
function createWindow() {
	WindowDependentTitle[0] = WindowData[4];
	Menu.setApplicationMenu(null)
	const mainWindow = new BrowserWindow({
		width: WindowData[0],
		height: WindowData[1],
		minWidth: WindowData[2],
		minHeight: WindowData[3],
		frame: WindowData[8],
		transparent: WindowData[5],
		title: WindowData[4],
		show: false,
		webPreferences: {preload: path.join(__dirname, 'preload.js'),backgroundThrottling: false,nodeIntegration: true,webSecurity: false,contextIsolation: false}
	})
	/*
	mainWindow.setAlwaysOnTop(true);
	setTimeout(() => {
		mainWindow.setAlwaysOnTop(false);
	}, 3000)
	*/
	WindowDependent[0] = mainWindow;
	
	//${ DebugTypeEV1 } WindowDependent[0].webContents.openDevTools({ mode: 'detach' }) ${ DebugTypeEV2 }
	WindowDependent[0].DownloadObj = {};
	mainWindow.on('close', (event) => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try { let ifclose = 窗口是否可关闭('" + JSON.stringify(WindowsID) + "');if(ifclose!=false){electronAPI.destroy('" + WindowData[4] + "');窗口被关闭('" + JSON.stringify(WindowsID) + "')} } catch (error) {electronAPI.destroy('" + WindowData[4] + "');electronAPI.MainDestroyWindow();try {窗口被关闭('" + JSON.stringify(WindowsID) + "')} catch (error) {}}")
		if (WindowData[12] == false) {
			event.preventDefault()
		}
	})
	mainWindow.on('closed', () => {
		try {
			WindowData[9].close();
			if (WindowDependent.length >= 2) {
				for (let index = 0; index < WindowDependent.length; index++) {
					if (index >= 1) {
						if (WindowDependent[index] != -1) {
							WindowDependent[index].close()
						}
					}
				}
			}
		} catch (error) {

		}
		globalShortcut.unregisterAll();//注销所有快捷键
	})
	mainWindow.on('ready-to-show', () => {
		mainWindow.webContents.executeJavaScript("try { let ifshow = 是否显示主窗口();if(ifshow!=false){electronAPI.show();electronAPI.focus();} } catch (error) {electronAPI.show();electronAPI.focus();}")
	});
	mainWindow.on('unresponsive', () => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口被卡死('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('responsive', () => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口卡死被恢复('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('blur', () => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口失去焦点('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('focus', () => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口获得焦点('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('maximize', () => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口最大化('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('unmaximize', () => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口退出最大化('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('minimize', () => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口最小化('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('restore', () => {
		let WindowsID = { "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口最小化恢复('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('resize', (event) => {
		let Size = { "宽度": mainWindow.getSize()[0], "高度": mainWindow.getSize()[1], "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口尺寸被改变('" + JSON.stringify(Size) + "')} catch (error) {}")
	})
	mainWindow.on('move', (event) => {
		let XY = { "横向位置": mainWindow.getBounds().x, "纵向位置": mainWindow.getBounds().y, "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口位置被改变('" + JSON.stringify(XY) + "')} catch (error) {}")
	})
	mainWindow.on('moved', (event) => {
		let XY = { "横向位置": mainWindow.getBounds().x, "纵向位置": mainWindow.getBounds().y, "窗口标识": WindowData[4] }
		mainWindow.webContents.executeJavaScript("try {窗口位置被改变('" + JSON.stringify(XY) + "')} catch (error) {}")
	})
	//串口
	mainWindow.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
		mainWindow.webContents.session.on('serial-port-added', (event, port) => {
			console.log('serial-port-added FIRED WITH', port)
		})
		mainWindow.webContents.session.on('serial-port-removed', (event, port) => {
			console.log('serial-port-removed FIRED WITH', port)
		})

		event.preventDefault()
		if (portList && portList.length > 0) {
			callback(portList[0].portId)
		} else {
			callback('')
		}
	})
	mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
		if (permission === 'serial' && details.securityOrigin === 'file:///') {
			return true
		}
		return false
	})
	mainWindow.webContents.session.setDevicePermissionHandler((details) => {
		if (details.deviceType === 'serial' && details.origin === 'file://') {
			return true
		}
		return false
	})
	mainWindow.webContents.on('did-finish-load', () => {
		mainWindow.webContents.executeJavaScript("try {页面加载完毕()} catch (error) {window.didFinishLoadFOF = true;}")
		let WindowsID = { "窗口标识": WindowDependentTitle[WindowDependentTitle.length - 1], "调试编译": WindowData[10] };
		mainWindow.webContents.executeJavaScript("try {窗口创建完毕('" + JSON.stringify(WindowsID) + "')} catch (error) {}");
	});
	mainWindow.webContents.on('dom-ready', () => {
		mainWindow.webContents.executeJavaScript("try {DOM加载完毕()} catch (error) {window.domreadyFOF = true;}")
	});
	loadFileDebug(mainWindow,"index.html","false")
	
	if (process.platform == 'darwin') {
		 app.dock.hide();
	}
	if (process.platform == 'win32') {
		app.setAppUserModelId(WindowData[4])//应用APPID
	}
	//print-begin
	WindowData[9] = new BrowserWindow({
		title: 'print',
		show: false,
		width: 800,
		height: 600,
		webPreferences: {
			preload: path.join(__dirname, 'preload.js'),
			nodeIntegration: true,
			webSecurity: false,
			contextIsolation: false,
		}
	})
	WindowData[9].webContents.on('dom-ready', () => {
		WindowData[13] = WindowData[9].webContents.getURL()
	})
	//print-end
	session.defaultSession.cookies.onChanged((event, cookie, cause, removed) => {if (!removed) {saveCookiesToFile([cookie]);}}); 
}
function loadFileDebug(mainWindow, IndexHtmlUrl, ifDebug) {
	mainWindow.loadFile("./DataHtml/" + IndexHtmlUrl)
	let PathFile = path.join(__dirname, 'DebugUrl.json');
	try {
		fs.accessSync(PathFile, fs.constants.F_OK);
		fs.unlink(PathFile, (err) => {
			if (err) throw err;
		});
	} catch (err) {

	}
	setTimeout(() => {
		if (ifDebug == "true") {
			setInterval(() => {
				try {
					fs.accessSync(PathFile, fs.constants.F_OK);
					// 文件存在，读取文件内容
					fs.readFile(PathFile, 'utf8', (err, data) => {
						if (err) throw err;
						mainWindow.loadFile(data)
						fs.unlink(PathFile, (err) => {
							if (err) throw err;
						});
					});
				} catch (err) {

				}
			}, 300)
		}
	}, 1000)
}
async function saveCookiesToFile(cookies) {try {const cookiesJson = JSON.stringify(cookies, null, 2);await fs.writeFile(path.join(app.getPath('userData'), 'cookies.json'), cookiesJson);	} catch (error) {}} 
async function loadCookiesFromFile() {try {const cookiesData = await fs.readFile(path.join(app.getPath('userData'), 'cookies.json'), 'utf8');const cookies = JSON.parse(cookiesData);for (const cookie of cookies) {await session.defaultSession.cookies.set(cookie);}} catch (error) {if (error.code !== 'ENOENT') {console.error('Error loading cookies:', error);}}} 
function SelectWindowID(ifMaximized) {
	if (ifMaximized == "") {
		ifMaximized = WindowData[4]
	}
	let IndexID = -1;
	for (let index = 0; index < WindowDependentTitle.length; index++) {
		if (WindowDependentTitle[index] == ifMaximized) {
			IndexID = index
		}

	}
	return IndexID;
}
app.whenReady().then(() => {
	const gotTheLock = app.requestSingleInstanceLock();if (!gotTheLock) {app.quit();} else {createWindow();app.on('activate', function () {if (BrowserWindow.getAllWindows().length === 0) createWindow()});app.on('second-instance', (event, commandLine, workingDirectory) => {if (WindowDependent[0]) {if (WindowDependent[0].isMinimized()) WindowDependent[0].restore();WindowDependent[0].focus();}});}
})
app.on('window-all-closed', function () {
	app.quit()
	return;
	if (process.platform !== 'darwin') {
		app.quit()//如果用户不是在 macOS(darwin) 上运行程序，则调用 app.quit()。 
		//在mac中不调用这个方法会让程序在菜单栏中保活~
	}
})
app.on('will-quit', () => {
	// 注销所有快捷键
	globalShortcut.unregisterAll()
})
ipcMain.handle("globalShortcut", (ev, Key = "") => {
	const ret = globalShortcut.register(Key, () => {
		WindowDependent[0].webContents.executeJavaScript("try {全局触发快捷键('" + Key + "')} catch (error) {}")
	});
});
ipcMain.handle("openDebug", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].webContents.openDevTools()
	}
});
ipcMain.handle("closeDevTools", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].webContents.closeDevTools()
	}
});
ipcMain.handle("openDebug1", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].webContents.openDevTools({ mode: 'left' })
	}

})
ipcMain.handle("openDebug2", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].webContents.openDevTools({ mode: 'right' })
	}
});
ipcMain.handle("openDebug4", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].webContents.openDevTools({ mode: 'bottom' })
	}

});
ipcMain.handle("openDebug3", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].webContents.openDevTools({ mode: 'detach' })
	}
});
ipcMain.handle("doMinWindow", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].minimize()
	}
});
ipcMain.handle("domaxWindow", (ev, ifMaximized = false, WindwosID = "") => {
	let WindwosIDIndex = SelectWindowID(WindwosID)
	if (WindwosIDIndex >= 0) {
		if (ifMaximized == true) {
			WindowDependent[WindwosIDIndex].maximize();
		} else {
			if (WindowDependent[WindwosIDIndex].isMaximized()) {
				WindowDependent[WindwosIDIndex].unmaximize();
			} else {
				WindowDependent[WindwosIDIndex].maximize();
			}
		}
	}
});
ipcMain.handle("CloseWindowYes", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].close()
		if (SelectWindowID(WindwosID) >= 1) {
			let IndexWindowsID = SelectWindowID(WindwosID);
			WindowDependent[IndexWindowsID] = -1;
			WindowDependentTitle[WindowDependentTitle] = "-1FOFStudio";
		}
	}
});
ipcMain.handle("DestroyWindowID", (ev, IndexWindowsID, WindowDependentTitleLength) => {
	//主动非主窗口销毁窗口标识，内部使用，在窗口是否可关闭代码处触发
	try {
		WindowDependent[IndexWindowsID] = -1;
		WindowDependentTitle[WindowDependentTitleLength] = "-1FOFStudio";
	} catch (error) {

	}
});
ipcMain.handle("MainDestroyWindow", (ev) => {
	//主动销毁所有窗口，当主窗口允许关闭时使用，内部使用，在窗口是否可关闭代码处触发
	try {
		globalShortcut.unregisterAll();//注销所有快捷键
		if (WindowDependent.length >= 2) {
			for (let index = 0; index < WindowDependent.length; index++) {
				if (index >= 1) {
					if (WindowDependent[index] != -1) {
						WindowDependent[index].close()
					}
				}
			}
		}
	} catch (error) {

	}
});
ipcMain.handle("doCloseWindow", (ev, WindwosID = "") => {
	let IndexWindowsID = SelectWindowID(WindwosID)
	if (IndexWindowsID >= 0) {
		if (IndexWindowsID >= 0) {
			WindowDependent[IndexWindowsID].destroy()
			WindowDependent[IndexWindowsID] = -1;
			WindowDependentTitle[IndexWindowsID] = "-1FOFStudio";
		}
	}
});
ipcMain.handle("destroy", (ev, WindwosID = "") => {
	let IndexWindowsID = SelectWindowID(WindwosID);
	if (IndexWindowsID >= 0) {
		if (IndexWindowsID == 0) {
			for (let index = 0; index < WindowDependent.length; index++) {
				if (WindowDependent[WindowDependent.length - index - 1] != -1) {
					try {
						//有一些销毁的窗口就不需要再销毁了，进行异常的俘获
						if (WindowDependent.length - index - 1 != IndexWindowsID) {
							//销毁所有非主窗口
							WindowDependent[WindowDependent.length - index - 1].destroy()
							WindowDependent[WindowDependent.length - index - 1] = -1;
							WindowDependentTitle[WindowDependent.length - index - 1] = "-1FOFStudio";
						}

					} catch (error) {

					}
				}
			}
			WindowData[12] = true;
			WindowDependent[IndexWindowsID].destroy()
			WindowDependent[IndexWindowsID] = -1;
			WindowDependentTitle[IndexWindowsID] = "-1FOFStudio";
			try {
				WindowData[9].close();
			} catch (error) {

			}
		} else {
			WindowDependent[IndexWindowsID].destroy()
			WindowDependent[IndexWindowsID] = -1;
			WindowDependentTitle[IndexWindowsID] = "-1FOFStudio";
		}
	}
});
ipcMain.handle("focus", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].focus()
	}
});
ipcMain.handle("isFocused", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isFocused();
	}
	return undefined;
});
ipcMain.handle("isVisible", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isVisible();
	}
	return undefined;
});
ipcMain.handle("isMaximized", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isMaximized();
	}
	return undefined;
});
ipcMain.handle("isMinimized", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isMinimized();
	}
	return undefined;
});
ipcMain.handle("isFullScreen", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isFullScreen();
	}
	return undefined;
});
ipcMain.handle("isResizable", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isResizable();
	}
	return undefined;
});
ipcMain.handle("isMovable", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isMovable();
	}
	return undefined;

});
ipcMain.handle("isMinimizable", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isMinimizable();
	}
	return undefined;
});
ipcMain.handle("isMaximizable", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		return WindowDependent[SelectWindowID(WindwosID)].isMaximizable();
	}
	return undefined;
});
ipcMain.handle("show", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].show()
	}

});
ipcMain.handle("hide", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].hide()
	}

});
ipcMain.handle("maximize", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].maximize()
	}

});
ipcMain.handle("unmaximize", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].unmaximize()
	}

});
ipcMain.handle("minimize", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].minimize()
	}

});
ipcMain.handle("restore", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].restore()
	}

});
ipcMain.handle("setFullScreen", (ev, ifsetFullScreen, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].setFullScreen(ifsetFullScreen)
	}

});
ipcMain.handle("setResizable", (ev, ifsetResizable, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].setResizable(ifsetResizable)
	}

});
ipcMain.handle("setMovable", (ev, ifsetMovable, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].setMovable(ifsetMovable)
	}

});
ipcMain.handle("setMinimizable", (ev, ifsetMinimizable, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].setMinimizable(ifsetMinimizable)
	}

});
ipcMain.handle("setMaximizable", (ev, ifsetMaximizable, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].setMaximizable(ifsetMaximizable)
	}

});
ipcMain.handle("setAlwaysOnTop", (ev, ifsetAlwaysOnTop, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].setAlwaysOnTop(ifsetAlwaysOnTop)
	}

});
ipcMain.handle("setSkipTaskbar", (ev, ifsetSkipTaskbar, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		if (ifsetSkipTaskbar == false) {
			WindowDependent[SelectWindowID(WindwosID)].setSkipTaskbar(true)
		} else {
			WindowDependent[SelectWindowID(WindwosID)].setSkipTaskbar(false)
		}
	}
});
ipcMain.handle("loadURL", (ev, url, WindwosID = "") => {

	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].loadURL(url)
	}
});
ipcMain.handle("loadFile", (ev, url, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].loadFile(url)
	}
});
ipcMain.handle("setBounds", (ev, setBoundsData, WindwosID = "") => {
	try {
		if (SelectWindowID(WindwosID) >= 0) {
			WindowDependent[SelectWindowID(WindwosID)].setBounds({ x: setBoundsData["横向位置"], y: setBoundsData["纵向位置"], width: setBoundsData["宽度"], height: setBoundsData["高度"] })
		}
	} catch (err) {

	}
});
ipcMain.handle("getBounds", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		let data = WindowDependent[SelectWindowID(WindwosID)].getBounds();
		let returndata = { "横向位置": data["x"], "纵向位置": data["y"], "宽度": data["width"], "高度": data["height"] }
		return returndata;
	}
	return undefined;

});
ipcMain.handle("setWidthHeight", (ev, WidthHeight, WindwosID = "") => {
	try {

		if (SelectWindowID(WindwosID) >= 0) {
			let data = WindowDependent[SelectWindowID(WindwosID)].getBounds();
			let returndata = { "横向位置": data["x"], "纵向位置": data["y"], "宽度": data["width"], "高度": data["height"] }
			WindowDependent[SelectWindowID(WindwosID)].setBounds({ x: returndata["横向位置"], y: returndata["纵向位置"], width: WidthHeight["宽度"], height: WidthHeight["高度"] })
		}
	} catch (err) {

	}
});
ipcMain.handle("getWidthHeight", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		let data = WindowDependent[SelectWindowID(WindwosID)].getBounds();
		let returndata = { "宽度": data["width"], "高度": data["height"] }
		return returndata;
	}
	return undefined;

});
ipcMain.handle("center", (ev, WindwosID = "") => {
	if (SelectWindowID(WindwosID) >= 0) {
		WindowDependent[SelectWindowID(WindwosID)].center()
	}
});
ipcMain.handle("startLog", (ev, url) => {
	try {
		crashReporter.start({ submitURL: url })
	} catch (err) {

	}
});
ipcMain.handle("powerSaveBlocker", () => PlatAPI.powerSaveBlocker());
ipcMain.handle("Notification", (ev, data) => PlatAPI.Notification(data));
ipcMain.handle("showOpenDialogSync", (ev, data) => {
	return DialogAPI.showOpenDialogSync(data)
});
ipcMain.handle("showOpenDialogSyncFile", (ev, data) => {
	return DialogAPI.showOpenDialogSyncFile(data)
});
ipcMain.handle("tray", (ev, data, funEv1, funEv2) => {
	trayApi.tray(data, funEv1, funEv2, WindowDependent[0])
});
ipcMain.handle("destroyTray", () => {
	trayApi.destroyTray();
});
ipcMain.handle("setCookie", (ev, url_, name_, value_) => {
	//设置COOKIE
	// Set a cookie with the given cookie data;
	// may overwrite equivalent cookies if they exist.
	const cookie = { url: url_, name: name_, value: value_ }
	session.defaultSession.cookies.set(cookie)
		.then(() => {
			// success
		}, (error) => {
			//console.error(error)
		})
});
ipcMain.handle("removeCookie", (ev, url_, name_) => {
	//删除COOKIE
	session.defaultSession.cookies.remove(url_, name_, (error) => {
		//判断是否error
	})
});
ipcMain.handle("initDownload", (ev, path, IfOpen, WindwosID = "") => {
	const { initDownload } = require('./electronClass/download.js');
	initDownload(WindowDependent[SelectWindowID(WindwosID)], path, IfOpen);
});
ipcMain.handle("DownloadPause", (ev, FileID, WindwosID = "") => {
	WindowDependent[SelectWindowID(WindwosID)].DownloadObj[FileID] = {
		"pause": true,
		"状态": "暂停下载"
	}
});
ipcMain.handle("DownloadResume", (ev, FileID, WindwosID = "") => {
	WindowDependent[SelectWindowID(WindwosID)].DownloadObj[FileID] = {
		"resume": true,
		"状态": "正在下载"
	}
});
ipcMain.handle("DownloadCancel", (ev, FileID, WindwosID = "") => {
	WindowDependent[SelectWindowID(WindwosID)].DownloadObj[FileID] = {
		"cancel": true,
		"状态": "停止下载"
	}
});
ipcMain.handle("DownloadType", (ev, FileID, WindwosID = "") => {
	return WindowDependent[SelectWindowID(WindwosID)].DownloadObj[FileID];
});
ipcMain.handle("openAtLogin", (ev, true_) => app.setLoginItemSettings({ openAtLogin: true_ }));
ipcMain.handle("DebugOfCom", (ev) => {
	return WindowData[10];
});
//print-begin
ipcMain.handle('getPrintAll', (ev, Fun_) => {
	const printers = WindowData[9].webContents.getPrinters();
	return printers
})
ipcMain.handle('SetPrintFile', (ev, File) => {
	WindowData[9].loadFile("./DataHtml/" + File)
})
ipcMain.handle('SetPrintHttp', (ev, http) => {
	WindowData[9].loadURL(http)
})
const exec = require('child_process').exec
ipcMain.handle('startPrintSend', (event, Data) => {
	if (Data["静默打印"] == undefined) {
		Data["静默打印"] = false
	}
	if (Data["背景打印"] == undefined) {
		Data["背景打印"] = true
	}
	if (Data["打印机名称"] == undefined) {
		Data["打印机名称"] = ""
	}
	if (Data["彩色打印"] == undefined) {
		Data["彩色打印"] = true
	}
	if (Data["是否Windows原生打印"] == undefined) {
		Data["是否Windows原生打印"] = false
	}
	if (Data["保存PDF"] == undefined) {
		Data["保存PDF"] = false
	}
	if (Data["保存PDF"] == true) {
		WindowData[9].webContents.printToPDF({
			printBackground: true
		}).then(data => {
			fs.writeFile(Data["保存路径"], data, error => {
				if (error) throw error;
				if (Data["打印标识"] != undefined) {
					WindowData[11][Data["打印标识"]] = "打印成功"
				}
			});
		}).catch(error => {
			if (Data["打印标识"] != undefined) {
				WindowData[11][Data["打印标识"]] = "打印失败"
			}
		});
		return;
	}
	if (process.platform != 'win32' || Data["是否Windows原生打印"] == true) {
		let printObj = {
			silent: Data["静默打印"],
			printBackground: Data["背景打印"],
			deviceName: Data["打印机名称"],
			color: Data["彩色打印"],
			margins: {
				marginType: "custom",
				top: 0,
				right: 0,
				bottom: 0,
				left: 0
			},
		}
		if (Data["纸张类型"] != undefined) {
			printObj["pageSize"] = Data["纸张类型"]
		}
		if (Data["打印页数"] != undefined) {
			printObj["pageRanges"] = Data["打印页数"]
		}
		if (Data["横向打印"] != undefined) {
			printObj["landscape"] = Data["横向打印"]
		}
		if (Data["缩放比例"] != undefined) {
			printObj["scaleFactor"] = Data["缩放比例"]
		}
		if (Data["合并页数"] != undefined) {
			printObj["pagesPerSheet"] = Data["合并页数"]
		}
		if (Data["打印份数"] != undefined) {
			printObj["copies"] = Data["打印份数"]
		}
		if (Data["打印DPI"] != undefined) {
			printObj["dpi"] = Data["打印DPI"]
		}
		if (Data["打印边距"] != undefined) {
			printObj["margins"] = { marginType: "custom", top: Data["打印边距"]["顶边"], right: Data["打印边距"]["右边"], bottom: Data["打印边距"]["底边"], left: Data["打印边距"]["左边"] }
			if (Data["打印边距"]["类型"] != "") {
				printObj["margins"]["marginType"] = Data["打印边距"]["类型"];
			}
		}
		if (Data["自定义打印"] != undefined) {
			if (Data["自定义打印"]["静默打印"] == undefined) {
				Data["自定义打印"]["静默打印"] = false
			}
			if (Data["自定义打印"]["背景打印"] == undefined) {
				Data["自定义打印"]["背景打印"] = true
			}
			if (Data["自定义打印"]["打印机名称"] == undefined) {
				Data["自定义打印"]["打印机名称"] = ""
			}
			if (Data["自定义打印"]["彩色打印"] == undefined) {
				Data["自定义打印"]["彩色打印"] = true
			}
			let printObj_ = {
				silent: Data["自定义打印"]["静默打印"],
				printBackground: Data["自定义打印"]["背景打印"],
				deviceName: Data["自定义打印"]["打印机名称"],
				color: Data["自定义打印"]["彩色打印"],
				margins: {
					marginType: "custom",
					top: 0,
					right: 0,
					bottom: 0,
					left: 0
				},
			}
			if (Data["自定义打印"]["纸张类型"] != undefined) {
				printObj_["pageSize"] = Data["自定义打印"]["纸张类型"]
			}
			if (Data["自定义打印"]["打印页数"] != undefined) {
				printObj_["pageRanges"] = Data["自定义打印"]["打印页数"]
			}
			if (Data["自定义打印"]["横向打印"] != undefined) {
				printObj_["landscape"] = Data["自定义打印"]["横向打印"]
			}
			if (Data["自定义打印"]["缩放比例"] != undefined) {
				printObj_["scaleFactor"] = Data["自定义打印"]["缩放比例"]
			}
			if (Data["自定义打印"]["合并页数"] != undefined) {
				printObj_["pagesPerSheet"] = Data["自定义打印"]["合并页数"]
			}
			if (Data["自定义打印"]["打印份数"] != undefined) {
				printObj_["copies"] = Data["自定义打印"]["打印份数"]
			}
			if (Data["自定义打印"]["打印DPI"] != undefined) {
				printObj_["dpi"] = Data["自定义打印"]["打印DPI"]
			}
			if (Data["自定义打印"]["打印边距"] != undefined) {
				printObj_["margins"] = { marginType: "custom", top: Data["自定义打印"]["打印边距"]["顶边"], right: Data["自定义打印"]["打印边距"]["右边"], bottom: Data["自定义打印"]["打印边距"]["底边"], left: Data["自定义打印"]["打印边距"]["左边"] }
				if (Data["自定义打印"]["打印边距"]["类型"] != "") {
					printObj_["margins"]["marginType"] = Data["自定义打印"]["打印边距"]["类型"];
				}
			}
			WindowData[9].webContents.print(printObj_, (success, failureReason) => {
				if (success == true) {
					if (Data["打印标识"] != undefined) {
						WindowData[11][Data["打印标识"]] = "打印成功"
					} else {
						if (Data["自定义打印"]["打印标识"] != undefined) {
							WindowData[11][Data["自定义打印"]["打印标识"]] = "打印成功"
						}
					}
				} else {
					if (Data["打印标识"] != undefined) {
						WindowData[11][Data["打印标识"]] = "打印失败"
					} else {
						if (Data["自定义打印"]["打印标识"] != undefined) {
							WindowData[11][Data["自定义打印"]["打印标识"]] = "打印失败"
						}
					}
				}
			});
		} else {
			WindowData[9].webContents.print(printObj, (success, failureReason) => {
				if (success == true) {
					if (Data["打印标识"] != undefined) {
						WindowData[11][Data["打印标识"]] = "打印成功"
					}
				} else {
					if (Data["打印标识"] != undefined) {
						WindowData[11][Data["打印标识"]] = "打印失败"
					}
				}
			});
		}
	} else {
		WindowData[9].webContents.printToPDF({
			printBackground: true
		}).then(data => {
			fs.writeFile(path.join(__dirname, 'packpdf.pdf'), data, error => {
				if (error) throw error;
				let printINI = ` -print-settings "参数成员"`
				let printCs = "";
				if (Data["打印页数w"] != undefined) {
					if (Data["打印页数w"]["起始页"] != undefined && Data["打印页数w"]["结束页"] != undefined) {
						printCs = printCs + Data["打印页数w"]["起始页"] + "-" + Data["打印页数w"]["结束页"]
					}
				}
				if (Data["打印偶数页w"] != undefined) {
					if (printCs != "") {
						printCs = printCs + ",even"
					} else {
						printCs = printCs + "even"
					}
				}
				if (Data["打印奇数页w"] != undefined) {
					if (printCs != "") {
						printCs = printCs + ",odd"
					} else {
						printCs = printCs + "odd"
					}
				}
				if (Data["不缩放页面w"] != undefined) {
					if (printCs != "") {
						printCs = printCs + ",noscale"
					} else {
						printCs = printCs + "noscale"
					}
				}
				if (Data["缩放页面w"] != undefined) {
					if (printCs != "") {
						printCs = printCs + ",shrink"
					} else {
						printCs = printCs + "shrink"
					}
				}
				printINI = printINI.replace("参数成员", printCs)
				let cmdCode = path.join(__dirname, 'electronClass/SumatraPDF.exe') + printINI + ` -print-to "` + Data["打印机名称"] + `"  "` + path.join(__dirname, 'packpdf.pdf') + `" `
				let cwd = {
					cwd: ""
				}
				if (Data["自定义打印"] != undefined) {
					if (isObject(Data["自定义打印"]) == false) {
						cmdCode = path.join(__dirname, 'electronClass/SumatraPDF.exe') + Data["自定义打印"] + ` -print-to "` + Data["打印机名称"] + `"  "` + path.join(__dirname, 'packpdf.pdf') + `" `
					}
				}
				let workerProcess = exec(cmdCode, cwd)
				workerProcess.stdout.on('data', function (data) {
					if (Data["打印标识"] != undefined) {
						WindowData[11][Data["打印标识"]] = "打印成功"
					}
				})
				workerProcess.stderr.on('data', function (data) {
					if (Data["打印标识"] != undefined) {
						WindowData[11][Data["打印标识"]] = "打印失败"
					}
				})
				workerProcess.on('close', function (code) {
					if (Data["打印标识"] != undefined) {
						if (WindowData[11][Data["打印标识"]] != "打印成功" && WindowData[11][Data["打印标识"]] != "打印失败") {
							WindowData[11][Data["打印标识"]] = "打印成功"
						}
					}
				})
			});
		}).catch(error => {
			if (Data["打印标识"] != undefined) {
				WindowData[11][Data["打印标识"]] = "打印失败"
			}
		});
	}
})
ipcMain.handle('GetPrintType', (ev, DataID) => {
	let Data = WindowData[11][DataID];
	if (Data) {
		delete WindowData[11][DataID];
		return Data;
	} else {
		return "NO"
	}
})
ipcMain.handle('GetUrlType', (ev) => {
	if (WindowData[13]) {
		if (WindowData[13] != "") {
			let RetData = WindowData[13];
			WindowData[13] = "";
			return RetData;
		}
	}
	return "NO";
})
ipcMain.handle('Screenshot', (ev, DataObj) => {
	const { screen } = require('electron');
	const { size } = screen.getPrimaryDisplay()
	let sizeObj = {}

	try {
		sizeObj = JSON.parse(DataObj)
		sizeObj["maxWidth"] = sizeObj["最大宽度"];
		sizeObj["minWidth"] = sizeObj["最小宽度"];
		sizeObj["minHeight"] = sizeObj["最小高度"];
		sizeObj["maxHeight"] = sizeObj["最大高度"];
	} catch (error) {
		sizeObj = {
			minWidth: size.width,
			maxWidth: size.width,
			minHeight: size.height,
			maxHeight: size.height
		}
	}
	WindowDependent[0].webContents.send('SET_SOURCE', JSON.stringify(sizeObj))
})
//print-end
ipcMain.handle("openWindows", (ev, WindowsData) => {
	if (WindowsData["窗口标识"]) {
		if (WindowsData["窗口标识"] == "") {
			return;
		}
	}
	for (let index = 0; index < WindowDependentTitle.length; index++) {
		if (WindowDependentTitle[index] == WindowsData["窗口标识"]) {
			return;
		}
	}
	try {
		if (WindowsData["可视状态"] == undefined) {
			WindowsData["可视状态"] = true;
		}
	} catch (error) {
		WindowsData["可视状态"] = true;
	}
	const mainWindow = new BrowserWindow({
		width: WindowsData["宽度"],
		height: WindowsData["高度"],
		title: WindowsData["标题"],
		show: WindowsData["可视状态"],
		minWidth: WindowsData["最小宽度"],
		minHeight: WindowsData["最小高度"],
		frame: WindowsData["有边框状态"],
		webPreferences: {preload: path.join(__dirname, 'preload.js'),backgroundThrottling: false,nodeIntegration: true,webSecurity: false,contextIsolation: false}
	})
	let WindowDependentLength = WindowDependent.length
	let WindowDependentTitleLength = WindowDependentTitle.length
	WindowDependent[WindowDependentLength] = mainWindow;
	WindowDependentTitle[WindowDependentTitleLength] = WindowsData["窗口标识"]
	
	//${ DebugTypeEV1 } mainWindow.webContents.openDevTools({ mode: 'detach' }) ${ DebugTypeEV2 }
	mainWindow.on('close', (event) => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		let IndexWindowsID = SelectWindowID(WindowsData["窗口标识"]);
		mainWindow.webContents.executeJavaScript("try { let ifclose = 窗口是否可关闭('" + JSON.stringify(WindowsID) + "');if(ifclose!=false){electronAPI.destroy('" + WindowsData["窗口标识"] + "');electronAPI.DestroyWindowID(" + IndexWindowsID + "," + WindowDependentTitleLength + ");窗口被关闭('" + JSON.stringify(WindowsID) + "')} } catch (error) { electronAPI.destroy('" + WindowsData["窗口标识"] + "');electronAPI.DestroyWindowID(" + IndexWindowsID + "," + WindowDependentTitleLength + ");try {窗口被关闭('" + JSON.stringify(WindowsID) + "')} catch (error) {} }")
		event.preventDefault()
	})
	mainWindow.on('unresponsive', () => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口被卡死('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('responsive', () => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口卡死被恢复('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('blur', () => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口失去焦点('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('focus', () => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口获得焦点('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('maximize', () => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口最大化('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('unmaximize', () => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口退出最大化('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('minimize', () => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口最小化('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('restore', () => {
		let WindowsID = { "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口最小化恢复('" + JSON.stringify(WindowsID) + "')} catch (error) {}")
	})
	mainWindow.on('resize', (event) => {
		let Size = { "宽度": mainWindow.getSize()[0], "高度": mainWindow.getSize()[1], "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口尺寸被改变('" + JSON.stringify(Size) + "')} catch (error) {}")
	})
	mainWindow.on('move', (event) => {
		let XY = { "横向位置": mainWindow.getBounds().x, "纵向位置": mainWindow.getBounds().y, "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口位置被改变('" + JSON.stringify(XY) + "')} catch (error) {}")
	})
	mainWindow.on('moved', (event) => {
		let XY = { "横向位置": mainWindow.getBounds().x, "纵向位置": mainWindow.getBounds().y, "窗口标识": WindowsData["窗口标识"] }
		mainWindow.webContents.executeJavaScript("try {窗口位置被改变('" + JSON.stringify(XY) + "')} catch (error) {}")
	})
	//串口
	mainWindow.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
		mainWindow.webContents.session.on('serial-port-added', (event, port) => {
			console.log('serial-port-added FIRED WITH', port)
		})
		mainWindow.webContents.session.on('serial-port-removed', (event, port) => {
			console.log('serial-port-removed FIRED WITH', port)
		})
		event.preventDefault()
		if (portList && portList.length > 0) {
			callback(portList[0].portId)
		} else {
			callback('')
		}
	})
	mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
		if (permission === 'serial' && details.securityOrigin === 'file:///') {
			return true
		}
		return false
	})
	mainWindow.webContents.session.setDevicePermissionHandler((details) => {
		if (details.deviceType === 'serial' && details.origin === 'file://') {
			return true
		}
		return false
	})
	mainWindow.webContents.on('did-finish-load', () => {
		mainWindow.webContents.executeJavaScript("try {页面加载完毕()} catch (error) {window.didFinishLoadFOF = true;}")
		let WindowsID = { "窗口标识": WindowsData["窗口标识"], "调试编译": WindowData[10] };
		mainWindow.webContents.executeJavaScript("try {窗口创建完毕('" + JSON.stringify(WindowsID) + "')} catch (error) {}");
	});
	mainWindow.webContents.on('dom-ready', () => {
		mainWindow.webContents.executeJavaScript("try {DOM加载完毕()} catch (error) {window.domreadyFOF = true;}")
	});
	if (startsWithDoubleSlash(WindowsData["页面"]) == true) {
		mainWindow.loadURL(WindowsData["页面"])
	} else {
		mainWindow.loadFile("./DataHtml/" + WindowsData["页面"])
	}
	if (process.platform == 'darwin') {
		app.dock.hide();
	}
});
function startsWithDoubleSlash(str) {
	if (typeof str !== 'string' || str.length < 4) {
		return false;
	}
	return str[0] === 'h' && str[1] === 't' && str[2] === 't' && str[3] === 'p';
}
function isObject(value) {
	return value !== null && typeof value === 'object';
}
const { shell } = require("electron");
const 路径模块 = require("path");
ipcMain.handle("设置快捷方式", (event, 程序名称, 快捷方式说明, 图标路径) => {
    const 目标路径 = 路径模块.join(app.getPath("desktop"), 程序名称 + ".lnk");
    // 创建快捷方式的选项
    const options = {
        target: process.execPath,
        args: ["--some-flag"],
        description: 快捷方式说明,
        iconPath: 图标路径,
        iconIndex: 0
    };
    shell.writeShortcutLink(目标路径, "create", options)
});
