var window, platform, log, servicePlatform,win, isDebug = false, isFull;
if (typeof cordova === 'undefined') {
    //判斷目前是使用NW.js 還是electron
	try{		
		try{			           
			var remote = nodeRequire('electron').remote;
			window = win = remote.getCurrentWindow();
            var appVersion = remote.app.getVersion();			
            if(appVersion != '6.0.1'){
                //win.setFullScreen(false);
				win.setMinimumSize(320, 568);
                win.setSize(320, 568);
                win.center();
                win.setResizable(false);
                win.setMaximizable(false);
                isFull = true;
            }			
			
			platform = 'electron';
		} catch(e){
            window = win = nodeRequire('nw.gui').Window.get();
            isFull = true;
            platform = 'nw';
		}
    }catch(e){
        //platform = 'web';
    }
	//網頁時的啟動
    angular.element().ready(startup);
} else {
    //裝置上運行時的啟動
	document.addEventListener("deviceready", function(){
		try{
			//設定全螢幕
			AndroidFullScreen.immersiveMode(function(){
				console.info("It worked!");
			}, function(error){
				console.error(error);
			});
			//綁定橫向螢幕
			screen.lockOrientation('landscape');
			//關閉狀態列
			StatusBar.hide();
    		navigator.splashscreen.hide();
    	} catch(e){};
    	startup();
	}, false);
}

function startup(){	           
	init();
	var domElement = document.querySelector('body');
	angular.bootstrap(domElement, ["update"]);
}

function parseParamsToConfig(config){
	if(platform == 'electron' || platform == 'nw'){
		try{
			var outside_params = [];
			var remote;
			if(platform == 'electron'){
				remote = nodeRequire('electron').remote;
				outside_params = remote.process.argv;
			} else if(platform == 'nw'){
				outside_params = nodeRequire('nw.gui').App.argv;
			}
			for(var index in outside_params){
				var param = outside_params[index];
				if(param.indexOf('-params?') == 0){
					var paramArray = param.replace('-params?','').split(';');
					for(var index_y in paramArray){
						var keyValue = paramArray[index_y].split('=');
						if(keyValue[0] == 'ip'){
						    //20201125 雋辰,新增選擇DNS/IP
						    var tmp = keyValue[1].split('.');
						    var isIP = false , isNum = true;
						    for (var i = 0; i < tmp.length; i++) {
						        if (isNaN(new Number(tmp[i]))) {
						            isNum = false;
						            break;
						        }
						    }
						    isIP = tmp.length == 4 && isNum;
						    if (isIP)
						    {
						        config.setting.DNSMode = false;
						        config.server.ip = keyValue[1];
						    } 
						    else
						    {
						        config.setting.DNSMode = true;
						        config.server.DNS = keyValue[1];
						    }
						  
										   
						}
						if(keyValue[0] == 'port'){
						    config.server.port = keyValue[1];						   
						}
						if(keyValue[0] == 'name'){
							config.server.name = keyValue[1];
						}
						if(keyValue[0] == 'eainame'){
							config.server.eainame = keyValue[1];
						}
					}
				} else if(param.indexOf('-debug') == 0){
					if(platform == 'electron'){
						isDebug = true;
						remote.getCurrentWebContents().openDevTools();
					} else if(platform == 'nw'){
						isDebug = true;
						win.showDevTools();
					}
				} else if(param.indexOf('-online') == 0){
					config.cache.offline = false;
				} else if(param.indexOf('-noneFullScreen') == 0){
					config.setting.fullScreen = 'N'
				}				
			}
		}catch(e){
			console.log(e);
		}
	}
	localStorage.setItem(config.appName + "_server", JSON.stringify(config.server));
	return config;
}

function fullScreen(config){
	if(platform == 'electron'){
	    try {
            debugger;
			const remote = nodeRequire('electron').remote;
			var version = remote.app.getVersion();
			if(version != '6.0.1'){
				win = remote.getCurrentWindow();
				if(config.setting.fullScreen == 'Y'){
					win.setFullScreen(true);
				} else {
					win.setMinimumSize(320, 568);
					win.setSize(320, 568);
					win.center();
					win.setResizable(false);
					win.setMaximizable(false);
					isFull = true;				
				}
			}
		}catch(e){}
	}
}

function init(){
	var app = angular.module("update", ['pascalprecht.translate', 'ngMaterialLite', 'angularCSS']);
	app.config(["$httpProvider", "$provide", "$translateProvider",
		function ($httpProvider, $provide, $translateProvider) {
			$translateProvider.useStaticFilesLoader({ prefix: 'module/system/localization/localization-', suffix: '.json' });
			$translateProvider.preferredLanguage('zh_TW');
		}
	]);
	app.value('config',{});
	app.controller("update_controller", ["$scope", "$timeout", "$http", "$mdDialog", "config", "$translate", "$filter", function($scope, $timeout, $http, $mdDialog, config, $translate, $filter) {
		var newAppVersion;		
		$scope.show_screen=false;
		$scope.show_update=false;
		$scope.mode = '';
		$scope.isFull = isFull;

	    //20201023 雋辰,新增WS設定
		$scope.showWS = false;
		var showWSClickCount = 0;

	    $scope.init = function(){
	    	//log.innerHTML = '...';
			log = document.getElementById('update_log');
			log.innerHTML = '...';			
			downloadConfig();
	    }

	    $scope.close = function(){
			window.close();
	    }

		$scope.loadServerList = function(){
			var serverList = [];
			if(config.serverList){
				for(var env_name in config.serverList){
					serverList.push({code:env_name, label:$filter('translate')('mms01_user_login.env.'+env_name), server:config.serverList[env_name]});
				}
			}
			showSelect({
				title : $filter('translate')('mms01_user_login.ServerList'),
				label : 'label',
				code : 'code',
				selectCode : '',
				list : serverList,
				confirm : function(item, dialog){
					dialog.hide();
					config.setting.environment = $scope.environment = item.code;
					config.server.name = item.server.name;
					config.server.eainame = item.server.eainame;
				    //20220419 13871,增加sc設定
					config.server.scname = item.server.scname;
					if (typeof(Storage) !== "undefined") {
						localStorage.setItem(config.appName + "_server", JSON.stringify(config.server));
						localStorage.setItem(config.appName + "_setting", JSON.stringify(config.setting));
						//localStorage.setItem(config.appName + "_lang", $scope.currentUse);
					}
				}
			});
		}		

	    //20201023 雋辰,顯示/隱藏WS設定
		$scope.showWSClick = function () {
		    showWSClickCount++;
		    if (showWSClickCount >= 5) {
		        showWSClickCount = 0;
		        $scope.showWS = !$scope.showWS;
		    }
		}

		function showSelect(options){
			$mdDialog.dialog('JSplugins/angular-material-lite/template/radioList.tmp.html', function(dialog){
				return {
					title : options.title||$filter('translate')('common.msg.plz_select'),
					label : options.label,
					code : options.code,
					order: options.order||options.label,
					selectCode : options.selectCode,
					back : function() {
						this.hide();
					},
					itemList : options.list,
					itemClick : function(item, event){
						//$translate.use(item.code);
						//$scope.currentUse = item.code;
						if(options.confirm)
							options.confirm(item, this);
						//this.hide();
					},
					itemCancel:function(){
						dialog.hide();
						if(options.cancel)
							options.cancel(this);
					},
					isCancel:options.cancel!=undefined
				}
			});
		}		
		
	    function downloadConfig(){
	    	$http.post('config/config.json').then(function(res){
	    		angular.merge(config, res.data);
	    		if (typeof (Storage) !== "undefined") {
	    		    //20201023 雋辰,新增WS設定
	    		    angular.merge(config.serverList, JSON.parse(localStorage.getItem(config.appName + "_serverList")));
					angular.merge(config.server, JSON.parse(localStorage.getItem(config.appName + "_server")));
					angular.merge(config.setting, JSON.parse(localStorage.getItem(config.appName + "_setting")));
					//config.server.name = 'mobilemiddleware';
					//config.server.name = 'MES_Production_MESws_STD';
					//config.server.eainame = 'MES_Production_MESws_EAI';
					$scope.environment = config.setting.environment;
					
					if(!config.setting.fullScreen){
                        config.setting.fullScreen = 'N';
                    }
					
					//載入Server設定
					config.server = angular.merge({}, config.serverList[config.setting.environment]);//取出預設的Server資訊
					var LocalServerConfig = JSON.parse(localStorage.getItem(config.appName + '_server'));//取出本地端儲存的Server資訊
					angular.merge(config.server, LocalServerConfig);
					if(config.server.name==''){
						config.server.name = 'MES_Production_MESws_STD';
					}		
					if(config.server.eainame==''){
						config.server.eainame = 'MES_Production_MESws_EAI';
					}	
					
					parseParamsToConfig(config);
					if(platform == 'electron')
					{win.setFullScreen(false);}
                    else if(platform == 'nw')
					{win.leaveFullscreen();}
					
					var temp = config.server.ip.split('.');
                    if(temp.length == 4){
                        $scope.serverIp = temp;
                    } else {
                        $scope.serverIp = ["0", "0", "0", "0"];
                    }					
					$translate.use(config.setting.lang);
					if(window.cordova){
						config.appVersion = localStorage.getItem(config.appName + "_version");
					}
					$scope.config = config;
					
				}
				angular.element(document.querySelector('#update_controller')).css('display','block');
				if(window.nodeRequire){
					$scope.isElectron = true;
					checkUpdate();
		    	} else if (window.cordova){
		    		try{
			    		navigator.splashscreen.hide();
			    	} catch(e){};
					$timeout(function(){
				    	checkUpdate();
					});
		    	} else {
					changeMode('setting');				
				}
	    	});
	    }

		function checkUpdate(){
		    //20201125 雋辰,新增選擇DNS/IP
		    var ip = config.setting.DNSMode ? config.server.DNS : config.server.ip;

			if(config.cache.offline){
				reDirect('index.html');
			} else if((!config.setting.DNSMode && config.server.ip != '0.0.0.0') ||
                       (config.setting.DNSMode && ip.length > 0)){
				$scope.show_update=true;
		    	log.innerHTML = $filter('translate')('update.msg.checking_update');//檢查更新中...
				
		    	sendToMESSrv_plain({
					uri: 'tcMES_LiveUpdate.clsLiveUpdate.LiveUpdate_PDA',
					//uri: 'tcMES_LiveUpdate.clsLiveUpdate.LiveUpdate',
					content : {
						applicationId:config.applicationId
					},
					success : function(data){
						data = JSON.parse(data);
						if(data.Result != 'fail'){
							//console.log(data.version);
							newAppVersion = data.version;
							servicePlatform = data.platform;
							
							if(data.version == config.appVersion || data.version == '0.0.0.0' || data.version == ''){
								$scope.show_update=true;
								checkUpdateExist();
							} else {
								if(data.url.indexOf('http://')==-1){
									data.url = 'http://'+config.server.ip+':'+config.server.port+"/"+data.url;
								}
								$scope.show_update=true;
								downloadZip(data.url);
							}
						} else {
							log.innerHTML = data.SysMsg;
							$scope.show_update=false;
						}
					}
				});
	    	} else {
	    		//一開始IP還未設定的時候
	    		changeMode('setting');
	    	}
		}
		
	    //檢查是否已經更新過
	    function checkUpdateExist(){
	    	if(window.resolveLocalFileSystemURL){
	    		window.resolveLocalFileSystemURL(cordova.file.dataDirectory+'update', function(updateFolder){
	    			reDirect(updateFolder.toURL() + '/index.html');
	    		}, function(){
	    			reDirect('index.html');
	    		});
	    	} else {
	    		reDirect('index.html');
	    	}
	    }

	    //download ZIP file
		function downloadZip(url){
			log.innerHTML = $filter('translate')('update.msg.update_download_start');//开始下载更新...
			$scope.show_update=true;
			try{
				var zipDistUrl = cordova.file.dataDirectory;
				var ft = new FileTransfer();
				ft.onprogress = function(progressEvent) {
		            if (progressEvent.lengthComputable) {
		            	//更新下載中
						log.innerHTML = $filter('translate')('update.msg.update_downloading')+Math.floor(progressEvent.loaded / progressEvent.total * 100)+'%';
						$scope.show_update=true;	
			        }
			    };
			    ft.download(url, zipDistUrl+'update.zip',
					function(r) {
						log.innerHTML = $filter('translate')('update.msg.updating');//程式更新中...
						$scope.show_update=true;
						if(navigator.userAgent.match(/iPhone|iPad|iPod/i)){
							unZIPforIOS(zipDistUrl);
						} else {
							prepareUnZip(zipDistUrl);
						}
					}, function(error) {
						log.innerHTML = $filter('translate')('update.msg.cant_download');//無法下載更新，請確認伺服器連線是否正常;
						$scope.show_update=false;
						changeMode('setting');
					}
				);
			}catch(e){
				if(window.nodeRequire){
					var data = {
							url : url,
							method : 'GET',
							type:"application/octet-stream",
							responseType: 'arraybuffer'
						},
						request = nodeRequire('request'),
						progress = nodeRequire('request-progress'),
						fs = nodeRequire('fs'),
						AppPath;
					const Zip = nodeRequire('adm-zip-electron');

					log.innerHTML = $filter('translate')('update.msg.updating');
					$scope.show_update=true;
					if(platform == 'electron'){
						AppPath = nodeRequire('electron').remote.app.getAppPath()+'\\';
					} else {
						var nwDir = nodeRequire('path').dirname(process.execPath);
						AppPath = nwDir+'\\package.nw\\';
					}

					var updateFile = AppPath + 'update.zip';
					var tempFile = fs.createWriteStream(updateFile);
					tempFile.on('finish', function(){
						tempFile.close(function(){
							try{
								log.innerHTML = $filter('translate')('update.msg.updating');//程式更新中...
								$scope.show_update=true;
								var zip = new Zip(updateFile);
								zip.extractAllTo(AppPath+'www\\', true);
								clearUpdate(AppPath, 'update.zip', function(){
									reDirect('index.html');
								});

							}catch(e){
								log.innerHTML = $filter('translate')('update.msg.zip_cant_download')+'<br>'+e;//無法下載更新，更新用的檔案不存在，請確認伺服器連線資訊是否正確
								$scope.show_update=false;
								changeMode('setting');
							}
						});
					});

					var request = request(url, function(error, response, body){
						if(error){
							log.innerHTML = $filter('translate')('update.msg.zip_cant_download');//無法下載更新，更新用的檔案不存在，請確認伺服器連線資訊是否正確
							$scope.show_update=false;
							changeMode('setting');
						} else {
							log.innerHTML = $filter('translate')('update.msg.update_downloading') + '100%';
							$scope.show_update=true;
						}
					});
					request.pipe(tempFile);
					progress(request, {
					    throttle: 200,                    // Throttle the progress event to 2000ms, defaults to 1000ms
					    // delay: 1000,                       // Only start to emit after 1000ms delay, defaults to 0ms
					    // lengthHeader: 'x-transfer-length'  // Length header to use, defaults to content-length
					})
					.on('progress', function (state) {
						//更新下載中
						log.innerHTML = $filter('translate')('update.msg.update_downloading')+(Math.round(state.percent * 100))+'%';
						$scope.show_update=true;						
					})
					.on('error', function (err) {
						log.innerHTML = $filter('translate')('update.msg.zip_cant_download');//無法下載更新，更新用的檔案不存在，請確認伺服器連線資訊是否正確
						$scope.show_update=false;
						changeMode('setting');
					});
				} else {
					reDirect('index.html');
				}
			}
		}

		var g_zipDistUrl;
		function prepareUnZip(zipDistUrl){
			var srcUrl = cordova.file.applicationDirectory + 'www/';
			g_zipDistUrl = zipDistUrl;
			window.resolveLocalFileSystemURL(srcUrl,
				function(directoryEntry){
					window.resolveLocalFileSystemURL(zipDistUrl, function(dstDirectoryEntry){
						dstDirectoryEntry.getDirectory('update', {create: true}, function(updateDirEntry){
							log.innerHTML = $filter('translate')('update.msg.prepare_updat'); //正在準備更新程式...
							$scope.show_update=true;
							//get file cordova.js, cordova_plugins.js, plugins
							directoryEntry.getFile('cordova.js', {}, function (fileEntry) {
								//copy cordova.js
								fileEntry.copyTo(updateDirEntry,'cordova.js', function(){
									directoryEntry.getFile('cordova_plugins.js', {}, function (fileEntry) {
										//copy cordova_plugins.js
										fileEntry.copyTo(updateDirEntry,'cordova_plugins.js', function(){
											directoryEntry.getDirectory('plugins', {}, function(pluginsDirEntry){
												//copy plugins
												pluginsDirEntry.copyTo(updateDirEntry,'plugins', function(){
													directoryEntry.getDirectory('cordova-js-src', {}, function(pluginsDirEntry){
														//copy cordova-js-src
														pluginsDirEntry.copyTo(updateDirEntry,'cordova-js-src', function(){
															directoryEntry.getDirectory('scripts', {}, function(pluginsDirEntry){
																//copy scripts
																pluginsDirEntry.copyTo(updateDirEntry,'scripts', function(){
																	unZIPforCordova(zipDistUrl);
																}, copyfileError);
															}, getDirectoryError);
														}, copyfileError);
													}, getDirectoryError);
												}, copyfileError);
											}, getDirectoryError);
										}, copyfileError);
									}, getDirectoryError);
								}, copyfileError);
							}, getDirectoryError);
						}, getDirectoryError);
					}, getDirectoryError);
				}, getDirectoryError
			);
		}

		function copyfileError(error){
			if(error.code == 9 || error.code == 12){
				unZIPforCordova(g_zipDistUrl);
			} else {
				log.innerHTML = $filter('translate')('update.msg.temp_file_cant_dele')+":"+error.code;//暫存檔案刪除失敗，請重新下載
				$scope.show_update=false;
				changeMode('setting');
			}
		}

		function unZIPforCordova(zipDistUrl){
            log.innerHTML = $filter('translate')('update.msg.updating');//程式更新中...
			$scope.show_update=true;
			var dstDir = zipDistUrl + 'update'
            zip.unzip(zipDistUrl+'update.zip', dstDir,
            	function(result){
            		if(result==0){
            			clearUpdate(zipDistUrl, 'update.zip', function(){
            				//localStorage.setItem(config.appName + "_version", newAppVersion);
            				reDirect(zipDistUrl+'update/index.html');
            			});
            		} else {
            			log.innerHTML = $filter('translate')('update.msg.zip_server_connect');//'更新檔解析失敗，請重新下載';
						$scope.show_update=false;
            			changeMode('setting');
            		}
            	},
            	function(progressEvent){
            		log.innerHTML = $filter('translate')('update.msg.updating') + Math.round((progressEvent.loaded / progressEvent.total) * 100)+'%';
					$scope.show_update=true;
            	}
            );
		}

		function unZIPforIOS(zipDistUrl){
			var srcUrl = cordova.file.applicationDirectory + 'www/';
			var dstDir = zipDistUrl + 'update'
			window.resolveLocalFileSystemURL(
					srcUrl,
				function(directoryEntry){
					window.resolveLocalFileSystemURL(zipDistUrl, function(dstDirectoryEntry){
						log.innerHTML = $filter('translate')('update.msg.prepare_updat'); //正在準備更新程式...
						$scope.show_update=true;
						directoryEntry.copyTo(dstDirectoryEntry, 'update', function(){
							zip.unzip(zipDistUrl+'update.zip', dstDir,
								function(result){
									if(result==0){
										clearUpdate(zipDistUrl, 'update.zip', function(){
											//localStorage.setItem(config.appName + "_version", newAppVersion);
											reDirect(zipDistUrl+'update/index.html');
										});
									} else {
										log.innerHTML = $filter('translate')('update.msg.zip_server_connect');//'更新檔解析失敗，請重新下載';
										$scope.show_update=false;
										changeMode('setting');
									}
								},
								function(progressEvent){
									log.innerHTML = $filter('translate')('update.msg.updating') + Math.round((progressEvent.loaded / progressEvent.total) * 100)+'%';
								}
							);
					    }, function(error){
					    	if(error.code == 9 || error.code == 12){
						    	log.innerHTML = $filter('translate')('update.msg.delete_temp_file');//正在刪除暫存檔案...
								$scope.show_update=true;
						    	resolveLocalFileSystemURL(dstDir, function(dstDirectory){
						    		dstDirectory.removeRecursively(function(){
						    			unZIPforCordova(zipDistUrl);
								    },function(error){
								    	log.innerHTML = $filter('translate')('update.msg.temp_file_cant_dele');//暫存檔案刪除失敗，請重新下載
										$scope.show_update=false;
										changeMode('setting');
								    });
						    	}, getDirectoryError);
					    	} else {
					    		log.innerHTML = $filter('translate')('update.msg.temp_file_cant_dele')+":"+error.code;//暫存檔案刪除失敗，請重新下載
								$scope.show_update=false;
								changeMode('setting');
					    	}
						});
					}, getDirectoryError);

				},
				getDirectoryError
			);
		}

		function getDirectoryError(error){
			log.innerHTML = "ERROR"+":"+error.code;//暫存檔案刪除失敗，請重新下載
			$scope.show_update=false;
			changeMode('setting');
		}

		//delete update.zip file
		function clearUpdate(url, fileName, feedback){
			try{
				resolveLocalFileSystemURL(url, function(dir) {
					dir.getFile(fileName, {create:false}, function(fileEntry) {
				        fileEntry.remove(function(){
				        	if(feedback)
				        		feedback();
				            // The file has been removed succesfully
				        },function(error){
							log.innerHTML = $filter('translate')('update.msg.temp_file_cant_dele');//暫存檔案刪除失敗
							$scope.show_update=false;
							if(feedback)
					        	feedback();
				        },function(){
				        	log.innerHTML = $filter('translate')('update.msg.temp_file_not_exist');//暫存檔案不存在
							$scope.show_update=false;
							if(feedback)
					        	feedback();
				        });
					});
				});
			} catch(e){
				nodeRequire('fs').unlink(url+'\\'+fileName, function(error){
					if(feedback)
				        feedback();
				});
			}
		}

		function changeMode(mode){
			$timeout(function(){
				$scope.mode = mode;
				if(mode == 'setting'){
					if(platform == 'electron'){
						win.setSize(320, 568);
						win.center();
					} else if(platform == 'nw'){
						win.resizeTo(320, 568);
					}
				} else{
					if(platform == 'electron'){
						win.setSize(320, 568);
						win.center();
					} else if(platform == 'nw'){
						win.resizeTo(320, 568);
					}
				}
			});
			
			$timeout(function(){
				$scope.show_screen=true;
			},750);
		}

		$scope.reCheckUpdate = function(){
		    config.server.ip = combineIP($scope.serverIp);
		    config.server.name = config.serverList[config.setting.environment].name;
		    config.server.eainame = config.serverList[config.setting.environment].eainame;
		    //20220419 13871,增加sc設定
		    config.server.scname = config.serverList[config.setting.environment].scname;

		    localStorage.setItem(config.appName + "_serverList", JSON.stringify(config.serverList));
			localStorage.setItem(config.appName + "_server", JSON.stringify(config.server));
			changeMode('');
			checkUpdate();
		}

		function combineIP(array){
			var totalip;
			array.forEach(function(ipstring){
				if(!totalip)
					totalip = ipstring;
				else
					totalip += "." +ipstring;
			});
			return totalip;
		}

		function reDirect(url, msg){
			log.innerHTML = msg||$filter('translate')('update.msg.update_complete');//程式更新完成...
			$scope.show_update=true;
			//底層為Cordova 的狀態下，一旦更新完成就把新的版本號寫入localStorage
			if(window.cordova && newAppVersion != '0.0.0.0'){
				localStorage.setItem(config.appName + "_version", newAppVersion);
			}
			localStorage.setItem(config.appName + "_servicePlatform", servicePlatform);
		
			$timeout(function(){
				if(platform == 'electron'){
					createWindow(url);
				} else if(platform == 'nw'){
					createWindowNW(url);
				} else {
					document.location.href = url;
				}				
			}, 100);
		}
		
		function createWindow (url) {
			var BrowserWindow = nodeRequire('electron').remote.BrowserWindow;
			var newWin = new BrowserWindow({
				width: 320,
				minWidth: 320,
				height: 568,
				minHeight: 568,
				frame:false,
				fullscreen: false,
				fullscreenable: true,
				titleBarStyle : 'customButtonsOnHover',
				show: false
			});
			newWin.loadURL('file://'+__dirname+'/'+url);
			newWin.on('closed', function(){
				newWin = null;
			});
			newWin.once('ready-to-show', function(){
				if(isDebug)
					newWin.webContents.openDevTools();
				newWin.show();
				newWin.setFullScreen(config.setting.fullScreen == 'Y');
				win.close();
			});
		}		
		
		function createWindowNW (url) {
			var nw = nodeRequire('nw.gui'),
				settings = {
					position: "center",
					min_width:320,
					min_height:568,
					width:320,
					height:568,
					resizable:true,
					fullscreen:config.setting.fullScreen == 'N',
					frame: false,
					show: false,
					icon:"icon/icon.png"
				};
			nw.Window.open('www/'+url, settings, function(new_win) {
				if(isDebug)
					new_win.showDevTools();
				new_win.on('loaded', function(){
                    new_win.show();
					win.close();
				});
			});
		}		

		function prepareHeader(data){
			var header = {};
			//TODO
			header.Method = data.uri;
			header["mds.userid"] = '';
			header["mds.password"] = '';
			header["mds.environment"] = config.setting.environment;
			header["mds.language_mode"] = $translate.use();
			header["mds.computer_name"] = config.client.ip;
			header["mds.sessionno"] = config.mdssessionno;
			return header;
		}

		function prepareContent(data){
			var content = {};
			content.CompanyID = config.setting.companyId;
			content.Equipment = '';
			content = angular.merge(content, data.content);
			return content;
		}
		
		function prepareMESHeader(data){
			var header = {};
			//TODO
			header["method"] = data.uri;
			header["userid"] = config.cache.account||'';
			header["languagemode"] = $translate.use();
			header["computername"] = config.client.ip;
			header["sessionno"] = config.mdssessionno;
			return header;
		}
		
		function sendToMESSrv_plain(sendData) {
		    //20201125 雋辰,新增選擇DNS/IP
		    var ip = config.setting.DNSMode ? config.server.DNS : config.server.ip;
			
			var apiurl = config.server.name+'/wsInvoke.asmx/InvokeSrv_plainjson';
			var liveupdate_url = 'http://'+ip+':'+config.server.port+'/'+apiurl;
			var	header = prepareMESHeader(sendData);
			
			var data = {
                url : liveupdate_url,
                method : 'POST',
                headers : {
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                data : {
                	"uri":JSON.stringify(header),
                	"content":JSON.stringify(sendData.content)
                }
            };
			if(config.server.timeout != 0)
				data.timeout =config.server.timeout;
			
			$http(data).success(function(data, status, headers, config) {
				try{
				var contentData = JSON.parse(data.d);
				if(contentData.Code === '0' || contentData.Code === null || contentData.code === '0' || contentData.code === null){
					if(sendData.success)
						sendData.success(contentData.ResultJson);
				} else {
					if(sendData.error){
						sendData.error(contentData);
					} else {
						log.innerHTML = contentData.exception;
						$scope.show_update=false;
						changeMode('setting');
					}
				}
				}catch(e){
					log.innerHTML = e
					$scope.show_update=false;
					changeMode('setting');
				}
			}).error(function(a,b,c,d){
				log.innerHTML = $filter('translate')('update.msg.cant_get_verInfo');//無法取得版本資訊
				$scope.show_update=false;
				changeMode('setting');
			});
		}
		

		function send(sendData){
			var data = {
				url : 'http://'+config.server.ip+':'+config.server.port+'/mobilemiddleware/api/v1/transaction/json',
				method : 'POST',
				headers : {
					'Content-Type': 'application/json;charset=UTF-8'
				},
				data : {
				    "applicationId":config.applicationId,
				    "uri": sendData.uri,
				    "headers":prepareHeader(sendData),
				    "cookies":[],
					'content':JSON.stringify(prepareContent(sendData))
				}
			};
			if(config.server.timeout != 0)
				data.timeout =config.server.timeout;

			$http(data).success(function(data, status, headers, config) {
				try{
				var contentData = JSON.parse(data.content);
				if(contentData.IsSuccess){
					if(sendData.success)
						sendData.success(contentData.Result);
				} else {
					if(sendData.error){
						sendData.error(contentData);
					} else {
						log.innerHTML = contentData.SysException;
						changeMode('setting');
					}
				}
				}catch(e){
					log.innerHTML = e
					changeMode('setting');
				}
			}).error(function(a,b,c,d){
				log.innerHTML = $filter('translate')('update.msg.cant_get_verInfo');//無法取得版本資訊
				changeMode('setting');
			});
		}
	}]);
};
