using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using Microsoft.Win32;
using System.Xml;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Globalization;
using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Collections;

namespace ManageTools
{
    
    
    public partial class Main : Form
    {
        
        //web工程的发布名称
        string webName = "WebContent";
        //判断系统版本
        bool bit64 = Environment.Is64BitOperatingSystem;
        //应用程序当前路径
        string curPath;
        //应用程序的上一级路径
        string parentPath;

        string rmsName = "";//抄表服务名
        string rmsRun64 = "";//64位下时应用程序名
        string rmsRun32 = "";//32位下时应用程序名

        string rmsSelfName = "";//抄表服务名
        string rmsSelfRun64 = "";//64位下时应用程序名
        string rmsSelfRun32 = "";//32位下时应用程序名

        string rmsCarName = "";//抄表服务名
        string rmsCarRun64 = "";//64位下时应用程序名
        string rmsCarRun32 = "";//32位下时应用程序名

        string rmsOpcName = "";//抄表服务名
        string rmsOpcRun64 = "";//64位下时应用程序名
        string rmsOpcRun32 = "";//32位下时应用程序名

        string GPRSName = "";//GPRS服务名
        string GPRSRun64 = "";//64位下时GPRS程序名
        string GPRSRun32 = "";//32位下时GPRS程序名

        bool autoRun = false; //自动运行
        //指定Sql Server提供者的连接字符串  
        string connString;
        //建立连接对象  
        MySqlConnection mySqlConnection;
        SqlConnection Sqlconn;  
        //为上面的连接指定Command对象  
        SqlCommand thiscommand;
        //为指定的command对象执行DataReader 
        //SqlDataReader thisSqlDataReader;
        public string language
        {
            set;
            get;
        }
        System.ComponentModel.ComponentResourceManager res;

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] 
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", EntryPoint = "IsWindow")]
        public static extern bool IsWindow(IntPtr hWnd);
        [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
        public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);

        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            loadConfig();
            curPath = System.Windows.Forms.Application.StartupPath;
            parentPath = curPath.Substring(0, curPath.IndexOf("ManageTools"));
            
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void bt_test_Click(object sender, EventArgs e)
        {
          
            
        }
        private void bt_stop_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            stopService(rmsSelfName);
            stopService(rmsCarName);
            stopService(rmsOpcName);
            stopService(GPRSName);
            stopService("Tomcat");

            killProcess("3761");
            killProcess("nginx");
            killProcess("LiveNVR");

        }

        private void killProcess(string processName)
        {
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();
            //得到所有打开的进程   
            try
            {
                foreach (Process thisproc in Process.GetProcessesByName(processName))
                {
                    if (!thisproc.CloseMainWindow())
                    {
                        Console.WriteLine("| ================" + processName);
                        thisproc.Kill();
                    }
                }

            }
            catch (Exception Exc)
            {
                MessageBox.Show(Exc.Message);
            }
        }

        //启动web服务
        private void bt_start_Click(object sender, EventArgs e)
        {
            /*
            if (bit64)
            {
                startService("抄表事务服务", parentPath + "\\Release", "runJavaApp_64.bat");
                startService("GPRS", parentPath + "\\GPRS服务", "IpServer_64.exe");
                startService("Tomcat", parentPath + "\\tomcat-8.0-64\\bin", "startup.bat");
            }
            else
            {
                startService("抄表事务服务", parentPath + "\\Release", "runJavaApp_32.bat");
                startService("GPRS", parentPath + "\\GPRS服务", "IpServer_32.exe");
                startService("Tomcat", parentPath + "\\tomcat-8.0-32\\bin", "startup.bat");
            }
             * */
            startServiceAll();
            timer1.Enabled = true;
        }
        private void startServiceAll()
        {
            if (bit64)
            {
                // 启动集中器
                startService(rmsSelfName, "", parentPath + "\\Release", rmsSelfRun64);
                startService(rmsCarName, "", parentPath + "\\Release", rmsCarRun64);
                startService(rmsOpcName, "", parentPath + "\\Release", rmsOpcRun64);
                // 启动 GPRS
                startService(GPRSName, "3761", parentPath + "\\GPRS-Service", GPRSRun64);
                // 启动主站后端
                startService("Tomcat","", parentPath + "\\apache-tomcat\\bin", "startup.bat");

                // 启动 nginx
                startService("nginx", "", parentPath + "\\nginx-1.18.0", "nginx.exe");

                // 启动 流媒体
                startService("LiveNVR", "", parentPath + "\\LiveNVR", "LiveNVR.exe");
            }
            else
            {
                startService(rmsSelfName, "", parentPath + "\\Release", rmsSelfRun32);
                startService(rmsCarName, "", parentPath + "\\Release", rmsCarRun32);
                startService(rmsOpcName, "", parentPath + "\\Release", rmsOpcRun32);
                startService(GPRSName, "3761", parentPath + "\\GPRS-Service", GPRSRun32);
                startService("Tomcat", "", parentPath + "\\apache-tomcat\\bin", "startup.bat");
                // 启动 nginx
                startService("nginx", "", parentPath + "\\nginx-1.18.0", "nginx.exe");
                // 启动 流媒体
                startService("LiveNVR", "", parentPath + "\\LiveNVR", "LiveNVR.exe");
            }
        }
        //开启服务
        private void startService(string windowName,string exeName,string appPath,string appName)
        {
            //IntPtr hWnd = FindWindow(null, windowName);
            IntPtr hWnd = IntPtr.Zero;
            Process[] MyProcesses = Process.GetProcesses();
            foreach(Process MyProcess in MyProcesses)
            {
                // Console.WriteLine("| MyProcess.ProcessName: " + MyProcess.ProcessName);
                if (exeName != "")
                {
                    if (MyProcess.ProcessName == exeName)
                    {
                        return;
                    }
                }

                if (windowName != "")
                {
                    // if (MyProcess.ProcessName == windowName)
                    if (MyProcess.ProcessName.IndexOf(windowName) > -1)
                    {
                        Console.WriteLine("| MyProcess.ProcessName: " + MyProcess.ProcessName);
                        return;
                    }
                }

                if ((MyProcess.MainWindowTitle.IndexOf(windowName) > -1))
                {
                    Console.WriteLine("| MyProcess.ProcessName: " + MyProcess.ProcessName + "MyProcess.MainWindowTitle:" + MyProcess.MainWindowTitle + ",windowName:" + windowName);
                    return;
                }

            }

            if (hWnd == IntPtr.Zero)
            {
                if (File.Exists(appPath + "\\" + appName))
                {
                    Directory.SetCurrentDirectory(appPath);
                    Process startProcess = new Process();
                    startProcess.StartInfo.FileName = appPath + "\\" + appName;
                    startProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                    startProcess.Start();

                    Console.WriteLine("| appPath: " + appPath);
                    Console.WriteLine(appName + "启动成功！！！\n");
                }
            }
        }
        //调用 cmd
        private string runDosCmd(string[] commandTexts)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = true;
            string strOutput = null;
            try
            {
                p.Start();
                foreach (string item in commandTexts)
                {
                    p.StandardInput.WriteLine(item);
                }
            }
            catch (Exception e)
            {
                strOutput = e.Message;
            }
            return strOutput;
        }

        private void stopService(string windowName)
        {
            IntPtr hWnd = IntPtr.Zero;
            Process[] MyProcesses = Process.GetProcesses();
            foreach (Process MyProcess in MyProcesses)
            {
                // Console.WriteLine("| MyProcess.ProcessName: " + MyProcess.ProcessName);
                if (MyProcess.MainWindowTitle.IndexOf(windowName) > -1)
                {
                    MyProcess.CloseMainWindow();
                    Console.WriteLine("| " + windowName + "已经关闭");
                    break;
                }
            }
        }

  

        

        #region 参数加载
        private void loadConfig()
        {
            String filePath = System.Windows.Forms.Application.StartupPath + "\\backup";

            String fileName = System.Windows.Forms.Application.StartupPath;
            fileName += "\\system.ini";
            INIFile iniFile = new INIFile(fileName);
            tb_Host.Text = iniFile.ReadValue("config", "tb_Host", "127.0.0.1");
            tb_db.Text = iniFile.ReadValue("config", "tb_db", "samr");
            tb_user.Text = iniFile.ReadValue("config", "tb_user", "sa");
            mtb_pwd.Text = iniFile.ReadValue("config", "mtb_pwd", "sa");
            tb_path.Text = iniFile.ReadValue("config", "tb_path", filePath);
            gprs_ip.Text = iniFile.ReadValue("config", "frontend_ip", "127.0.0.1");
            // dTP_time.Text = iniFile.ReadValue("config", "dTP_time", "22:00");
            checkBox1.Checked = iniFile.ReadValue("config", "autoRun", false);
            baseUrl.Text = iniFile.ReadValue("config", "baseUrl", "8.129.11.230:8083");
            cameraUrl.Text = iniFile.ReadValue("config", "cameraUrl", "8.129.11.230:18010");

            iniFile.WriteValue("config", "autoRun", checkBox1.Checked);

            autoRun = checkBox1.Checked;
            //服务启动
            rmsName = iniFile.ReadValue("runserver", "rmsName", "Read-Service");
            rmsRun64 = iniFile.ReadValue("runserver", "rmsRun64", "runJavaApp_64.bat");
            rmsRun32 = iniFile.ReadValue("runserver", "rmsRun32", "runJavaApp_32.bat");

            iniFile.WriteValue("runserver", "rmsName", rmsName);
            iniFile.WriteValue("runserver", "rmsRun64", rmsRun64);
            iniFile.WriteValue("runserver", "rmsRun32", rmsRun32);

            rmsSelfName = iniFile.ReadValue("runserver", "rmsSelfName", "Read-Service-self");
            rmsSelfRun64 = iniFile.ReadValue("runserver", "rmsSelfRun64", "runJavaApp_self_64.bat");
            rmsSelfRun32 = iniFile.ReadValue("runserver", "rmsSelfRun32", "runJavaApp_self_32.bat");

            iniFile.WriteValue("runserver", "rmsSelfName", rmsSelfName);
            iniFile.WriteValue("runserver", "rmsSelfRun64", rmsSelfRun64);
            iniFile.WriteValue("runserver", "rmsSelfRun32", rmsSelfRun32);

            rmsCarName = iniFile.ReadValue("runserver", "rmsCarName", "Read-Service-car");
            rmsCarRun64 = iniFile.ReadValue("runserver", "rmsCarRun64", "runJavaApp_car_64.bat");
            rmsCarRun32 = iniFile.ReadValue("runserver", "rmsCarRun32", "runJavaApp_car_32.bat");

            iniFile.WriteValue("runserver", "rmsCarName", rmsCarName);
            iniFile.WriteValue("runserver", "rmsCarRun64", rmsCarRun64);
            iniFile.WriteValue("runserver", "rmsCarRun32", rmsCarRun32);

            rmsOpcName = iniFile.ReadValue("runserver", "rmsOpcName", "Read-Service-opc");
            rmsOpcRun64 = iniFile.ReadValue("runserver", "rmsOpcRun64", "runJavaApp_opc_64.bat");
            rmsOpcRun32 = iniFile.ReadValue("runserver", "rmsOpcRun32", "runJavaApp_opc_32.bat");

            iniFile.WriteValue("runserver", "rmsOpcName", rmsOpcName);
            iniFile.WriteValue("runserver", "rmsOpcRun64", rmsOpcRun64);
            iniFile.WriteValue("runserver", "rmsOpcRun32", rmsOpcRun32);

            GPRSName = iniFile.ReadValue("runserver", "GPRSName", "GPRS");
            GPRSRun64 = iniFile.ReadValue("runserver", "GPRSRun64", "3761.exe");
            GPRSRun32 = iniFile.ReadValue("runserver", "GPRSRun32", "3761.exe");

            iniFile.WriteValue("runserver", "GPRSName", GPRSName);
            iniFile.WriteValue("runserver", "GPRSRun64", GPRSRun64);
            iniFile.WriteValue("runserver", "GPRSRun32", GPRSRun32);

            this.language = iniFile.ReadValue("config", "language", "");
            if (this.language != "")
                cb1.Checked = true;
            ApplyResource();

        }

        private void saveConfig()
        {
            String fileName = System.Windows.Forms.Application.StartupPath;
            fileName += "\\system.ini";
            INIFile iniFile = new INIFile(fileName);
            iniFile.WriteValue("config", "tb_Host", tb_Host.Text);
            iniFile.WriteValue("config", "tb_db", tb_db.Text);
            iniFile.WriteValue("config", "tb_user", tb_user.Text);
            iniFile.WriteValue("config", "mtb_pwd", mtb_pwd.Text);
            iniFile.WriteValue("config", "tb_path", tb_path.Text);
            // iniFile.WriteValue("config", "dTP_time", dTP_time.Text);
            iniFile.WriteValue("config", "language", this.language);
            iniFile.WriteValue("config", "autoRun", checkBox1.Checked);
            iniFile.WriteValue("config", "baseUrl", baseUrl.Text);
            iniFile.WriteValue("config", "cameraUrl", cameraUrl.Text);
            iniFile.WriteValue("config", "frontend_ip", gprs_ip.Text);
        }

        #endregion

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            saveConfig();
           
        }

        //测试数据
        private void bt_test_Click_1(object sender, EventArgs e)
        {
            String msg = connectDB();
            if (msg.Trim() == "")
            {
                MessageBox.Show(Properties.Resources.数据库连接成功 + "!", Properties.Resources.提示信息);
                mySqlConnection.Close();
            }
            else
            {
                MessageBox.Show(Properties.Resources.数据库连接失败 + "! \r\n"
                    + connString + "\r\n"
                    + msg , Properties.Resources.提示信息);
            }
        }


        //数据库连接测试
        private String connectDB()
        {
            String msg = "";
            // SQL server 连接信息
            //   connString = "Data Source=" + tb_Host.Text + 
            //     ";Initial Catalog=" +  tb_db.Text +
            //     ";User id=" + tb_user.Text +
            //     ";Password=" + mtb_pwd.Text ;
            // Console.WriteLine(connString);
            // Sqlconn = new SqlConnection(connString);

            // MySQL 连接信息
            String connectStr = "server=" + tb_Host.Text + 
                ";port=3306;user=" + tb_user.Text + 
                ";password=" + mtb_pwd.Text + 
                ";database=" + tb_db.Text + ";";
            mySqlConnection = new MySqlConnection(connectStr);
            try
            {
                mySqlConnection.Open();
               
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }


        //参数生效
        private void btapply_Click(object sender, EventArgs e)
        {
            //需要关闭服务
            if (MessageBox.Show(Properties.Resources.请确认服务是否已经关闭 + "?", Properties.Resources.提示信息, MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            //配置java环境变量  -----------------------------------------------------------------------------------------------------------------
            /*try
            {
                setJavaParameter();
                log("设置JAVA环境变量完成!");
            }
            catch(Exception ex)
            {
                log("设置JAVA环境变量时，出现异常:" + ex.Message);
            }*/
            //tomcat  --------------------------------------------------------------------------------------------------------------------------------
            String tempPath;
            if (bit64)
                tempPath = parentPath + "\\apache-tomcat\\webapps\\" + webName + "\\WEB-INF\\applicationContext.xml";
            else
                 tempPath = parentPath + "\\apache-tomcat\\webapps\\" + webName + "\\WEB-INF\\applicationContext.xml";
            log(tempPath);
            XmlDocument dom = new XmlDocument();
            dom.Load(tempPath);
            String strValue;
            foreach (XmlNode tempNode in dom.ChildNodes[1].ChildNodes[1])
              {
                Console.WriteLine("============" + tempNode);
                  if (tempNode.Attributes == null)
                {
                    continue;
                }
                  strValue = tempNode.Attributes.GetNamedItem("name").InnerText;
                  if (strValue == "url")
                  {
                    // tempNode.Attributes.GetNamedItem("value").Value = getUTF8String("jdbc:sqlserver://" + tb_Host.Text.Trim() + ":1433;databasename=" + tb_db.Text.Trim());
                    tempNode.Attributes.GetNamedItem("value").Value = getUTF8String("jdbc:mysql://" + tb_Host.Text.Trim() + ":3306/" + tb_db.Text.Trim() + "?useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true");
                    continue;
                  }
                  else if (strValue == "username")
                  {
                      tempNode.Attributes.GetNamedItem("value").Value = getUTF8String(tb_user.Text.Trim());
                      continue;
                  }
                  else if (strValue == "password")
                  {

                      tempNode.Attributes.GetNamedItem("value").Value = getUTF8String(mtb_pwd.Text.Trim());
                      continue;
                  } 
                
              }

              dom.Save(tempPath);

            // 修改 hibernate 事务配置文件
            String hibernateConfigPath = parentPath + "\\apache-tomcat\\webapps\\" + webName + "\\WEB-INF\\classes\\hibernate.cfg.xml";
            XmlReaderSettings settings = new XmlReaderSettings() {
                ProhibitDtd = false,
                XmlResolver = null
            };
            XmlDocument hibernateDom = new XmlDocument();
            XmlReader xmlReader = XmlReader.Create(hibernateConfigPath, settings);
            // hibernateDom.Load(hibernateConfigPath);
            hibernateDom.Load(xmlReader);

            String configValue;
            foreach (XmlNode configNode in hibernateDom.ChildNodes[2].ChildNodes[0])
            {
                // Console.WriteLine("============" + configNode);
                if (configNode.Attributes == null)
                {
                    continue;
                }
                if (configNode.Attributes.GetNamedItem("name") == null)
                {
                    continue;
                }

                configValue = configNode.Attributes.GetNamedItem("name").InnerText;
                if (configValue == "hibernate.connection.url")
                {
                    configNode.InnerText = getUTF8String("jdbc:mysql://" + tb_Host.Text.Trim() + ":3306/" + tb_db.Text.Trim());
                    continue;
                }

                if (configValue == "hibernate.connection.password")
                {
                    configNode.InnerText = getUTF8String(mtb_pwd.Text.Trim());
                    continue;
                }

                if (configValue == "hibernate.connection.username")
                {
                    configNode.InnerText = getUTF8String(tb_user.Text.Trim());
                    continue;
                }

                if (configValue == "hibernate.default_schema")
                {
                    configNode.InnerText = tb_db.Text.Trim();
                    continue;
                }
            }
            xmlReader.Close();
            hibernateDom.Save(hibernateConfigPath);

            //事件服务  --------------------------------------------------------------------------------------------------------------------------------
            tempPath = parentPath + "\\GPRS-Service\\system.ini";
            INIFile iniFileGPRS = new INIFile(tempPath);

            // [system] 配置
            /*IPAddress ipAddr = Dns.Resolve(Dns.GetHostName()).AddressList[0];//获得当前IP地址
            iniFileGPRS.WriteValue("system", "host", ipAddr.ToString());*/

            // [config] 配置
            iniFileGPRS.WriteValue("config", "server", tb_Host.Text.Trim());
            iniFileGPRS.WriteValue("config", "dbname", tb_db.Text.Trim());
            iniFileGPRS.WriteValue("config", "user", tb_user.Text.Trim());
            iniFileGPRS.WriteValue("config", "pwd", mtb_pwd.Text.Trim());
            iniFileGPRS.WriteValue("config", "language", this.language);
            
            // [Connection] 配置
            /*iniFileGPRS.WriteValue("Connection", "DBHost", tb_Host.Text);
            iniFileGPRS.WriteValue("Connection", "DBPWD", mtb_pwd.Text);
            iniFileGPRS.WriteValue("Connection", "DataBase", tb_db.Text);*/
            log("抄表事件服务参数配置完成!");

            //前置机 --------------------------------------------------------------------------------------------------------------------------------
            try
            {
                tempPath = parentPath + "\\Release\\conn.properties";
                FileStream aFile = new FileStream(tempPath, FileMode.Create);
                StreamWriter sw = new StreamWriter(aFile);
                sw.WriteLine("driver = com.mysql.jdbc.Driver");
                sw.WriteLine("url = jdbc:mysql://" + tb_Host.Text.Trim() + ":3306/" + tb_db.Text.Trim() + "?connectTimeout=60&socketTimeout=6000&useSSL=false");
                sw.WriteLine("user = " + tb_user.Text.Trim());
                sw.WriteLine("pwd = " + mtb_pwd.Text.Trim());

                sw.WriteLine("language = " + this.language);
                sw.WriteLine("opcControl = false");
                sw.WriteLine("MControlTiming15 = false");
                sw.WriteLine("MControlTiming60 = false");
                sw.WriteLine("ForWard485 = false");
                sw.WriteLine("LampTiming = false");
                sw.WriteLine("LampDay3761Timing =false");
                sw.WriteLine("TerminalDay3761Timing =false");
                sw.WriteLine("AnalysisOfTunnelElectricity=true");
                sw.Close();

                /*String releasePath = parentPath + "\\Release\\conn.properties";
                String[] datas = Main.load(releasePath);

                if (datas != null)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int c = 0; c < datas.Length; c++)
                    {
                        if (datas[c].Trim() == "")
                        {
                            continue;
                        }
                        if (datas[c].StartsWith("driver"))
                        {
                            datas[c] = "driver = com.mysql.jdbc.Driver";
                        }
                        if (datas[c].StartsWith("url"))
                        {
                            datas[c] = "url = jdbc:mysql://" + tb_Host.Text.Trim() + ":3306/" + tb_db.Text.Trim()
                                + "?connectTimeout=60&socketTimeout=6000&useSSL=false";
                        }
                        if (datas[c].StartsWith("user"))
                        {
                            datas[c] = "user = " + tb_user.Text.Trim();
                        }
                        if (datas[c].StartsWith("pwd"))
                        {
                            datas[c] = "pwd = " + mtb_pwd.Text.Trim();
                        }
                        if (datas[c].StartsWith("language"))
                        {
                            datas[c] = "language = " + this.language;
                        }
                        sb.Append(datas[c].Trim()).Append(System.Environment.NewLine);
                    }
                    File.WriteAllText(releasePath, sb.ToString(), System.Text.Encoding.UTF8);
                }*/

                log("GPRS前置机参数配置完成!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(Properties.Resources.配置抄表服务参数时出现异常 + ":\r\n" + ex.Message.ToString());
                return;
            }

            MessageBox.Show(Properties.Resources.参数已生效 + "，"  + Properties.Resources.请重启服务 + "!",Properties.Resources.提示信息);
        }

        public static string[] load(string file)
        {
            SortedList list = new SortedList();
            string content = null;
            try
            {
                content = File.ReadAllText(file, System.Text.Encoding.UTF8);
            }
            catch (Exception e)
            {
                return null;
            }
            return content.Split('\n');
            
        }

        private string getUTF8String(string s)
        {
            return s;
        }

        private void log(String str)
        {
            Console.WriteLine(str);
        }
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Sqlconn != null)
            {
                if (Sqlconn.State == System.Data.ConnectionState.Open)
                {
                    Sqlconn.Close();
                }
            }
        }

        private void bt_choose_Click_1(object sender, EventArgs e)
        {
            FolderBrowserDialog dlgOpenFolder = new FolderBrowserDialog();
            dlgOpenFolder.SelectedPath = Environment.CurrentDirectory;
            dlgOpenFolder.ShowNewFolderButton = true;
            if (dlgOpenFolder.ShowDialog(this) == DialogResult.OK)
            {
                tb_path.Text = dlgOpenFolder.SelectedPath;
            }
        }

        private void bt_createtask_Click(object sender, EventArgs e)
        {
            if (connectDB().Trim().Length > 0)
            {
                MessageBox.Show(Properties.Resources.请设置正确的数据库参数 + "!",Properties.Resources.提示信息);
                return;
            }

            String backupPath = tb_path.Text.Replace("\\", "/");
            String startTime = dTP_time.Text.Replace(" ", "T");

            // 备份 mysql 数据库
            String batPath = parentPath + "\\DB\\mysql_backup.bat";
            String[] datas = Main.load(batPath);

            if (datas != null)
            {
                StringBuilder sb = new StringBuilder();
                for (int c = 0; c < datas.Length; c++)
                {
                    if (datas[c].Trim() == "")
                    {
                        continue;
                    }
                    if (datas[c].Contains("mysql_backup"))
                    {
                        datas[c] = "mysqldump -u" + tb_user.Text.Trim() + " -p" + mtb_pwd.Text.Trim() + " " + tb_db.Text.Trim()
                                + " -R -E > " + backupPath + "/mysql_backup_%yMd%-%hms%.sql";
                    }

                    sb.Append(datas[c].Trim()).Append(System.Environment.NewLine);
                }
                File.WriteAllText(batPath, sb.ToString(), System.Text.Encoding.UTF8);
            }

            // 清理 7 天前的备份脚本
            String cleanPath = parentPath + "\\DB\\mysql_backup_clean.bat";
            String[] cleanDatas = Main.load(cleanPath);

            if (cleanDatas != null)
            {
                StringBuilder sb = new StringBuilder();
                for (int c = 0; c < cleanDatas.Length; c++)
                {
                    if (cleanDatas[c].Trim() == "")
                    {
                        continue;
                    }
                    if (cleanDatas[c].Contains("forfiles"))
                    {
                        cleanDatas[c] = "forfiles /p \"" + tb_path.Text + "\" /m *.sql /d -7 /c \"cmd /c del @path\"";
                    }

                    sb.Append(cleanDatas[c].Trim()).Append(System.Environment.NewLine);
                }
                File.WriteAllText(cleanPath, sb.ToString(), System.Text.Encoding.UTF8);
            }

            try
            {
                SchTaskExt.CreateTaskScheduler("admin", "backup", batPath, "PT24H", startTime);
                SchTaskExt.CreateTaskScheduler("admin", "backup_clean", cleanPath, "PT24H", startTime);
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message.Trim());
                return;
            }

            /*String strtime = dTP_time.Text.Replace(":","");
            
            //删除 sql
            String sql1 = "IF OBJECT_ID ('dbo.proc_DBMaintaince') IS NOT NULL " +
                 "DROP PROCEDURE dbo.proc_DBMaintaince  ";

            //备份数据库 sql
            String sql2 = "CREATE PROCEDURE proc_DBMaintaince AS " +
                "BEGIN " +
                "DECLARE @sql VARCHAR(1000) " +
                "SET @sql='backup  database  " + tb_db.Text + "  to  disk=''" + tb_path.Text + "\\' +rtrim(convert(CHAR(10),getdate(),112))+'.bak''' " +
                "EXEC(@sql)  " +
                "Print 'Backup operation is completed'  " +
                "SET @sql='del  " + tb_path.Text + "\\'  +rtrim(convert(CHAR(10),getdate()-30,112)) +'.bak' " +
                "EXEC master..xp_cmdshell  @sql " +
                "Print 'Delete operation to complete' " +
                "End ";
             //备份任务 sql
            String sql3 =
                "BEGIN TRANSACTION " +
                "  DECLARE @JobID BINARY(16)  DECLARE @ReturnCode INT " +
                "  SELECT @ReturnCode = 0 " +
                "  SELECT @JobID = job_id FROM   msdb.dbo.sysjobs WHERE (name = N'SAMR database backup') " +
                "  IF (@JobID IS NOT NULL) " +
                "     BEGIN " +
                "          IF (EXISTS (SELECT  * FROM    msdb.dbo.sysjobservers WHERE   (job_id = @JobID) AND (server_id <> 0))) " +
                "             BEGIN " +
                "                 RAISERROR (N'Unable to import the homework“SAMR database backup”，Task name repetition。', 16, 1) " +
                "                 GoTo QuitWithRollback " +
                "              End Else " +
                "                  EXECUTE msdb.dbo.sp_delete_job @job_name = N'SAMR database backup' " +
                "           SELECT @JobID = NULL " +
                "     End " +
                "   EXECUTE @ReturnCode = msdb.dbo.sp_add_job @job_id = @JobID OUTPUT , @job_name = N'SAMR database backup', @owner_login_name = N'sa', @description = N'No description available。', @category_name = N'Database Maintenance', @enabled = 1, @notify_level_email = 0, @notify_level_page = 0, @notify_level_netsend = 0, @notify_level_eventlog = 2, @delete_level= 0 " +
                "   IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback " +
                "   EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID , @step_id = 1, @step_name = N'No.1', @command = N'EXEC proc_DBMaintaince', @database_name = N'samr', @server = N'', @database_user_name = N'', @subsystem = N'TSQL', @cmdexec_success_code = 0, @flags = 4, @retry_attempts = 0, @retry_interval = 0, @output_file_name = N'', @on_success_step_id = 0, @on_success_action = 1, @on_fail_step_id = 0, @on_fail_action = 2 " +
                "   IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback " +
                "   EXECUTE @ReturnCode = msdb.dbo.sp_update_job @job_id = @JobID, @start_step_id = 1 " +
                "   IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback " +
                "   EXECUTE @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id = @JobID, @name = N'No.1-1', @enabled = 1, @freq_type = 4, @active_start_date = 20140101, @active_start_time = " + strtime + ", @freq_interval = 1, @freq_subday_type = 1, @freq_subday_interval = 0, @freq_relative_interval = 0, @freq_recurrence_factor = 0, @active_end_date = 99991231, @active_end_time = 235959 " +
                "   IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback " +
                "   EXECUTE @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @JobID, @server_name = N'(local)' " +
                "   IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback  " +
                "COMMIT TRANSACTION " + 
                "  GoTo EndSave  " +
                "QuitWithRollback: " +
                "  IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION " +
                "EndSave: ";

            try
            {
                thiscommand = new SqlCommand();
                thiscommand.Connection = Sqlconn;

                log(sql1);
                thiscommand.CommandText = sql1;
                thiscommand.ExecuteNonQuery();
                thiscommand.Dispose();

                log(sql2);
                thiscommand.CommandText = sql2;
                thiscommand.ExecuteNonQuery();
                thiscommand.Dispose();

                log(sql3);
                thiscommand.CommandText = sql3;
                thiscommand.ExecuteNonQuery();
                thiscommand.Dispose();
                Sqlconn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Properties.Resources.数据库备份失败 + "!" + ex.Message, Properties.Resources.提示信息);
                return;
            }*/
            MessageBox.Show(Properties.Resources.数据库备份任务创建成功 + "!");

        }
        private void bt_backup_Click(object sender, EventArgs e)
        {
            if (connectDB().Trim().Length > 0)
            {
                MessageBox.Show(Properties.Resources.请设置正确的数据库参数 + "!", Properties.Resources.提示信息);
                return;
            }
            /*String sqlBackUp = "declare " + 
                  "@filename nvarchar(100) set  @filename='"  + tb_path.Text  + "\\'+convert(char(6),getdate(),112)+'.bak' " + 
                  " backup  database  " + tb_db.Text + "  to disk= @filename ";*/
               
            try
            {
                /*thiscommand = new SqlCommand();
                thiscommand.Connection = Sqlconn;
                thiscommand.CommandText = sqlBackUp;
                thiscommand.ExecuteNonQuery();

                thiscommand.Dispose();
                Sqlconn.Close();*/

                Process p = new Process();
                //设置要启动的应用程序
                p.StartInfo.FileName = "cmd.exe";
                //是否使用操作系统shell启动
                p.StartInfo.UseShellExecute = false;
                // 接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardInput = true;
                //输出信息
                p.StartInfo.RedirectStandardOutput = true;
                // 输出错误
                p.StartInfo.RedirectStandardError = true;
                //不显示程序窗口
                p.StartInfo.CreateNoWindow = true;
                //启动程序
                p.Start();

                String backupPath = tb_path.Text.Replace("\\", "/");

                String sqlPath = backupPath + "/mysql_backup.sql";
                //向cmd窗口发送输入信息
                p.StandardInput.WriteLine("mysqldump --no-data -u" + tb_user.Text.Trim() + " -p" + mtb_pwd.Text.Trim() + " --databases samr > " + sqlPath);

                p.StandardInput.AutoFlush = true;

                //获取输出信息
                // string strOuput = p.StandardOutput.ReadToEnd();
                //等待程序执行完退出进程
                // p.WaitForExit();
                p.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(Properties.Resources.数据库备份失败 + "!"
                    + ex.Message
                    // + "\r\n "  + sqlBackUp
                    ,Properties.Resources.提示信息);
                return;
            }
            MessageBox.Show(Properties.Resources.数据库备份成功 + "!");
        }

        
        private void setJavaParameter()
        {
            string jdkPath = string.Empty;
            if (bit64)
            {
                jdkPath = parentPath + "\\Java\\jdk1.7_64";
            }
            else
            {
                jdkPath = parentPath + "\\Java\\jdk1.7_32";
            }

            SysEnvironment sysEnvironment = new SysEnvironment();
            log(jdkPath);
            //JAVA_HOME
            sysEnvironment.SetSysEnvironment("JAVA_HOME", jdkPath);
            //CLASSPATH
            sysEnvironment.SetSysEnvironment("CLASSPATH", "%JAVA_HOME%\\lib;%JAVA_HOME%\\lib\\dt.jar;%JAVA_HOME%\\lib\\tools.jar;");
            //Path 
            sysEnvironment.SetPathAfter("%JAVA_HOME%\\bin");

            log("JAVA_HOME");
            log(sysEnvironment.GetSysEnvironmentByName("JAVA_HOME"));
            log("CLASSPATH");
            log(sysEnvironment.GetSysEnvironmentByName("CLASSPATH"));
            log("PATH");
            log(sysEnvironment.GetSysEnvironmentByName("PATH"));

        }

        private void button1_Click(object sender, EventArgs e)
        {
            setJavaParameter();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            
            
        }
        /// <summary>
        /// 取消开机启动，删除注册表中的值
        /// </summary>
        public void CancleAutoRun()
        {
            try
            {
                string filepath = Assembly.GetExecutingAssembly().Location;
                string runName = Path.GetFileNameWithoutExtension(filepath);
                RegistryKey hkml = Registry.LocalMachine;
                RegistryKey runKeys = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                runKeys.DeleteValue(runName);
            }
            catch
            { }
        }
        /// <summary>
        /// 写进注册表，以便开机启动
        /// </summary>
        private void SetAutoStar()
        {
            try
            {
                string filepath = Assembly.GetExecutingAssembly().Location;
                string runName = Path.GetFileNameWithoutExtension(filepath);

                RegistryKey hkml = Registry.LocalMachine;
                RegistryKey runKey = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                runKey.SetValue(runName, filepath);
                runKey.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void Main_Shown(object sender, EventArgs e)
        {
            if (autoRun) //自动运行
            {
                timer1.Enabled = true;
                
               // startServiceAll();
              //  MessageBox.Show("autoRun!!", "提示", MessageBoxButtons.OK);
               
            }
               
        }

        private void checkBox1_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkBox1.Checked)
                //添加到注册表中
                {
                    SetAutoStar();
                    //保存参数
                }
                else
                //删除注册表信息
                {
                    CancleAutoRun();
                }
                String fileName = Directory.GetCurrentDirectory();
                fileName += "\\system.ini";
                INIFile iniFile = new INIFile(fileName);
                iniFile.WriteValue("config", "autoRun", checkBox1.Checked);
            }
            catch
            {
            }
        }

        private void cb1_CheckedChanged(object sender, EventArgs e)
        {
            if (cb1.Checked)
            {
                this.language = "en";
            }
            else
            {
                this.language = "";
            }
            ApplyResource();
            saveConfig();
        }

        private void ApplyResource()
        {

            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.language);
            res = new ComponentResourceManager(typeof(Main));
            foreach (Control ctl in Controls)
            {
                res.ApplyResources(ctl, ctl.Name);
            }
            res.ApplyResources(this, "$this");

            res.ApplyResources(bt_start, bt_start.Name);
            res.ApplyResources(bt_stop, bt_stop.Name);
            res.ApplyResources(label1, label1.Name);
            res.ApplyResources(label2, label2.Name);
            res.ApplyResources(label3, label3.Name);
            res.ApplyResources(label5, label5.Name);
            res.ApplyResources(bt_test, bt_test.Name);
            res.ApplyResources(btapply, btapply.Name);
            res.ApplyResources(label4, label4.Name);
            res.ApplyResources(label6, label6.Name);
            res.ApplyResources(label7, label7.Name);
            res.ApplyResources(bt_backup, bt_backup.Name);
            res.ApplyResources(bt_createtask, bt_createtask.Name);
            res.ApplyResources(cb1, cb1.Name);
            res.ApplyResources(checkBox1, checkBox1.Name);
            res.ApplyResources(baseurl_label, baseurl_label.Name);
            res.ApplyResources(groupBox6, groupBox6.Name);
            res.ApplyResources(cameraUrl_label, cameraUrl_label.Name);
            res.ApplyResources(groupBox4, groupBox4.Name);
            res.ApplyResources(button1, button1.Name);
            res.ApplyResources(button4, button4.Name);
            res.ApplyResources(label10, label10.Name);
            res.ApplyResources(label8, label8.Name);
            res.ApplyResources(mysql_install, mysql_install.Name);
            res.ApplyResources(java_env_setting, java_env_setting.Name);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            startServiceAll();
        }

        private void label11_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (baseUrl.Text.Trim() == "")
            {
                MessageBox.Show(Properties.Resources.请设置服务器地址 + "!");
                return;
            }

            if (cameraUrl.Text.Trim() == "")
            {
                MessageBox.Show(Properties.Resources.请设置流媒体地址 + "!");
                return;
            }
            String frontPath = parentPath + "\\nginx-1.18.0\\html\\mysql\\serverconfig.json";
            String json = File.ReadAllText(frontPath, Encoding.Default);
            /*JObject jOject = JObject.Parse(json);
            jOject["baseUrl"] = baseUrl.Text.Trim();//替换需要的文件
            jOject["cameraUrl"] = cameraUrl.Text.Trim();
            string convertString = Convert.ToString(jOject);//将json装换为string*/

            StringBuilder sb = new StringBuilder();
            sb.Append("{\"baseUrl\":\"http://" + baseUrl.Text.Trim() + "/WebContent\"," +
                "\"cameraUrl\":\"http://" + cameraUrl.Text.Trim() + "/nvc/LiveNVR001/api/v1\",\"qrcode\":true}").Append(System.Environment.NewLine);
            File.WriteAllText(frontPath, sb.ToString(), System.Text.Encoding.UTF8);

            // 修改 nginx.conf 配置
            String nginxPath = parentPath + "\\nginx-1.18.0\\conf\\nginx.conf";
            String nginxTempPath = parentPath + "\\nginx-1.18.0\\conf\\nginx-temp.conf";
            File.Copy(nginxPath, nginxTempPath, true);

            FileStream fsReader = new FileStream(nginxTempPath, FileMode.OpenOrCreate, FileAccess.Read);
            StreamReader sr = new StreamReader(fsReader, Encoding.Default);

            FileStream fsWriter = new FileStream(nginxPath, FileMode.Create, FileAccess.Write);
            StreamWriter ngSw = new StreamWriter(fsWriter, Encoding.Default);

            // String[] ips = baseUrl.Text.Trim().Split(':');
            String tempStr = "";
            string str = string.Empty;
            while ((str = sr.ReadLine()) != null)
            {
                if (tempStr.Contains("WebContent"))
                {
                    // str = "\t\t\tproxy_pass\t http://" + ips[0] + ":8081;";
                    str = "\t\t\tproxy_pass\t http://" + baseUrl.Text.Trim() + ";";
                }
                ngSw.WriteLine(str);
                tempStr = str;
            }
            ngSw.Flush();
            ngSw.Close();
            sr.Close();

            MessageBox.Show(Properties.Resources.保存前端连接参数成功 + "!");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("保存连接数据库信息成功!");
        }

        private void tb_db_TextChanged(object sender, EventArgs e)
        {

        }

        private void mtb_pwd_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Process proc = null;
            try
            {
                String batPath = parentPath + "Java\\";
                string targetDir = string.Format(@batPath);//this is where testChange.bat lies
                proc = new Process();
                proc.StartInfo.WorkingDirectory = targetDir;
                proc.StartInfo.FileName = "installJDK.bat";
                //proc.StartInfo.Arguments = string.Format("10");//this is argument
                //proc.StartInfo.CreateNoWindow = true;
                //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示，经实践可行
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            Process proc = null;
            try
            {
                String batPath = parentPath + "mysql-5.5.23\\";
                string targetDir = string.Format(@batPath);//this is where testChange.bat lies
                proc = new Process();
                proc.StartInfo.WorkingDirectory = targetDir;
                proc.StartInfo.FileName = "MySQL_install.bat";
                //proc.StartInfo.Arguments = string.Format("10");//this is argument
                //proc.StartInfo.CreateNoWindow = true;
                //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示，经实践可行
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                String tempPath = parentPath + "\\GPRS-Service\\system.ini";
                INIFile iniFileGPRS = new INIFile(tempPath);

                // [system] 配置
                iniFileGPRS.WriteValue("system", "host", gprs_ip.Text.Trim());// 设置 GPRS IP

                log("抄表事件服务参数配置完成!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(Properties.Resources.配置抄表服务参数时出现异常 + ":\r\n" + ex.Message.ToString());
                return;
            }
            MessageBox.Show(Properties.Resources.参数已生效 + "，" + Properties.Resources.请重启服务 + "!", Properties.Resources.提示信息);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label8_Click(object sender, EventArgs e)
        {

        }
    }
}
