using GcDevicePc.Common;
using Ini.Net;
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GcDevicePc
{
    public delegate void UpdataHMIOS(int index,ushort val);
    public delegate void UpdataHMIOpS(ushort val);
    public partial class SysConfig : Form
    {
        private string HmiIP = null;
        private ushort HmiPort = 911;
        private ArrayList SearchRet = new ArrayList();
        public SysConfig()
        {
            InitializeComponent();
        }
        public SysConfig(ushort[] val)
        {
            InitializeComponent();
            checkBox4.Checked = val[0] == 0 ? false : true;
            checkBox8.Checked = val[1] == 0 ? false : true;
            checkBox4.CheckedChanged += CheckBox4_CheckedChanged;
            checkBox8.CheckedChanged += CheckBox8_CheckedChanged1;

        }
        public event UpdataHMIOS uphos;

        private void CheckBox8_CheckedChanged1(object sender, EventArgs e)
        {
            ushort val = checkBox8.Checked ? (ushort)1 : (ushort)0;
            uphos(1, val);
        }

        private void CheckBox4_CheckedChanged(object sender, EventArgs e)
        {
            ushort val = checkBox4.Checked ? (ushort)1 : (ushort)0;
            uphos(0, val);
        }

        private void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void Thirdparty_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void Foreign_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.Graphics.FillRectangle(new SolidBrush(e.BackColor), e.Bounds);
            if (e.Index >= 0)
            {
                StringFormat sStringFormat = new StringFormat();
                sStringFormat.LineAlignment = StringAlignment.Center;
                e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, sStringFormat);
            }
            e.DrawFocusRectangle();
        }

        private void ListBox1_MeasureItem(object sender, MeasureItemEventArgs e)
        {
            e.ItemHeight += 12;
        }

        private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            panel1.Visible = false;
            panel2.Visible = false;
            panel3.Visible = false;
            panel5.Visible = false;
            panel6.Visible = false;
            if (this.listBox1.SelectedIndex == 0)
            {
                panel1.Visible = true;
            }
            else if (this.listBox1.SelectedIndex == 1)
            {
                panel2.Visible = true;
            }
            else if (this.listBox1.SelectedIndex == 2)
            {
                panel3.Visible = true;
            }
            else if (this.listBox1.SelectedIndex == 3)
            {
                panel5.Visible = true;
            }
            else if (this.listBox1.SelectedIndex == 4)
            {
                panel6.Visible = true;
            }
        }

        private void SysConfig_Load(object sender, EventArgs e)
        {
            this.CHmibtn.Enabled = false;
            this.runbtn.Enabled = false;
            this.chosenbtn.Enabled = false;
            this.updatebtn.Enabled = false;
            string file = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.StartupPath), "GC_Config\\GC_Set\\启动参数\\startup.ini");
            if (File.Exists(file))
            {
                IniFile ini = new IniFile(file);

                string value = ini.ReadString("StartUp", "自启动");
                string opensys = ini.ReadString("StartUp", "打开系统");
                string runtype = ini.ReadString("StartUp", "运行类型");
                string info_log = ini.ReadString("Logs", "InfoLog");
                string err_log = ini.ReadString("Logs", "ErrLog");
                string hmi_log = ini.ReadString("Logs", "HmiLog");

                int Version = ini.ReadInteger("Version", "VersionType");
                string appname = ini.ReadString("Version", "AppName");
                string uname = ini.ReadString("User", "Name");
                string upwd = ini.ReadString("User", "Password");
                
                int dsf = ini.ReadInteger("SendData", "Thirdparty");
                int dw = ini.ReadInteger("SendData", "Foreign");
                int sdzb = ini.ReadInteger("SaveData", "ZBSaveData");
                int fi = ini.ReadInteger("StartUp", "Forceintegral");

                string sp = ini.ReadString("StartUp", "space");
                string dt = ini.ReadString("StartUp", "Datetime");

                switch (Version)
                {
                    case 0:
                        radioButton9.Checked = true;
                        break;
                    case 1:
                        radioButton8.Checked = true;
                        break;
                    default:
                        radioButton8.Checked = true;
                        break;
                }

                this.textBox9.Text = appname;

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

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

                if (fi == 1)
                {
                    this.checkBox2.Checked = true;
                }
                else
                {
                    this.checkBox2.Checked = false;
                }

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

                //if (Version == 1)
                //{
                //    this.checkBox1.Checked = true;
                //}
                //else
                //{
                //    this.checkBox1.Checked = false;
                //}

                textBox1.Text = uname;
                textBox2.Text = upwd;
                textBox3.Text = upwd;

                textBox8.Text = sp;
                textBox7.Text = dt;

                switch (dsf)
                {
                    case 0:
                        radioButton2.Checked = true;
                        break;
                    case 1:
                        radioButton1.Checked = true;
                        break;
                    case 2:
                        radioButton3.Checked = true;
                        break;
                    default:
                        radioButton4.Checked = true;
                        break;
                }

                switch (dw)
                {
                    case 0:
                        radioButton5.Checked = true;
                        break;
                    case 1:
                        radioButton6.Checked = true;
                        break;
                    default:
                        radioButton7.Checked = true;
                        break;
                }

                checkBox3.Checked = sdzb == 1 ? true : false;
            }
            else
            {

            }
            listBox1.SelectedIndex = 0;
        }
        public event UpdataHMIOpS uphops;
        private void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                uphops(2);

            }
            catch 
            {

            }

            try
            {
                string file = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.StartupPath), "GC_Config\\GC_Set\\启动参数\\startup.ini");
                if (File.Exists(file))
                {
                    IniFile ini = new IniFile(file);


                    if (appstartup.Checked)
                    {
                        ini.WriteString("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
                    {
                        ini.WriteString("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();
                    }

                    if (runbat.Checked)
                    {
                        ini.WriteString("StartUp", "打开系统", "1");
                        ini.WriteString("StartUp", "运行类型", "2");
                    }
                    else if (runsingle.Checked)
                    {
                        ini.WriteString("StartUp", "打开系统", "1");
                        ini.WriteString("StartUp", "运行类型", "1");
                    }
                    else
                    {
                        ini.WriteString("StartUp", "打开系统", "0");
                        ini.WriteString("StartUp", "运行类型", "0");
                    }

                    if (checkBox2.Checked)
                    {
                        ini.WriteString("StartUp", "Forceintegral", "1");
                    }
                    else
                    {
                        ini.WriteString("StartUp", "Forceintegral", "0");
                    }

                    if (radioButton8.Checked)
                    {
                        ini.WriteString("Version", "VersionType", "1");
                    }
                    else if (radioButton9.Checked)
                    {
                        ini.WriteString("Version", "VersionType", "0");
                    }

                    ini.WriteString("Version", "AppName", this.textBox9.Text);

                    if (this.permin.Checked)
                    {
                        ini.WriteString("Logs", "HmiLog", "1");
                        globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.hmi_log = true;
                        ini.WriteString("Logs", "InfoLog", "1");
                        globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.info_log = true;
                        ini.WriteString("Logs", "ErrLog", "1");
                        globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.error_log = true;
                    }
                    else
                    {
                        ini.WriteString("Logs", "HmiLog", "0");
                        globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.hmi_log = false;
                        ini.WriteString("Logs", "InfoLog", "0");
                        globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.info_log = false;
                        ini.WriteString("Logs", "ErrLog", "0");
                        globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.error_log = false;
                    }

                    if (radioButton1.Checked)
                    {
                        ini.WriteString("SendData", "Thirdparty", "1");//zb
                    }
                    else if (radioButton2.Checked)
                    {
                        ini.WriteString("SendData", "Thirdparty", "0");//hl
                    }
                    else if (radioButton3.Checked)
                    {
                        ini.WriteString("SendData", "Thirdparty", "2");//sp
                    }
                    else
                    {
                        ini.WriteString("SendData", "Thirdparty", "3");//无
                    }


                    if (radioButton5.Checked)
                    {
                        ini.WriteString("SendData", "Foreign", "0");//默认
                    }
                    else if (radioButton6.Checked)
                    {
                        ini.WriteString("SendData", "Foreign", "1");//环空
                    }
                    else
                    {
                        ini.WriteString("SendData", "Foreign", "2");//无
                    }

                    if (checkBox3.Checked)
                    {
                        ini.WriteString("SaveData", "ZBSaveData", "1");
                    }
                    else
                    {
                        ini.WriteString("SaveData", "ZBSaveData", "0");
                    }
                    if (string.IsNullOrEmpty(textBox8.Text))
                    {
                        ini.WriteString("StartUp", "space", "500");

                    }
                    else
                    {
                        ini.WriteString("StartUp", "space", textBox8.Text);

                    }

                    if (string.IsNullOrEmpty(textBox7.Text))
                    {
                        ini.WriteString("StartUp", "Datetime", "30");

                    }
                    else
                    {
                        ini.WriteString("StartUp", "Datetime", textBox7.Text);

                    }
                    

                    if (label4.Visible || label5.Visible || label6.Visible)
                    {
                        MessageBox.Show("请确保安全性");
                        return;
                    }
                    else
                    {
                        ini.WriteString("User", "Name", textBox1.Text);
                        ini.WriteString("User", "Password", textBox3.Text);
                    }

                    this.Close();
                }
                else
                {
                    MessageBox.Show("配置保存失败");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

        }

        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                label4.Visible = true;
                label4.Text = "不能为空";
            }
            else
            {
                label4.Visible = false;
                label4.Text = "";
            }
        }

        private void TextBox2_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox2.Text))
            {
                label5.Visible = true;
                label5.Text = "不能为空";
            }
            else
            {
                label5.Visible = false;
                label5.Text = "";
            }
        }

        private void TextBox3_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox3.Text))
            {
                label6.Visible = true;
                label6.Text = "不能为空";
            }
            else if (!textBox3.Text.Equals(textBox2.Text))
            {
                label6.Visible = true;
                label6.Text = "密码不一致";
            }
            else
            {
                label6.Visible = false;
                label6.Text = "";
            }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Runbat_CheckedChanged(object sender, EventArgs e)
        {
            if (runbat.Checked)
            {
                runsingle.Checked = false;
            }
        }

        private void Runsingle_CheckedChanged(object sender, EventArgs e)
        {
            if (runsingle.Checked)
            {
                runbat.Checked = false;
            }
        }

        private void CheckBox2_CheckedChanged(object sender, EventArgs e)
        {
            CKVocAnalyzer.GlobalCKV.vocAlgorithm.Forceintegral = checkBox2.Checked;
        }


        bool hmisearch = false;
        Thread addhmi;
        ManualResetEvent mre = new ManualResetEvent(false);
        private void searchHMI_Click(object sender, EventArgs e)
        {
            ArrayList DeviceList = new ArrayList();
            if (!hmisearch)
            {
                if (mre != null)
                    mre.Reset();
                addhmi = new Thread(searchhmi);
                addhmi.IsBackground = true;
                addhmi.Start();
                this.searchHMI.Text = "停止";
                hmisearch = !hmisearch;
            }
            else
            {
                this.searchHMI.Text = "搜索";
                this.hmilist.Text = "请选择...";
                mre.Set();
                hmisearch = !hmisearch;
            }
        }

        private void hmilist_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.HmiIP = this.hmilist.Text;

            this.CHmibtn.Enabled = true;
        }

        private string updateexe = null;
        private string localpath = null;
        private void CHmibtn_Click(object sender, EventArgs e)
        {
            if (HmiIP != null)
            {
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == false)
                {
                    this.CHmibtn.Enabled = false;
                    int ret = 0;
                    FileServerClient singlesend = new FileServerClient();
                    singlesend.WtClientInit(HmiIP, HmiPort);
                    ret = singlesend.WtHMICloseRro("WtMainProc");
                    if (ret == 1)
                    {
                        MessageBox.Show("停止系统成功！");
                    }

                    singlesend.WtClientClose();
                    // this.runbtn.Enabled = true;
                    this.chosenbtn.Enabled = true;
                    this.updatebtn.Enabled = true;

                }
                else
                {
                    MessageBox.Show("请停止系统，再关闭！");
                }


            }
        }

        private void runbtn_Click(object sender, EventArgs e)
        {
            int ret;
            if (HmiIP != null)
            {
                FileServerClient singlesend = new FileServerClient();
                singlesend.WtClientInit(HmiIP, HmiPort);
                ret = singlesend.WtHMIRunPro("GcDevice.exe", globaldata.exeremoteFolder);
                if (ret == 1)
                {
                    MessageBox.Show("开启系统成功！");
                }
                singlesend.WtClientClose();

                this.runbtn.Enabled = false;
                this.chosenbtn.Enabled = false;
                this.updatebtn.Enabled = false;
                this.CHmibtn.Enabled = true;

                this.label4.Text = "";
                this.progressBar1.Value = 0;
                this.ProName.Text = "";
            }
        }

        private void chosenbtn_Click(object sender, EventArgs e)
        {
            string file;
            OpenFileDialog fileDlg = new OpenFileDialog();
            fileDlg.Multiselect = false;
            fileDlg.InitialDirectory = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.TmpFolder;
            fileDlg.RestoreDirectory = true;
            fileDlg.Title = "请选择方法文件";
            fileDlg.Filter = "更新程序(*.*)|*.*";
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                file = fileDlg.FileName;
                this.updateexe = file.Substring(file.LastIndexOf("\\") + 1);
                this.localpath = file;
                this.ProName.Text = this.localpath;
                this.updatebtn.Enabled = true;

            }
        }

        private void updatebtn_Click(object sender, EventArgs e)
        {
            if (HmiIP != null)
            {
                this.CHmibtn.Enabled = false;
                this.runbtn.Enabled = false;
                this.chosenbtn.Enabled = false;
                this.updatebtn.Enabled = false;


                Thread fThread = new Thread(new ThreadStart(SleepT));
                fThread.IsBackground = true;
                fThread.Start();
            }
        }


        private bool send_ok = false;
        private void SleepT()
        {
            Thread send_Thread = new Thread(new ThreadStart(sendnewhmi));
            send_Thread.IsBackground = true;
            send_Thread.Start();

            for (int i = 0; i < 100; i++)
            {
                if (send_ok)
                {
                    SetTextMesssage(100, i.ToString() + "\r\n");
                }
                else
                {
                    Thread.Sleep(200);
                    SetTextMesssage(i, i.ToString() + "\r\n");

                    if (i == 95)
                    {
                        i--;
                    }
                }
            }
        }

        private void sendnewhmi()
        {
            int ret;
            FileServerClient singlesend = new FileServerClient();
            singlesend.WtClientInit(HmiIP, HmiPort);
            ret = singlesend.WtClientCopytoServerNoDelay(this.updateexe, this.localpath, globaldata.exeremoteFolder);

            if (ret == 1)
            {
                this.send_ok = true;
            }

            singlesend.WtClientClose();
        }

        private void searchhmi()
        {
            try
            {
                ProThread.HMISearch mysearch = new ProThread.HMISearch(null);
                int hmicount = 0;
                int i;
                mysearch.ThStart();
                while (!mre.WaitOne(500))
                {
                    hmicount = mysearch.HMICount();

                    this.Invoke(new Action(() =>
                    {
                        this.hmilist.Text = "搜索到" + hmicount + "个";
                    }));
                }

                this.Invoke(new Action(() =>
                {
                    hmilist.Items.Clear();
                    //SearchRet = globaldata.hHMIList;  
                    SearchRet = mysearch.myHMIList;
                    for (i = 0; i < hmicount; i++)
                    {
                        hmilist.Items.Add(((globaldata.DeviceInfo)(SearchRet[i])).IpAddr);
                    }
                }));
                mysearch.ThStop();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }

        private void SetTextMesssage(int ipos, string vinfo)
        {
            if (this.InvokeRequired)
            {
                SetPos setpos = new SetPos(SetTextMesssage);
                this.Invoke(setpos, new object[] { ipos, vinfo });
            }
            else
            {
                this.label13.Text = ipos.ToString() + "/100";
                this.progressBar1.Value = Convert.ToInt32(ipos);

                if (ipos == 100 || send_ok)
                {
                    this.label13.Text = "传输完成";
                    this.runbtn.Enabled = true;
                    this.chosenbtn.Enabled = true;
                    this.updatebtn.Enabled = true;
                }
            }
        }

        public event StopForUpdateFirm sfupdatefirm;
        public event UpdateFirmCMD updatefirm;
        private void firmwareupdate_Click(object sender, EventArgs e)
        {
            if (HmiIP != null)
            {
                sfupdatefirm();
                this.label7.Text = "发送中...";
                Thread fThread = new Thread(new ThreadStart(FirmWareUpdate));
                fThread.IsBackground = true;
                fThread.Start();

            }
        }

        private bool updatefirm_ok = false;
        private bool sendfirm_ok = false;
        private void FirmWareUpdate()
        {
            Thread send_Thread = new Thread(new ThreadStart(sendfirmware));
            send_Thread.IsBackground = true;
            send_Thread.Start();

            for (int i = 0; i < 100; i++)
            {
                if (updatefirm_ok)
                {
                    SetTextMesssage2(100, i.ToString() + "\r\n");
                }
                else
                {
                    Thread.Sleep(500);
                    SetTextMesssage2(i, i.ToString() + "\r\n");

                    if (i == 95)
                    {
                        i--;
                    }

                }
            }
        }


        private void sendfirmware()
        {
            string firmDire = null;
            string fullfilename = null;
            bool updatestart = false;
            firmDire = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.FwFolder;

            //try
            //{
            FileServerClient singlesend = new FileServerClient();
            DirectoryInfo theFolder = new DirectoryInfo(firmDire);
            DirectoryInfo[] dirInfo = theFolder.GetDirectories();

            singlesend.WtClientInit(HmiIP, HmiPort);
            foreach (FileInfo NextFile in theFolder.GetFiles())
            {
                fullfilename = NextFile.FullName;
                singlesend.WtClientCopytoServerNoDelay(NextFile.Name, fullfilename, globaldata.updateremoteFolder);
                Thread.Sleep(500);
            }

            sendfirm_ok = true;
            singlesend.WtClientClose();

            if (sendfirm_ok)
            {
                updatefirm();

                while (true)
                {
                    if (globaldata.m_hmibuffer.gcinfo.hmistatus == 5)
                    {

                        this.Invoke(new Action(() =>
                        {
                            this.label7.Text = "更新中...";
                        }));
                        updatestart = true;
                    }

                    if (updatestart)
                    {
                        if (globaldata.m_hmibuffer.gcinfo.hmistatus == 0)
                        {
                            this.Invoke(new Action(() =>
                            {
                                this.label7.Text = "更新完成...";
                            }));

                            updatefirm_ok = true;
                            sendfirm_ok = false;
                            break;
                        }
                    }

                    Thread.Sleep(500);
                }
            }
        }

        private void SetTextMesssage2(int ipos, string vinfo)
        {
            if (this.InvokeRequired)
            {
                SetPos setpos = new SetPos(SetTextMesssage2);
                this.Invoke(setpos, new object[] { ipos, vinfo });
            }
            else
            {
                this.label11.Text = ipos.ToString() + "/100";
                this.progressBar2.Value = Convert.ToInt32(ipos);

                if (ipos == 100)
                {
                    this.label10.Text = "更新完成...";
                }
            }
        }
    }
}
