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

namespace GcDevicePc
{

    public delegate void SendUpdateCMD(bool flag);
    public delegate void SendStopCMD();

    public partial class RunTables : Form
    {
        private string _configRunTable;

        private struct RunTabInfo
        {
            public string filename;
            public string runtime;
            public string runcount;
            public string rundelay;
        };

        public static ArrayList RunTabList = new ArrayList();

        public RunTables()
        {
            InitializeComponent();
            this.tabrun.Text = globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue ? "启动自动运行" : "提交运行表";
        }

        #region 界面初始化
        private void InitLocalMethod_View()
        {
            DataGridViewCheckBoxColumn checkfile = new DataGridViewCheckBoxColumn();
            checkfile.Name = "checkfile";
            checkfile.Width = 40;
            checkfile.HeaderText = "选择";
            LocalMethodView.Columns.Add(checkfile);
            DataGridViewTextBoxColumn filename = new DataGridViewTextBoxColumn();
            filename.Name = "filename";
            filename.Width = 80;
            filename.HeaderText = "文件名";
            LocalMethodView.Columns.Add(filename);
            DataGridViewTextBoxColumn lasttime = new DataGridViewTextBoxColumn();
            lasttime.Name = "lasttime";
            lasttime.Width = 140;
            lasttime.HeaderText = "最后修改时间";
            LocalMethodView.Columns.Add(lasttime);

            DirectoryInfo MethodDir = new DirectoryInfo(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder);

            foreach (FileInfo file in MethodDir.GetFiles("*.ini"))
            {
                int index = LocalMethodView.Rows.Add();
                LocalMethodView.Rows[index].Cells[1].Value = file.Name;
                LocalMethodView.Rows[index].Cells[2].Value = file.LastWriteTime.ToString();
            }
        }


        private void LoadLocalRunTable_View()
        {
           
            DirectoryInfo MethodDir = new DirectoryInfo(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder);

            foreach (FileInfo file in MethodDir.GetFiles("*.ini"))
            {
                int index = LocalRunTableView.Rows.Add();
                LocalRunTableView.Rows[index].Cells[0].Value = file.Name;
                LocalRunTableView.Rows[index].Cells[1].Value = file.LastWriteTime.ToString();
            }
        }

        private void InitLocalRunTable_View()
        {
            DataGridViewTextBoxColumn filename = new DataGridViewTextBoxColumn();
            filename.Name = "bfilename";
            filename.Width = 80;
            filename.HeaderText = "文件名";
            LocalRunTableView.Columns.Add(filename);
            DataGridViewTextBoxColumn lasttime = new DataGridViewTextBoxColumn();
            lasttime.Name = "lasttime";
            lasttime.Width = 140;
            lasttime.HeaderText = "最后修改时间";
            LocalRunTableView.Columns.Add(lasttime);
            LoadLocalRunTable_View();
        }


        private void refreshLocalRunTable_View()
        {
            if (LocalRunTableView.DataSource != null)
            {
                DataTable dt = (DataTable)LocalRunTableView.DataSource;
                dt.Rows.Clear();
                LocalRunTableView.DataSource = dt;
            }
            else
            {
                LocalRunTableView.Rows.Clear();
            }
            LoadLocalRunTable_View();
        }

        private void LoadRunTable_View()
        {
            if (String.IsNullOrEmpty(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab))
            {
                String tmpfilename = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab;
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab = tmpfilename;

                this._configRunTable = tmpfilename.Substring(tmpfilename.LastIndexOf("\\") + 1);
            }

            if (!String.IsNullOrEmpty(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab))
            {
                INIOperation runtable = new INIOperation(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab);
                string[] key = runtable.INIGetAllItemKeys("运行表");
                for (int i = 1; i < key.Length; i++)
                {
                    int index = RunTableView.Rows.Add();
                    RunTableView.Rows[index].Cells[0].Value = i - 1;
                    RunTableView.Rows[index].Cells[1].Value = runtable.INIGetStringValue("运行表", key[i], "无");
                    RunTableView.Rows[index].Cells[2].Value = runtable.INIGetStringValue("运行时间", key[i], "无");
                    RunTableView.Rows[index].Cells[3].Value = runtable.INIGetStringValue("循环", key[i], "无");
                    RunTableView.Rows[index].Cells[4].Value = runtable.INIGetStringValue("间隔时间", key[i], "无"); ;
                }

                this.updategv.Enabled = false;
            }
        }


        private void InitRunTable_View()
        {
            //方法表
            DataGridViewTextBoxColumn methodid = new DataGridViewTextBoxColumn();
            methodid.Name = "methodid";
            methodid.Width = 40;
            methodid.HeaderText = "序号";
            RunTableView.Columns.Add(methodid);
            DataGridViewTextBoxColumn filename = new DataGridViewTextBoxColumn();
            filename.Name = "filename";
            filename.Width = 80;
            filename.HeaderText = "指定事项";
            RunTableView.Columns.Add(filename);
            DataGridViewTextBoxColumn runtime = new DataGridViewTextBoxColumn();
            runtime.Name = "runtime";
            runtime.Width = 80;
            runtime.HeaderText = "运行时间";
            RunTableView.Columns.Add(runtime);
            DataGridViewTextBoxColumn runcount = new DataGridViewTextBoxColumn();
            runcount.Name = "runcount";
            runcount.Width = 80;
            runcount.HeaderText = "循环次数";
            RunTableView.Columns.Add(runcount);
            DataGridViewTextBoxColumn rundelay = new DataGridViewTextBoxColumn();
            rundelay.Name = "rundelay";
            rundelay.Width = 80;
            rundelay.HeaderText = "间隔时间";
            RunTableView.Columns.Add(rundelay);

            LoadRunTable_View();
        }

        private void refreshRunTable_View()
        {
            while (this.RunTableView.Rows.Count != 0)
            {
                this.RunTableView.Rows.RemoveAt(0);
            }

            LoadRunTable_View();
        }

        private void RunTables_Load(object sender, EventArgs e)
        {
            InitLocalMethod_View();
            InitRunTable_View();
            InitLocalRunTable_View();
        }

        #endregion

       

        #region RunTable操作事件
        private void RunTableView_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void RunTableView_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if ((e.Clicks < 2) && (e.Button == MouseButtons.Left))
            {
                //if ((e.ColumnIndex == -1) && (e.RowIndex > -1))
                if ((e.RowIndex > -1))
                    RunTableView.DoDragDrop(RunTableView.Rows[e.RowIndex], DragDropEffects.Move);
            }
        }

        int selectionIdx = 0;
        private void RunTableView_DragDrop(object sender, DragEventArgs e)
        {
            int idx = GetRowFromPoint(e.X, e.Y);

            if (idx < 0) return;

            if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
            {
                DataGridViewRow row = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));
                RunTableView.Rows.Remove(row);
                selectionIdx = idx;
                RunTableView.Rows.Insert(idx, row);
            }

            for (idx = 0; idx < RunTableView.Rows.Count; idx ++ )
            {
                RunTableView.Rows[idx].Cells[0].Value = idx;

            }
        }

        private int GetRowFromPoint(int x, int y)
        {
            for (int i = 0; i < RunTableView.RowCount; i++)
            {
                Rectangle rec = RunTableView.GetRowDisplayRectangle(i, false);

                if (RunTableView.RectangleToScreen(rec).Contains(x, y))
                    return i;
            }

            return -1;
        }

        private void RunTableView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            try
            {
                if (selectionIdx > -1)
                {
                    RunTableView.Rows[selectionIdx].Selected = true;
                    RunTableView.CurrentCell = RunTableView.Rows[selectionIdx].Cells[0];
                }
            }
            catch
            {

            }
            
        }


        private void RunTableView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (RunTableView.Rows[e.RowIndex].Selected == false)
                    {
                        RunTableView.ClearSelection();
                        RunTableView.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (RunTableView.SelectedRows.Count == 1)
                    {
                        RunTableView.CurrentCell = RunTableView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                       
                    }
                    //弹出操作菜单
                    RunTabMenu.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        #endregion


        #region 运行表菜单事件
        private int _curEdit;
        private string _curFilename;
        private void EditRow_Click(object sender, EventArgs e)
        {
            int index = RunTableView.SelectedRows[0].Index;

            _curFilename = RunTableView.Rows[index].Cells[1].Value.ToString();
            rtbox.Text = RunTableView.Rows[index].Cells[2].Value.ToString();
            rcbox.Text = RunTableView.Rows[index].Cells[3].Value.ToString();
            rdbox.Text = RunTableView.Rows[index].Cells[4].Value.ToString();
            _curEdit = index;
            this.AddMethodbtn.Enabled = false;
            this.RunTableView.Enabled = false;
            this.updategv.Enabled = true;
            //this.rtsave.Enabled = false;
        }

        private void DelRow_Click(object sender, EventArgs e)
        {
            int index = RunTableView.SelectedRows[0].Index;
            DataGridViewRow row = RunTableView.Rows[index];
            RunTableView.Rows.Remove(row);

            for (int idx = 0; idx < RunTableView.Rows.Count; idx++)
            {
                RunTableView.Rows[idx].Cells[0].Value = idx;

            }
        }

        private void MoveupRow_Click(object sender, EventArgs e)
        {
            int index = RunTableView.SelectedRows[0].Index;
            if(index >=1 )
            {
                DataGridViewRow row = RunTableView.Rows[index];
                DataGridViewRow uprow = RunTableView.Rows[index-1];
                RunTableView.Rows.Remove(row);
                RunTableView.Rows.Remove(uprow);

                RunTableView.Rows.Insert(index-1, row);
                RunTableView.Rows.Insert(index, uprow);
            }
            for (int idx = 0; idx < RunTableView.Rows.Count; idx++)
            {
                RunTableView.Rows[idx].Cells[0].Value = idx;

            }
        }

        private void MouedownRow_Click(object sender, EventArgs e)
        {
            int index = RunTableView.SelectedRows[0].Index;
            if (index < RunTableView.Rows.Count -1)
            {
                DataGridViewRow row = RunTableView.Rows[index];
                DataGridViewRow downrow = RunTableView.Rows[index + 1];
                RunTableView.Rows.Remove(row);
                RunTableView.Rows.Remove(downrow);

                RunTableView.Rows.Insert(index, downrow);
                RunTableView.Rows.Insert((index + 1), row);
               
            }

            for (int idx = 0; idx < RunTableView.Rows.Count; idx++)
            {
                RunTableView.Rows[idx].Cells[0].Value = idx;
            }
        }
        #endregion

        private void updategv_Click(object sender, EventArgs e)
        {

            DataGridViewRow row = RunTableView.Rows[_curEdit];
            RunTableView.Rows.Remove(row);

            DataGridViewRow dr = new DataGridViewRow();
            dr.CreateCells(RunTableView);

            dr.Cells[0].Value = _curEdit;
            dr.Cells[1].Value = _curFilename;
            dr.Cells[2].Value = rtbox.Text;
            dr.Cells[3].Value = rcbox.Text;
            dr.Cells[4].Value = rdbox.Text;

            RunTableView.Rows.Insert(_curEdit, dr);

            this.AddMethodbtn.Enabled = true;
            this.RunTableView.Enabled = true;
            //this.rtsave.Enabled = true;
            this.updategv.Enabled = false;

            this.rtbox.Text = "";
            this.rcbox.Text = "";
            this.rdbox.Text = "";
        }


        private void AddMethodbtn_Click(object sender, EventArgs e)
        {
            RunTabList.Clear();
           
            //string sendfilename = null;
            //string sendname = null;

            for (int i = 0; i < LocalMethodView.Rows.Count; i++)
            {
                
                if ((bool)LocalMethodView.Rows[i].Cells[0].EditedFormattedValue == true)
                {
                    RunTabInfo tmp;
                    tmp.filename = (string)LocalMethodView.Rows[i].Cells[1].Value;
                    tmp.runtime = "0";
                    tmp.runcount = "1";
                    tmp.rundelay = "0";
                    RunTabList.Add(tmp);
                }
            }

            for (int i = 0; i < RunTabList.Count; i++)
            {
                int index = RunTableView.Rows.Add();
                RunTableView.Rows[index].Cells[0].Value = index;
                RunTableView.Rows[index].Cells[1].Value = ((RunTabInfo)RunTabList[i]).filename;
                RunTableView.Rows[index].Cells[2].Value = ((RunTabInfo)RunTabList[i]).runtime;
                RunTableView.Rows[index].Cells[3].Value = ((RunTabInfo)RunTabList[i]).runcount;
                RunTableView.Rows[index].Cells[4].Value = ((RunTabInfo)RunTabList[i]).rundelay;
            }

            //if (!String.IsNullOrEmpty(globaldata.connection_ip))
            //{
            //    FileServerClient runtabclient = new FileServerClient();
            //    runtabclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
            //    for (int i = 0; i < RunTabList.Count; i++)
            //    {
            //        sendfilename = ((RunTabInfo)RunTabList[i]).filename;
            //        sendname = null;
            //        sendname = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, sendfilename);
            //        runtabclient.WtClientCopytoServer(sendfilename, sendname, globaldata.remoteFolder + "仪器方法\\");
            //        Thread.Sleep(100);
            //    }
            //    runtabclient.WtClientClose();
            // }

        }

        public event SendUpdateCMD sendupdatecmd;
        private void tabrun_Click(object sender, EventArgs e)
        {
            this.tabrun.Enabled = false;

            if (!File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab))
            {
                StreamWriter sw = new StreamWriter(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab, false, System.Text.Encoding.Unicode);
                sw.WriteLine("[运行表]");
                sw.Close();
            }
            string file = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab;
            INIOperation runtable = new INIOperation(file);

            string subkey;
            runtable.INIEmptySection(file, "运行表");
            runtable.INIEmptySection(file, "循环");
            runtable.INIEmptySection(file, "运行时间");
            runtable.INIWriteValue(file, "运行表", "0", "开机");
            runtable.INIWriteValue(file, "循环", "0", "1");
            runtable.INIWriteValue(file, "运行时间", "0", "1");
            runtable.INIWriteValue(file, "间隔时间", "0", "1");

            bool rbet;
            FileServerClient rtclient = null;
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                rtclient = new FileServerClient();
                rtclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);

            }

            string lfilename;
            string rfilename;

            for (int i = 0; i < RunTableView.RowCount; i++)
            {
                subkey = (Convert.ToInt32(RunTableView.Rows[i].Cells[0].Value) + 1).ToString();
                rbet = runtable.INIWriteValue(file, "运行表", subkey, RunTableView.Rows[i].Cells[1].Value.ToString());

                if (RunTableView.Rows[i].Cells[3].Value.ToString() == "-1")
                    rbet = runtable.INIWriteValue(file, "循环", subkey, "-1");
                else if (RunTableView.Rows[i].Cells[3].Value.ToString() == "0")
                    rbet = runtable.INIWriteValue(file, "循环", subkey, "0");
                else
                    rbet = runtable.INIWriteValue(file, "循环", subkey, RunTableView.Rows[i].Cells[3].Value.ToString());

                rbet = runtable.INIWriteValue(file, "运行时间", subkey, RunTableView.Rows[i].Cells[2].Value.ToString());

                rbet = runtable.INIWriteValue(file, "间隔时间", subkey, RunTableView.Rows[i].Cells[4].Value.ToString());

                lfilename = null;
                rfilename = null;
                rfilename = RunTableView.Rows[i].Cells[1].Value.ToString();
                lfilename = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, rfilename);
                if (rtclient != null)
                    rtclient.WtClientCopytoServer(rfilename, lfilename, globaldata.remoteFolder + "仪器方法\\");
            }

            if (rtclient != null)
                rtclient.WtClientClose();

            //string message = "运行表保存成功";
            //MessageBox.Show(message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);


            if ( !String.IsNullOrEmpty(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab)  &&  !String.IsNullOrEmpty(globaldata.connection_ip))
            {

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 2;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;


                if (File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab))
                {
                    FileServerClient bfclient = new FileServerClient();
                    bfclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                    bfclient.WtClientCopytoServer("RunMethod.ini", globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab, globaldata.remoteFolder + "运行表\\");
                    bfclient.WtClientClose();

                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab =
                        globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab;
                }
               
                sendupdatecmd(false);
            }
            this.tabrun.Enabled = true;

            this.Close();
        }

        private void rtsave_Click(object sender, EventArgs e)
        {
            this.tabrun.Enabled = false;
            if (!File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab))
            {
                StreamWriter sw = new StreamWriter(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab, false, System.Text.Encoding.Unicode);
                sw.WriteLine("[运行表]");
                sw.Close();
            }
            string file = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab;
            INIOperation runtable = new INIOperation(file);
            
            string subkey;
            runtable.INIEmptySection(file, "运行表");
            runtable.INIEmptySection(file, "循环");
            runtable.INIEmptySection(file, "运行时间");
            runtable.INIWriteValue(file, "运行表", "0", "开机");
            runtable.INIWriteValue(file, "循环", "0", "1");
            runtable.INIWriteValue(file, "运行时间", "0", "1");
            runtable.INIWriteValue(file, "间隔时间", "0", "1");

            bool rbet;
            FileServerClient rtclient = null;
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                rtclient = new FileServerClient();
                rtclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
              
            }

            string lfilename;
            string rfilename;

            for(int i = 0; i < RunTableView.RowCount; i++)
            {               
                subkey = (Convert.ToInt32(RunTableView.Rows[i].Cells[0].Value) + 1).ToString();
                rbet  = runtable.INIWriteValue(file, "运行表", subkey, RunTableView.Rows[i].Cells[1].Value.ToString());

                if (RunTableView.Rows[i].Cells[3].Value.ToString() == "-1")
                    rbet = runtable.INIWriteValue(file, "循环", subkey, "-1");
                else if (RunTableView.Rows[i].Cells[3].Value.ToString() == "0")
                    rbet = runtable.INIWriteValue(file, "循环", subkey, "0");
                else
                    rbet = runtable.INIWriteValue(file, "循环", subkey, RunTableView.Rows[i].Cells[3].Value.ToString());

                rbet =  runtable.INIWriteValue(file, "运行时间", subkey, RunTableView.Rows[i].Cells[2].Value.ToString());

                rbet = runtable.INIWriteValue(file, "间隔时间", subkey, RunTableView.Rows[i].Cells[4].Value.ToString());

                lfilename = null;
                rfilename = null;
                rfilename = RunTableView.Rows[i].Cells[1].Value.ToString();
                lfilename = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, rfilename);
                if(rtclient != null)
                    rtclient.WtClientCopytoServer(rfilename, lfilename, globaldata.remoteFolder + "仪器方法\\");       
            }

            if (rtclient != null)
                rtclient.WtClientClose();

            string message = "运行表保存成功";
            MessageBox.Show(message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.tabrun.Enabled = true;
        }

        public event SendStopCMD sendstopcmd;
        private void stopbat_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 0;
                sendstopcmd();
            }
        }

        private void LocalRunTableView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int index = LocalRunTableView.SelectedRows[0].Index;
            String name = LocalRunTableView.Rows[index].Cells[0].Value.ToString();
            this._configRunTable = name;
            String configname = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, name);

            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.config_RunTab = configname;

            refreshRunTable_View();

        }

        private void delRunTable_Click(object sender, EventArgs e)
        {
            int index = LocalRunTableView.SelectedRows[0].Index;
            String name = LocalRunTableView.Rows[index].Cells[0].Value.ToString();
            String delname = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, name);
            if (File.Exists(delname))
            {
                File.Delete(delname);
            }
            refreshLocalRunTable_View();
        }

        private void addRunTable_Click(object sender, EventArgs e)
        {
            addRunTable.Enabled = false;
            DialogResult dr = new SaveWin(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, 2).ShowDialog();

            if (dr == DialogResult.OK)
            {
                refreshLocalRunTable_View();
            }
         
            addRunTable.Enabled = true;
        }
    }
}
