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 Microsoft.Win32;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Management;
using System.Text.RegularExpressions;
using System.Threading;
using System.Net.NetworkInformation;

namespace GcDevicePc
{
    public partial class UserConfig : Form
    {
     
        public UserConfig()
        {
            InitializeComponent();
        }

        private void autorun_CheckedChanged(object sender, EventArgs e)
        {
            string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder + "\\startup.ini";
            INIOperation test = new INIOperation(file);
            int count = 0;

              if ((sender as CheckBox).Checked == true) 
              { 
                  foreach (CheckBox chk in this.groupBox3.Controls) 
                  { 
                      if (chk != sender)
                          chk.Checked = false;                          
                  }

                 if( int.Parse((sender as CheckBox).Tag.ToString()) == 0)
                 {
                     test.INIWriteValue(file, "StartUp", "打开系统", "1");
                     test.INIWriteValue(file, "StartUp", "运行类型", "0");

                 }else if( int.Parse((sender as CheckBox).Tag.ToString()) == 1)
                 {
                     test.INIWriteValue(file, "StartUp", "打开系统", "1");
                     test.INIWriteValue(file, "StartUp", "运行类型", "1");
                 }else if( int.Parse((sender as CheckBox).Tag.ToString()) == 2)
                 {
                     test.INIWriteValue(file, "StartUp", "打开系统", "1");
                     test.INIWriteValue(file, "StartUp", "运行类型", "2");
                 }else
                 {
                     test.INIWriteValue(file, "StartUp", "打开系统", "0");
                     test.INIWriteValue(file, "StartUp", "运行类型", "0");
                 }
              }

              foreach (CheckBox chk in this.groupBox3.Controls)
              {
                  if (chk.Checked == false)
                      count++;
              }

              if (count == 3)
              {
                  test.INIWriteValue(file, "StartUp", "打开系统", "0");
                  test.INIWriteValue(file, "StartUp", "运行类型", "0");
              }
        }

        private void appstartup_CheckedChanged(object sender, EventArgs e)
        {
            string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder + "\\startup.ini";
            INIOperation test = new INIOperation(file);
            string value;
            if(this.appstartup.Checked)
            {
                value = test.INIGetStringValue("StartUp", "自启动", null);
                if (Convert.ToInt32(value) != 1)
                {
                    MessageBox.Show("设置开机自启动，需要修改注册表", "提示");
                    test.INIWriteValue(file, "StartUp", "自启动", "1");
                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.LocalMachine;
                    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                    rk2.SetValue("JcShutdown", path);
                    rk2.Close();
                    rk.Close();
                }
                
            }else
            {
                MessageBox.Show("取消开机自启动，需要修改注册表", "提示");
                test.INIWriteValue(file, "StartUp", "自启动", "0");
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.DeleteValue("JcShutdown", false);
                rk2.Close();
                rk.Close();
            }
        }

        private bool ChosenAdapter(string localip)
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                if (adapter.Name == "本地连接")
                {
                    bool Pd1 = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet); //判断是否是以太网连接
                    if (Pd1)
                    {
                        {
                            IPInterfaceProperties ip = adapter.GetIPProperties();     //IP配置信息
                            UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                            foreach (UnicastIPAddressInformation ipadd in ipCollection)
                            {
                                if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    if(localip == ipadd.Address.ToString())
                                    {
                                        return true;
                                    }
                                } 
                            }
                        }
                    }
                }              
            }
            return false;
        }


        private void UserConfig_Load(object sender, EventArgs e)
        {
            string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder + "\\startup.ini";
            INIOperation test = new INIOperation(file);
            string MAC = test.INIGetStringValue("NetWorkConfig", "MAC地址", null);
            string value = test.INIGetStringValue("StartUp", "自启动", null);
            string opensys = test.INIGetStringValue("StartUp", "打开系统", null);
            string runtype = test.INIGetStringValue("StartUp", "运行类型", null);

            string info_log = test.INIGetStringValue("Logs", "InfoLog", null);
            string err_log = test.INIGetStringValue("Logs", "ErrLog", null);
            string hmi_log = test.INIGetStringValue("Logs", "HmiLog", null);

            if (String.IsNullOrEmpty(MAC))
            {
                this.label1.Text = "目前Mac(未绑定)：";
                this.label3.Text = ((globaldata.DeviceInfo) globaldata.DeviceList[0]).MacAddr;
            }
            else
            {
                this.label3.Text = MAC;
            }

            if (Convert.ToInt32(value) == 1)
            {
                this.appstartup.Checked = true;
            }else
            {
                this.appstartup.Checked = false;
            }

            if (Convert.ToInt32(opensys) == 1)
            {
                if(Convert.ToInt32(runtype) == 0)
                {
                    this.runsingle.Checked = true;
                }
                else if (Convert.ToInt32(runtype) == 2)
                {
                    this.runbat.Checked = true;
                }
            }

            if (Convert.ToInt32(hmi_log) == 1)
            {
                this.permin.Checked = true;
            }
            else
            {
                this.permin.Checked = false;
            }

            if(globaldata.DeviceList.Count > 0)
            {
                this.hmiip.Text = ((globaldata.DeviceInfo)globaldata.DeviceList[0]).IpAddr;
                this.hmigw.Text = ((globaldata.DeviceInfo)globaldata.DeviceList[0]).Gateway;
                this.hminm.Text = ((globaldata.DeviceInfo)globaldata.DeviceList[0]).Netmask;
            }
        
            try
            {
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection nics = mc.GetInstances();
                foreach (ManagementObject nic in nics)
                {
                    if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                    {
                        string ip = (nic["IPAddress"] as String[])[0];//IP地址
                        string ipsubnet = (nic["IPSubnet"] as String[])[0];//子网掩码
                        string ipgateway = (nic["DefaultIPGateway"] as String[])[0];//默认网关
                        if (ip != null && ChosenAdapter(ip))
                        {
                            this.localip.Text = ip;
                            this.localgw.Text = ipgateway;
                            this.localnm.Text = ipsubnet;
                            break;
                        }
                        else
                        {
                            continue;
                        }

                    }
                }
            }
            catch
            {

            }

            

            //string AddressIP = string.Empty;
            //string IPGateWay = string.Empty;
            //string IPSubNet = string.Empty;
            //foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            //{
            //    if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
            //    {
            //        AddressIP = _IPAddress.ToString();
            //    }

            //    if (_IPAddress.AddressFamily.ToString() == "IPSubnet")
            //    {
            //        IPSubNet = _IPAddress.ToString();
            //    }

            //    if (_IPAddress.AddressFamily.ToString() == "DefaultIPGateway")
            //    {
            //        IPGateWay = _IPAddress.ToString();
            //    }

            //}
           
        }

        private void CaseNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else
            {
                if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || e.KeyChar == 8)
                {
                    e.Handled = false;
                }
                else
                {
                    if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || e.KeyChar == 8)
                    {
                        e.Handled = false;
                    }
                    else e.Handled = true;
                }
            }
        }

        private void changemac_Click(object sender, EventArgs e)
        {
            bool ret = false;
            string newMac = string.Format(String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}",mac1.Text,mac2.Text,mac3.Text,mac4.Text,mac5.Text,mac6.Text));

            string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder + "\\startup.ini";
            INIOperation test = new INIOperation(file);
            ret = test.INIWriteValue(file, "NetWorkConfig", "MAC地址", newMac);

            if (ret)
            {
                MessageBox.Show("MAC绑定修改成功！", "提示");
            }else
            {
                MessageBox.Show("MAC绑定修改失败！", "提示");
            }
        }

        private void changip_Click(object sender, EventArgs e)
        {
            UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
            IPEndPoint endpoint =new IPEndPoint(IPAddress.Parse("255.255.255.255"), 233);;
         
            byte[] headBytes = new byte[] { 0x57, 0x54, 0x14, 0x00, 0x00, 0x00, 0x06, 0x00 };
            byte[] endBytes = new byte[] { 0x55, 0xAA };

            string myIP;
            string myMask;
            string myGW;
            myIP = this.hmiip.Text;
            myGW = this.hmigw.Text;
            myMask = this.hminm.Text;

            if (!IsIPAddress(myIP) || !IsIPAddress(myGW))
            {
                MessageBox.Show("请确认修改相关地址格式！", "提示");
                return;
            }

            int i = 0;

            string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder + "\\startup.ini";
            INIOperation test = new INIOperation(file);
            string myMAC = test.INIGetStringValue("NetWorkConfig", "MAC地址", null);
            try
            {
                byte[] sMac = new byte[6];

                string[] sMAC = myMAC.Split(':');
                for (i = 0; i < 6; i++)
                    sMac[i] = Convert.ToByte(sMAC[i],16);

            //sMac[0] = m_pWUEthInfo.byteMacAddr[0];
            //sMac[1] = m_pWUEthInfo.byteMacAddr[1];
            //sMac[2] = m_pWUEthInfo.byteMacAddr[2];
            //sMac[3] = m_pWUEthInfo.byteMacAddr[3];
            //sMac[4] = m_pWUEthInfo.byteMacAddr[4];
            //sMac[5] = m_pWUEthInfo.byteMacAddr[5];

                byte[] update = new byte[12];

                string[] sIP = myIP.Split('.');
                for (i = 0; i < 4; i++)
                    update[i] = Convert.ToByte(sIP[i]);


                string[] sMask = myMask.Split('.');
                for (i = 0; i < 4; i++)
                    update[i + 4] = Convert.ToByte(sMask[i]);

                string[] sGW = myGW.Split('.');
                for (i = 0; i < 4; i++)
                    update[i + 8] = Convert.ToByte(sGW[i]);

                byte[] sendBytes = new Byte[headBytes.Length + sMac.Length + update.Length + endBytes.Length];
                headBytes.CopyTo(sendBytes, 0);
                sMac.CopyTo(sendBytes, headBytes.Length);
                update.CopyTo(sendBytes, headBytes.Length + sMac.Length);
                endBytes.CopyTo(sendBytes, headBytes.Length + sMac.Length + update.Length);
           
                client.Send(sendBytes, sendBytes.Length, endpoint);
                MessageBox.Show("IP修改成功！", "提示");

                DialogResult result = MessageBox.Show("IP修改成功，确定重启IP软件嘛？", "提示信息", MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {
                    Application.ExitThread();
                    Application.Exit();
                    Application.Restart();
                    Process.GetCurrentProcess().Kill();  
                }                                
            }
            catch (Exception)
            {
                if (myIP == null || myGW == null || myMask == null)
                {
                    MessageBox.Show("请检查IP,网关,掩码是否正确！", "提示");
                }else
                {
                    MessageBox.Show("IP修改失败！", "提示");
                }              
            }           
        }


        public static bool IsIPAddress(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        private void changeip()
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            string myip = localip.Text;
            string mynm = localnm.Text;
            string mygw = localgw.Text;

            if (!IsIPAddress(myip) || !IsIPAddress(mygw))
            {
                MessageBox.Show("请确认修改相关地址格式！", "提示");
                return;
            }

            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                {
                    // MessageBox.Show("已检测到网卡，但无法设置。请检查网卡优先性并确认是否已被禁用或已插网线。");
                    continue;
                }

                //设置ip地址和子网掩码 
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = new string[] { myip };
                inPar["SubnetMask"] = new string[] { mynm };
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);

                //设置网关地址 
                inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = new string[] { mygw };
                outPar = mo.InvokeMethod("SetGateways", inPar, null);

                //设置DNS   
                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = new string[] { "8.8.8.8", "114.114.114.114" };
                outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                break;
            }
        }

        Thread th_changeip;



        private void changelocal_Click(object sender, EventArgs e)
        {
            try
            {
                int count = 0; ;
                th_changeip = new Thread(changeip);
                th_changeip.IsBackground = true;
                th_changeip.Start();
                ManagementClass mc;
                while(true)
                {
                    string ip = string.Empty;
                    string ipsubnet = string.Empty;
                    string ipgateway = string.Empty; 
                    mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection nics = mc.GetInstances();
                    foreach (ManagementObject nic in nics)
                    {
                        if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                        {
                            ip = (nic["IPAddress"] as String[])[0];//IP地址
                            ipsubnet = (nic["IPSubnet"] as String[])[0];//子网掩码
                            ipgateway = (nic["DefaultIPGateway"] as String[])[0];//默认网关             
                        }
                    }

                    if(this.localip.Text == ip && this.localgw.Text == ipgateway && this.localnm.Text == ipsubnet)
                    {
                        break;   
                    }
                    Thread.Sleep(200);
                    count++;
                    if (count == 20)
                        break;
                }
              
                if(count == 10)
                {
                    MessageBox.Show("本机IP修改失败！", "提示"); 
                }else
                {
                    DialogResult result = MessageBox.Show("修改完成，是否重启PC软件？", "提示信息", MessageBoxButtons.OKCancel);
                    if (result == DialogResult.OK)
                    {
                        Application.ExitThread();
                        Application.Exit();
                        Application.Restart();
                        Process.GetCurrentProcess().Kill();
                    }                             
                }
            }
            catch (Exception)
            {
                MessageBox.Show("本机IP修改失败！", "提示");               
            }
        }

        /// <summary>
        /// 分钟数据记录开关
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void permin_CheckedChanged(object sender, EventArgs e)
        {
            string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder + "\\startup.ini";
            try
            {
                INIOperation test = new INIOperation(file);
                if (this.permin.Checked == true)
                {
                    test.INIWriteValue(file, "Logs", "HmiLog", "0");
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.hmi_log = false;
                }
                else
                {
                    test.INIWriteValue(file, "Logs", "HmiLog", "1");
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.hmi_log = true;
                }
            }
            catch
            {

            }
        }
    }
}
