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;

namespace GcDevicePc
{

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

    public partial class RunTables : Form
    {
        public struct RunTabInfo
        {
            public string filename;
            public string runtime;
            public string runcount;
            public string rundelay;
        };

        public static ArrayList RunTabList = new ArrayList();

        public RunTables()
        {
            InitializeComponent();

            if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
            {
                this.tabrun.Text = "启动自动运行";
            }
            else
            {
                this.tabrun.Text = "提交运行表";
            }
        }

        private void InitLocalMethod_View()
        {
            DataGridViewCheckBoxColumn checkfile = new DataGridViewCheckBoxColumn();
            checkfile.Name = "bfilename";
            checkfile.Width = 40;
            checkfile.HeaderText = "选择";
            LocalMethodView.Columns.Add(checkfile);
            DataGridViewTextBoxColumn filename = new DataGridViewTextBoxColumn();
            filename.Name = "lasttime";
            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 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);

            INIOperation runtable = new INIOperation(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_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 = "1";
            }

            this.updategv.Enabled = false;
        }

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


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

            for (int i = 0; i < LocalMethodView.Rows.Count; i++)
            {
                if ((bool)LocalMethodView.Rows[i].Cells[0].EditedFormattedValue == true)
                {
                    tmp.filename = (string)LocalMethodView.Rows[i].Cells[1].Value;
                    tmp.runtime = "0";
                    tmp.runcount = "1";
                    tmp.rundelay = "1";
                    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(globaldata.connection_ip != null)
            {
                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);
          //          sendname = sendfilename;
           //         Console.WriteLine(sendname.ToString());
                    runtabclient.WtClientCopytoServer(sendfilename, sendname, "\\Hard Disk\\仪器方法\\");
                    Thread.Sleep(100);
                }
                runtabclient.WtClientClose();
            }
          

        }

        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)
        {
            if (selectionIdx > -1)
            {
                RunTableView.Rows[selectionIdx].Selected = true;
                RunTableView.CurrentCell = RunTableView.Rows[selectionIdx].Cells[0];
            }
        }


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

        int cur_edit;
        string cur_filename;
        private void EditRow_Click(object sender, EventArgs e)
        {
            int index = RunTableView.SelectedRows[0].Index;
           // RunTableView.Rows[index].Selected = false;
           // RunTableView.CurrentCell = RunTableView.Rows[cur_Row].Cells[cur_Column];

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

        private void updategv_Click(object sender, EventArgs e)
        {

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

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

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

            RunTableView.Rows.Insert(cur_edit,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 = "";
        }

        public event SendUpdateCMD sendupdatecmd;
        private void tabrun_Click(object sender, EventArgs e)
        {
            string sendname = null;
            if (globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab != null && globaldata.connection_ip != null)
            {
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 2;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;

                this.tabrun.Enabled = false;

                FileServerClient bfclient = new FileServerClient();
                sendname = null;
                bfclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                sendname = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, "RunMethod.ini");
                bfclient.WtClientCopytoServer("RunMethod.ini", sendname, "\\Hard Disk\\运行表\\");
                bfclient.WtClientClose();

               // Thread.Sleep(500);
              
                sendupdatecmd(false);
                this.tabrun.Enabled = true;
            }

            this.Close();

        }

        private void rtsave_Click(object sender, EventArgs e)
        {

            if (System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab))
            {
                System.IO.File.Delete(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab);
                StreamWriter sw = new StreamWriter(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab, false, System.Text.Encoding.Unicode);
                sw.WriteLine("[运行表]");
                sw.Close();
                //System.IO.File.Create(globaldata.cur_RunTab);
            }

            INIOperation runtable = new INIOperation(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab);
            string file = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab;
            string subkey;
            string sendname;
            runtable.INIEmptySection(file, "运行表");
            runtable.INIEmptySection(file, "循环");
            runtable.INIEmptySection(file, "运行时间");
            runtable.INIWriteValue(file, "运行表", "0", "开机");
            runtable.INIWriteValue(file, "循环", "0", "1");
            runtable.INIWriteValue(file, "运行时间", "0", "1");

            bool rbet;
            FileServerClient rtclient = null;
            if(globaldata.connection_ip != null)
            {
                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());
              rbet  = runtable.INIWriteValue(file, "循环", subkey, RunTableView.Rows[i].Cells[3].Value.ToString());
              rbet =  runtable.INIWriteValue(file, "运行时间", subkey, RunTableView.Rows[i].Cells[2].Value.ToString());

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

            sendname = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, "RunMethod.ini");
            rtclient.WtClientCopytoServer("RunMethod.ini", sendname, "\\Hard Disk\\运行表\\");

            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(globaldata.connection_ip != null)
                sendstopcmd();

        }   
    }
}
