using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using GcDevicePc.IniParam;

namespace GcDevicePc
{
    public delegate void AUXTool(int flag, ushort futime, ushort hvtime, ushort ffdeley);
    //public delegate void AUXTool(int flag, ushort futime, ushort hvtime);
    public delegate void StopForUpdateFirm();
    public delegate void UpdateFirmCMD();
    public delegate void SetPos(int ipos, string vinfo);
    public delegate void TCD_SW(ushort port);
    public delegate void TCD_SetDAC(ushort port, ushort val);

    public delegate void HAir_SW(int val);

    public partial class auxtool : Form
    {
        private string HmiIP = null;
        private ushort HmiPort = 911;
        private ArrayList SearchRet = new ArrayList();

        public auxtool()
        {
            InitializeComponent();
            fidfire.Start();
        }

        public auxtool(ushort time1, ushort time2, ushort time3)
        {
            InitializeComponent();

            this.fireuptime.Text = time1.ToString();
            this.hvalvetime.Text = time2.ToString();

            this.firstfiredelay.Text = time3.ToString();
            fidfire.Start();

        }

        public void setfireuptime(ushort time1, ushort time2, ushort time3)
        {
            this.fireuptime.Text = time1.ToString();
            this.hvalvetime.Text = time2.ToString();
            this.firstfiredelay.Text = time3.ToString();

        }

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

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

        private void hvalvetime_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

        private void fireuptime_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

        public event AUXTool auxtoolforfireup;
        private void fireupbtn_Click(object sender, EventArgs e)
        {
            //if(String.IsNullOrEmpty(fireuptime.Text) || String.IsNullOrEmpty(hvalvetime.Text))
            //{
            //    MessageBox.Show("点火时间 和 氢气阀时间不能为空！！！");
            //}
            //else
            //{
            //    ushort time1 = ushort.Parse(fireuptime.Text);
            //    ushort time2 = ushort.Parse(hvalvetime.Text);

            //    if(time1 >= time2)
            //    {
            //        auxtoolforfireup(0, time1, time2);
            //    }else
            //    {
            //        MessageBox.Show("点火时间需大于等于氢气阀时间！！！");
            //    }  
            //}

            //if (min >= 30)
            try
            {
                if (String.IsNullOrEmpty(fireuptime.Text) || String.IsNullOrEmpty(hvalvetime.Text) || string.IsNullOrEmpty(firstfiredelay.Text))
                {
                    MessageBox.Show("点火时间 第一次点火延时 和 氢气阀时间不能为空！！！");
                }
                else
                {

                    ushort time1 = ushort.Parse(fireuptime.Text);
                    ushort time2 = ushort.Parse(hvalvetime.Text);
                    ushort time3 = ushort.Parse(firstfiredelay.Text);
                    if (time1 >= time2)
                    {
                        auxtoolforfireup(0, time1, time2, time3);
                        this.fireupbtnI.Enabled = false;

                    }
                    else
                    {
                        MessageBox.Show("点火时间需大于等于氢气阀时间！！！");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //else
            //{
            //    MessageBox.Show("请在三十分钟后在点火！");
            //}
        }

        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();
        }


        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 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 hmilist_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.HmiIP = this.hmilist.Text;

            this.CHmibtn.Enabled = true;
        }

        private void auxtool_Load(object sender, EventArgs e)
        {
            this.CHmibtn.Enabled = false;
            this.runbtn.Enabled = false;
            this.chosenbtn.Enabled = false;
            this.updatebtn.Enabled = false;
        }

        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.label6.Text = ipos.ToString() + "/100";
                this.progressBar2.Value = Convert.ToInt32(ipos);

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

        public event HAir_SW hairsw;
        private void hair_h1_Click(object sender, EventArgs e)
        {
            hairsw(1);
        }

        private void hair_a1_Click(object sender, EventArgs e)
        {
            hairsw(2);
        }

        private void hair_h2_Click(object sender, EventArgs e)
        {
            hairsw(3);
        }

        private void hair_a2_Click(object sender, EventArgs e)
        {
            hairsw(4);
        }

        public event TCD_SetDAC gctcd_setdac;
        public event TCD_SW gctcd_sw;
        private void tcdset1_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(tcddac1.Text))
            {
                MessageBox.Show("设置值不能为空！！！");
            }
            else
            {
                ushort val = ushort.Parse(tcddac1.Text);


                if (val >= 0 && val < 150)
                {
                    gctcd_setdac(0, val);
                }
                else
                {
                    MessageBox.Show("超过设置值(0~150)！！！");
                }
            }
        }

        private void tcdset2_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(tcddac2.Text))
            {
                MessageBox.Show("设置值不能为空！！！");
            }
            else
            {
                ushort val = ushort.Parse(tcddac2.Text);


                if (val >= 0 && val < 150)
                {
                    gctcd_setdac(1, val);
                }
                else
                {
                    MessageBox.Show("超过设置值(0~150)！！！");
                }
            }
        }

        private void tcdset3_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(tcddac3.Text))
            {
                MessageBox.Show("设置值不能为空！！！");
            }
            else
            {
                ushort val = ushort.Parse(tcddac3.Text);


                if (val >= 0 && val < 150)
                {
                    gctcd_setdac(2, val);
                }
                else
                {
                    MessageBox.Show("超过设置值(0~150)！！！");
                }
            }
        }

        private void tcd1_sw_Click(object sender, EventArgs e)
        {

            if (String.IsNullOrEmpty(tcddac1.Text))
            {
                MessageBox.Show("设置值不能为空！！！");
            }
            else
            {
                ushort val = ushort.Parse(tcddac1.Text);


                if (val >= 0 && val < 150)
                {
                    gctcd_setdac(0, val);
                }
                else
                {
                    MessageBox.Show("超过设置值(0~150)！！！");
                }
            }

            String tcd1_flag = tcd1_sw.Text;
            string[] sArray = tcd1_flag.Split(new char[2] { '(', ')' });
            if (sArray[1] == "关")
            {
                tcd1_sw.Text = "前TCD(开)";
            }
            else if (sArray[1] == "开")
            {
                tcd1_sw.Text = "前TCD(关)";
            }
            Console.WriteLine(sArray[1]);
            gctcd_sw(0);
        }

        private void tcd2_sw_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(tcddac2.Text))
            {
                MessageBox.Show("设置值不能为空！！！");
            }
            else
            {
                ushort val = ushort.Parse(tcddac2.Text);


                if (val >= 0 && val < 150)
                {
                    gctcd_setdac(1, val);
                }
                else
                {
                    MessageBox.Show("超过设置值(0~150)！！！");
                }
            }

            String tcd2_flag = tcd2_sw.Text;
            string[] sArray = tcd2_flag.Split(new char[2] { '(', ')' });
            if (sArray[1] == "关")
            {
                tcd2_sw.Text = "中TCD(开)";
            }
            else if (sArray[1] == "开")
            {
                tcd2_sw.Text = "中TCD(关)";
            }
            Console.WriteLine(sArray[1]);
            gctcd_sw(1);
        }

        private void tcd3_sw_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(tcddac3.Text))
            {
                MessageBox.Show("设置值不能为空！！！");
            }
            else
            {
                ushort val = ushort.Parse(tcddac3.Text);


                if (val >= 0 && val < 150)
                {
                    gctcd_setdac(2, val);
                }
                else
                {
                    MessageBox.Show("超过设置值(0~150)！！！");
                }
            }

            String tcd3_flag = tcd3_sw.Text;
            string[] sArray = tcd3_flag.Split(new char[2] { '(', ')' });
            if (sArray[1] == "关")
            {
                tcd3_sw.Text = "后TCD(开)";
            }
            else if (sArray[1] == "开")
            {
                tcd3_sw.Text = "后TCD(关)";
            }
            Console.WriteLine(sArray[1]);
            gctcd_sw(2);
        }

        private void fireupbtnI_Click(object sender, EventArgs e)
        {
            //if (min >= 30)
            {
                if (String.IsNullOrEmpty(fireuptime.Text) || String.IsNullOrEmpty(hvalvetime.Text))
                {
                    MessageBox.Show("点火时间 和 氢气阀时间不能为空！！！");
                }
                else
                {
                    ushort time1 = ushort.Parse(fireuptime.Text);
                    ushort time2 = ushort.Parse(hvalvetime.Text);
                    ushort time3 = ushort.Parse(firstfiredelay.Text);

                    if (time1 >= time2)
                    {
                        auxtoolforfireup(1, time1, time2, time3);
                        this.fireupbtn.Enabled = false;
                    }
                    else
                    {
                        MessageBox.Show("点火时间需大于等于氢气阀时间！！！");
                    }
                }
            }
            //else
            //{
            //    MessageBox.Show("请在三十分钟后在点火！");
            //}
        }

        private void fidfire_Tick(object sender, EventArgs e)
        {
            if (CProfileDevice.m_DevParam.syspara.u16DetFrontType == 1)
            {
                if (globaldata.m_dpbuffer.ShowList.showDet.iDetStatue == 1)
                {
                    this.fireupbtn.Enabled = false;
                }
                else
                {
                    this.fireupbtn.Enabled = true;

                }
            }

            if (CProfileDevice.m_DevParam.syspara.u16DetInterType == 1)
            {
                if (globaldata.m_dpbuffer.ShowList.showDet.fDetStatue == 1)
                {
                    this.fireupbtnI.Enabled = false;
                }
                else
                {
                    this.fireupbtnI.Enabled = true;

                }
            }

            this.tcd1_sw.Enabled = this.tcd2_sw.Enabled = this.tcd3_sw.Enabled = globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue;
        }

        private void auxtool_FormClosed(object sender, FormClosedEventArgs e)
        {
            fidfire.Stop();
        }

        //private void fireupbtnb_Click(object sender, EventArgs e)
        //{
        //    if (String.IsNullOrEmpty(fireuptime.Text) || String.IsNullOrEmpty(hvalvetime.Text))
        //    {
        //        MessageBox.Show("点火时间 和 氢气阀时间不能为空！！！");
        //    }
        //    else
        //    {
        //        ushort time1 = ushort.Parse(fireuptime.Text);
        //        ushort time2 = ushort.Parse(hvalvetime.Text);
        //        ushort time3 = ushort.Parse(firstfiredelay.Text);

        //        if (time1 >= time2)
        //        {
        //            auxtoolforfireup(2, time1, time2, time3);
        //        }
        //        else
        //        {
        //            MessageBox.Show("点火时间需大于等于氢气阀时间！！！");
        //        }
        //    }
        //}
    }
}
