using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GcDevicePc.GCBuffer;

namespace GcDevicePc.DeviceConfigUI
{
    public delegate void UpdataHMIOP(ushort val);
    public partial class ConfigDevice : Form
    {

        #region 私有变量
        private HWConfig hWConfig;
        #endregion

        public InstrConfig fatherForm;

        FileServerClient SCclient = new FileServerClient();

        public ConfigDevice()
        {
            InitializeComponent();

            hWConfig = new HWConfig(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder, "DevStatus.ini");
            
        }

        public ConfigDevice(HWConfig hw_config)
        {
            InitializeComponent();
            if (hw_config != null)
            {
                this.hWConfig = hw_config;
            }
            else
            {
                this.hWConfig = new HWConfig();
            }

        }

        #region 界面初始化
        /// <summary>
        /// 初始化系统默认设备
        /// </summary>
        private void InitSysConfigTree()
        {
            //仪器配置
            TreeNode hmi_identifier = new TreeNode("仪器配置");
            TreeNode hmi_identifier_sub1 = new TreeNode("仪器编码");
            hmi_identifier_sub1.Tag = 1;
            TreeNode hmi_identifier_sub2 = new TreeNode("仪器名称");
            hmi_identifier_sub2.Tag = 2;
            TreeNode hmi_identifier_sub3 = new TreeNode("仪器档次");
            hmi_identifier_sub3.Tag = 3;
            hmi_identifier.Nodes.Add(hmi_identifier_sub1);
            hmi_identifier.Nodes.Add(hmi_identifier_sub2);
            hmi_identifier.Nodes.Add(hmi_identifier_sub3);

            //进样单元
            TreeNode sampling_unit = new TreeNode("进样单元");
            TreeNode sampling_unit_sub1 = new TreeNode("进样器");
            sampling_unit_sub1.Tag = 4;
            TreeNode sampling_unit_sub3 = new TreeNode("进样阀");
            sampling_unit_sub3.Tag = 5;
            TreeNode sampling_unit_sub4 = new TreeNode("进样口");
            sampling_unit_sub4.Tag = 6;

            sampling_unit.Nodes.Add(sampling_unit_sub1);
            sampling_unit.Nodes.Add(sampling_unit_sub3);
            sampling_unit.Nodes.Add(sampling_unit_sub4);
            //柱箱单元
            TreeNode columnbox_unit = new TreeNode("柱箱单元");
            TreeNode columnbox_unit_sub1 = new TreeNode("柱箱");
            columnbox_unit_sub1.Tag = 7;
            columnbox_unit.Nodes.Add(columnbox_unit_sub1);

            //检测单元
            TreeNode detection_unit = new TreeNode("检测单元");
            TreeNode detection_unit_sub1 = new TreeNode("检测器");
            detection_unit_sub1.Tag = 8;
            detection_unit.Nodes.Add(detection_unit_sub1);

            //辅助单元
            TreeNode auxiliary_unit = new TreeNode("辅助单元");
            TreeNode auxiliary_unit_sub1 = new TreeNode("加热器");
            auxiliary_unit_sub1.Tag = 9;
            auxiliary_unit.Nodes.Add(auxiliary_unit_sub1);

            SysConfigTree.Nodes.Add(hmi_identifier);
            SysConfigTree.Nodes.Add(sampling_unit);
            SysConfigTree.Nodes.Add(columnbox_unit);
            SysConfigTree.Nodes.Add(detection_unit);
            SysConfigTree.Nodes.Add(auxiliary_unit);
            SysConfigTree.Nodes[0].Expand();
        }


        private void UpdateHMIConfigTree(int no)
        {
            if (hWConfig != null)
            {
                HMIConfigTree.Nodes.Clear();
                //仪器配置
                TreeNode hmi_identifier = new TreeNode("仪器配置");
                TreeNode hmi_identifier_sub1 = new TreeNode("仪器编码");
                hmi_identifier_sub1.Tag = 1;
                TreeNode hmi_identifier_sub2 = new TreeNode("仪器名称");
                hmi_identifier_sub2.Tag = 2;
                TreeNode hmi_identifier_sub3 = new TreeNode("仪器档次");
                hmi_identifier_sub3.Tag = 3;

                hmi_identifier.Nodes.Add(hmi_identifier_sub1);
                hmi_identifier.Nodes.Add(hmi_identifier_sub2);
                hmi_identifier.Nodes.Add(hmi_identifier_sub3);
                HMIConfigTree.Nodes.Add(hmi_identifier);
                ////////////////////////////////////////////////////////////////////////////////////////////
                TreeNode sampling_unit = new TreeNode("进样单元");
                if (hWConfig.hwconfiginfo.u16SampleFront == 1 || hWConfig.hwconfiginfo.u16SampleBehind == 1)
                {
                    TreeNode sampling_unit_sub1 = new TreeNode("进样器");
                    sampling_unit_sub1.Tag = 4;
                    sampling_unit.Nodes.Add(sampling_unit_sub1);
                }

                if (hWConfig.hwconfiginfo.u16ValveOne == 1|| hWConfig.hwconfiginfo.u16ValveTwo == 1 || hWConfig.hwconfiginfo.u16ValveThree == 1 ||
                    hWConfig.hwconfiginfo.u16ValveFour == 1 || hWConfig.hwconfiginfo.u16ValveFive == 1 || hWConfig.hwconfiginfo.u16ValveSix == 1)
                {
                    TreeNode sampling_unit_sub3 = new TreeNode("进样阀");
                    sampling_unit_sub3.Tag = 5;
                    sampling_unit.Nodes.Add(sampling_unit_sub3);
                }

                if (hWConfig.hwconfiginfo.u16InjPortFront == 1|| hWConfig.hwconfiginfo.u16InjPortBehind == 1|| hWConfig.hwconfiginfo.u16ChromFront == 1 || hWConfig.hwconfiginfo.u16ChromBehind == 1)
                {
                    TreeNode sampling_unit_sub9 = new TreeNode("进样口");
                    sampling_unit_sub9.Tag = 6;
                    sampling_unit.Nodes.Add(sampling_unit_sub9);
                }

                HMIConfigTree.Nodes.Add(sampling_unit);
                ///////////////////////////////////////////////////////////////////////////////////////////
                TreeNode columnbox_unit = new TreeNode("柱箱单元");

                if (hWConfig.hwconfiginfo.u16Col == 1)
                {
                    TreeNode columnbox_unit_sub1 = new TreeNode("柱箱");
                    columnbox_unit_sub1.Tag = 7;
                    columnbox_unit.Nodes.Add(columnbox_unit_sub1);
                }

                HMIConfigTree.Nodes.Add(columnbox_unit);

                ///////////////////////////////////////////////////////////////////////////////////////////////
                TreeNode detection_unit = new TreeNode("检测单元");
                if (hWConfig.hwconfiginfo.u16DetFront == 1|| hWConfig.hwconfiginfo.u16DetBehind == 1|| hWConfig.hwconfiginfo.u16DetInter == 1)
                {
                    TreeNode detection_unit_sub1 = new TreeNode("检测器");
                    detection_unit_sub1.Tag = 8;
                    detection_unit.Nodes.Add(detection_unit_sub1);
                }
                HMIConfigTree.Nodes.Add(detection_unit);

                ////////////////////////////////////////////////////////////////////////////////////////////////
                TreeNode auxiliary_unit = new TreeNode("辅助单元");

                if (hWConfig.hwconfiginfo.u16AuxHeater1 == 1|| hWConfig.hwconfiginfo.u16AuxHeater2 == 1)
                {
                    TreeNode auxiliary_unit_sub1 = new TreeNode("加热器");
                    auxiliary_unit_sub1.Tag = 9;
                    auxiliary_unit.Nodes.Add(auxiliary_unit_sub1);
                }

                HMIConfigTree.Nodes.Add(auxiliary_unit);

                HMIConfigTree.Nodes[no].Expand();
            }
            else
            {
                MessageBox.Show("配置文件为空！");
            }
        }
        #endregion

        private void ConfigDevice_Load(object sender, EventArgs e)
        {
            InitSysConfigTree();
            UpdateHMIConfigTree(0);
        }

        #region 控件事件
        private void HMIConfigTree_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right || e.Node.Level == 0)
                    return;

                int nodename = int.Parse(HMIConfigTree.SelectedNode.Tag.ToString());
                if (nodename > 0 && nodename < 24)
                {
                    if (nodename <= 3)
                    {
                        Device device = new Device(ref hWConfig);
                        device.ShowDialog();
                    }
                    else if (nodename <= 6)
                    {
                        Sampling sampling = new Sampling(ref hWConfig, nodename);
                        sampling.ShowDialog();
                    }
                    else if (nodename == 7)
                    {
                        ColumnBox columnBox = new ColumnBox(ref hWConfig);
                        columnBox.ShowDialog();
                    }
                    else if (nodename == 8)
                    {
                        Detection detection = new Detection(ref hWConfig);
                        detection.ShowDialog();
                    }
                    else
                    {
                        Auxiliary auxiliary = new Auxiliary(ref hWConfig);
                        auxiliary.ShowDialog();
                    }

                }
            }
            catch
            {
                
            }
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="flag">true- add module flase -del</param>
        private void updatemodule(bool flag)
        {
            try
            {
                if ((SysConfigTree.SelectedNode.Tag != null || HMIConfigTree.SelectedNode.Tag != null) && hWConfig != null)
                {
                    int no = 0;


                    no = flag ? int.Parse(SysConfigTree.SelectedNode.Tag.ToString()) : int.Parse(HMIConfigTree.SelectedNode.Tag.ToString());

                    switch (no)
                    {
                        case 4:
                            hWConfig.hwconfiginfo.u16SampleFront = flag ? 1 : 0;
                            break;

                        case 5:
                            hWConfig.hwconfiginfo.u16ValveOne = flag ? 1 : 0;
                            break;
                        
                        case 6:
                            hWConfig.hwconfiginfo.u16InjPortFront = flag ? 1 : 0;
                            hWConfig.hwconfiginfo.u16ChromFront = flag ? 1 : 0;
                            break;

                        case 7:
                            hWConfig.hwconfiginfo.u16Col = flag ? 1 : 0;
                            break;

                        case 8:
                            hWConfig.hwconfiginfo.u16DetFront = flag ? 1 : 0;
                            break;

                        case 9:
                            hWConfig.hwconfiginfo.u16AuxHeater1 = flag ? 1 : 0;
                            break;

                    }

                    int node = 0;
                    if (no > 0 && no < 24)
                    {
                        if (no <= 3)
                        {
                            node = 0;
                        }
                        else if (no >= 4 && no <= 6)
                        {
                            node = 1;
                        }
                        else if (no == 7)
                        {
                            node = 2;
                        }
                        else if (no == 8)
                        {
                            node = 3;
                        }
                        else
                        {
                            node = 4;
                        }

                    }
                    UpdateHMIConfigTree(node);
                }
                else
                {
                    MessageBox.Show("NULL");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("请选择节点");
            }

        }

        private void addmodule_Click(object sender, EventArgs e)
        {
            updatemodule(true);

        }

        private void delmodule_Click(object sender, EventArgs e)
        {
            updatemodule(false);
        }

        #endregion
        string sendfilename;

        public event UpdataHMIOP upho;
        private void savebtn_Click(object sender, EventArgs e)
        {

            //Console.WriteLine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder);

            //SaveDialog saveDialog = new SaveDialog(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.SubStatusFolder, 2);
            //DialogResult dr = saveDialog.ShowDialog();
            //if (dr == DialogResult.OK)

            try
            {

                sendfilename = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.SubStatusFolder,
    "DevStatus.ini");

                if (File.Exists(sendfilename))
                {
                    System.IO.File.Delete(sendfilename);
                }

                hWConfig.CreatHWConfig(sendfilename);

                hWConfig.SavaHWConfig();


                string ip = globaldata.connection_ip;

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == false)
                {
                    savebtn.Enabled = false;

                    SCclient.WtClientInit(ip, globaldata.fileserverport);
                    SCclient.WtClientCopytoServer("DevStatus.ini", sendfilename, globaldata.remoteFolder + "仪器状态\\");
                    upho(1);

                    try
                    {
                        string tmpname = "";

                        globaldata.m_appinit.InitAppFolder(globaldata.DeviceName);
                        globaldata.m_appinit.SyncConfigFiles();
                        globaldata.m_appinit.InitAppDefaultConfig();
                        globaldata.m_profileMethod.SetStatusFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName);
                        globaldata.m_profileMethod.GetDevState();

                        tmpname = globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2 ?
                        globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName :
                        globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;

                        if (!String.IsNullOrEmpty(tmpname))
                        {
                            globaldata.show_MethodName = tmpname;
                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, tmpname.ToString());

                            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, tmpname.ToString());

                            globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);
                            globaldata.m_profileMethod.GetDevInjPortAllPara();
                            globaldata.m_profileMethod.GetSampleAllPara("前进样器");
                            globaldata.m_profileMethod.GetInjValveAllPara();
                            globaldata.m_profileMethod.GetChromAllPara();
                            globaldata.m_profileMethod.GetColTableElseAllPara();
                            globaldata.m_profileMethod.GetFidAllPara();
                            globaldata.m_profileMethod.GetTcdAllPara();
                            globaldata.m_profileMethod.GetAuxiliaryAllPara();
                        }
                        else
                        {
                        }
                    }
                    catch
                    {
                    }
                    this.Close();
                }
                else
                {
                    MessageBox.Show("请停止系统，再更新配置！");
                }
            }
            catch (Exception)
            {

            }

        }

        private void resetbtn_Click(object sender, EventArgs e)
        {

        }

        private void updateHMIbtn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(sendfilename))
            {
                string ip = globaldata.connection_ip;

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == false)
                {
                    SCclient.WtClientInit(ip, globaldata.fileserverport);
                    SCclient.WtClientCopytoServer("DevStatus.ini", sendfilename, globaldata.remoteFolder + "仪器状态\\");
                    //MessageBox.Show("更新配置完成！");
                    //this.Close();

                    int ret = 0;
                    ret = SCclient.WtHMICloseRro("WtMainProc");
                    if (ret == 1)
                    {
                        ret = SCclient.WtHMIRunPro("GcDevice.exe", globaldata.exeremoteFolder);
                        if (ret == 1)
                        {

                            DialogResult result = MessageBox.Show("HMI自重启成功，是否重启PC软件以同步？", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
                            if (result == DialogResult.OK)
                            {
                                Application.ExitThread();
                                Application.Exit();
                                Application.Restart();
                                Process.GetCurrentProcess().Kill();
                            }
                            else if (result == DialogResult.Cancel)
                            {
                                this.Close();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请停止系统，再更新配置！");
                }
            }
            else
            {
                MessageBox.Show("请先保存配置！");
            }

        }
    }

}
    