using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using MeasureData;
using MeasureThread;
using FileManager;
using DBManager;

using System.Data.SQLite;

namespace WindowsFormsApp1
{
    public partial class MainForm : Form
    {
        #region 成员变量
        private BackgroundWorker m_BackgroundWorker;// 申明后台对象
        /// <summary>
        /// 测量文件
        /// </summary>
        public MeasureFile m_MeasureFile;
        
        /// 测量线程  
        public Measure m_Ms;

        //自动对焦函数
        public FocusParam m_focusParam;

        enum WorkType
        {
            AutoFocus =  1,
            AllThing = 2
        };

        WorkType m_work;

        #endregion
        #region 构造函数
        public MainForm()
        {
            InitializeComponent();

            m_BackgroundWorker = new BackgroundWorker(); // 实例化后台对象 
            m_BackgroundWorker.WorkerReportsProgress = true; // 设置可以通告进度 
            m_BackgroundWorker.WorkerSupportsCancellation = true; // 设置可以取消 
            m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
            m_BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
            m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);

            LogManager.InitManulLog();

            m_focusParam = new FocusParam();
            m_work = new WorkType();
        }
        #endregion
        #region 测量线程
        void DoWork(object sender, DoWorkEventArgs e)
        {
            m_Ms = new Measure("","","");
            m_Ms.InitMeas(m_MeasureFile);
            m_Ms.SendThreadStatus += new ThreadStatusHandler(displayMessage); //注册事件

            if (m_work == WorkType.AutoFocus)
            {
                //自动对焦
                //int nWd;
                //m_Ms.AutoFocus(m_focusParam, out nWd);
                //double wd = (double)nWd / 100.0;
                //tB_WD.Text = wd.ToString();
            }
            else
            {
                //自动测量的全过程
                m_Ms.DoMeasure();
            }
            
            //定位
            //切割
            //分析位置
            //截面

        }

        public void displayMessage(object sender, ThreadStatusEventArgs e)
        {
            //主界面显示内容
            this.BeginInvoke((Action)delegate
            {
                this.listmsg.Items.Add(e.Time.ToString() + e.State);
            });
        }

        void UpdateProgress(object sender, ProgressChangedEventArgs e)
        {
        }
        void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
        {
        }
        #endregion
        #region 按钮操作
        /// <summary>
        /// 新建文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNewFile_Click(object sender, EventArgs e)
        {
            m_MeasureFile = new MeasureFile();
            if (!m_MeasureFile.New())
            {
                return;
            }
            else
            {
                MessageBox.Show("新建测量文件成功。");
            }
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveFile_Click(object sender, EventArgs e)
        {
            if (m_MeasureFile == null)
            {
                MessageBox.Show("请新建一个测量文件");
            }
            else
            {
                m_MeasureFile.Save();                
            }
        }

        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFile_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (m_BackgroundWorker.IsBusy)
            {
                m_BackgroundWorker.CancelAsync();
            }

        }

        /// <summary>
        /// 加载切割孔
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoadCutHoles_Click(object sender, EventArgs e)
        {
            if (m_MeasureFile == null)
            {
                MessageBox.Show("请新建一个测量文件");
            }
            else
            {
                if (!m_MeasureFile.GetCutHolesFromFile(""))
                {
                    MessageBox.Show("导入切孔失败");
                }

                this.CutHoleGridView.Rows.Clear();
                List<CutHole> listHoles = m_MeasureFile.ListCutHole;
                foreach (CutHole hole in listHoles)
                {
                    //在CutHoleGridView中，添加切孔信息
                    int index = this.CutHoleGridView.Rows.Add();
                    this.CutHoleGridView.Rows[index].Cells[0].Value = hole.HoleName;

                    SemPosition pos = hole.Position;
                    this.CutHoleGridView.Rows[index].Cells[1].Value = pos.X;
                    this.CutHoleGridView.Rows[index].Cells[2].Value = pos.Y;
                    this.CutHoleGridView.Rows[index].Cells[3].Value = pos.Z;
                    this.CutHoleGridView.Rows[index].Cells[4].Value = pos.M;
                    this.CutHoleGridView.Rows[index].Cells[5].Value = pos.R;
                    this.CutHoleGridView.Rows[index].Cells[6].Value = pos.T;
                }
            }
        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (m_MeasureFile == null)
            {
                MessageBox.Show("请新建一个测量文件");
                listmsg.Items.Clear();
            }
            else
            {
                if (m_BackgroundWorker.IsBusy)
                {
                    MessageBox.Show("线程已经运行");
                    return;
                }
                m_BackgroundWorker.RunWorkerAsync(this);
            }
        }

        /// <summary>
        /// 调区FIB模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btFIB_Click(object sender, EventArgs e)
        {
            string FilePathName;
            string fileNameWithoutExtension;
            //新建一个文件对话框
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            //设置对话框标题
            pOpenFileDialog.Title = "选择模板文件";
            //设置打开文件类型
            pOpenFileDialog.Filter = "ely文件（*.ely）|*.ely";
            //监测文件是否存在
            pOpenFileDialog.CheckFileExists = true;
            //文件打开后执行以下程序
            if (pOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                FilePathName = System.IO.Path.GetFullPath(pOpenFileDialog.FileName);                             //绝对路径
                fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(FilePathName);
                this.tBFIBTemp.Text = fileNameWithoutExtension;
            }
        }

        private void btParamOK_Click(object sender, EventArgs e)
        {
            if (m_MeasureFile == null)
            {
                MessageBox.Show("请新建一个测量文件");
                this.listmsg.Items.Add("请新建一个测量文件");
            }
            else
            {
                m_MeasureFile.MParam.PT = this.cBIsPT.Checked;
                m_MeasureFile.MParam.SampleName = this.tBSampleName.Text;
                m_MeasureFile.MParam.FIBTemp = this.tBFIBTemp.Text;
                //m_MeasureFile.MParam.FocusMode = this.cBIsManul.Checked;

                MessageBox.Show("参数设置成功");
            }
        }

        #endregion

        //定位操作
        private void button5_Click(object sender, EventArgs e)
        {

        }

        //切割操作
        private void button6_Click(object sender, EventArgs e)
        {

        }

        //分析位置操作
        private void button7_Click(object sender, EventArgs e)
        {

        }

        //观测截面
        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void btImgPath_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "选择拍图保存的文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show("图像文件夹不能为空");
                    return;
                }

                m_focusParam.Path = dialog.SelectedPath;
                tBImgPath.Text = dialog.SelectedPath;

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (tBImgPath.Text == "" ||
               tB_Up.Text == "" ||
               tB_Down.Text == "" ||
               tB_Step.Text == "" ||
               tB_fRange.Text == "" ||
               tB_fStep.Text == "")
            {
                MessageBox.Show("请输入完整的参数");
                return;
            }
            //保存自动对焦函数
            m_focusParam.Path = tBImgPath.Text;            
            m_focusParam.Step = float.Parse(tB_Step.Text);
            m_focusParam.Range = float.Parse(tB_fRange.Text);
            m_focusParam.fStep = float.Parse(tB_fStep.Text);

            float fUP = float.Parse(tB_Up.Text);
            float fDown = float.Parse(tB_Down.Text);

            if (fDown <= fUP)
            {
                MessageBox.Show("请输入下限大于上限的值");
                return;
            }
           
            m_focusParam.UP = float.Parse(tB_Up.Text);
            m_focusParam.Down = float.Parse(tB_Down.Text);            
        }

        private void tB_TextChanged(object sender, EventArgs e)
        {

        }

        //输入限制只能是数字
        private void textBox_KeyPress(string text, object sender, KeyPressEventArgs e)
        {

            //允许输入数字、小数点、删除键和负号  
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-'))
            {
                MessageBox.Show("请输入正确的数字");
                text = "";
                e.Handled = true;
            }
            if (e.KeyChar == (char)('-'))
            {
                if (text != "")
                {
                    MessageBox.Show("请输入正确的数字");
                    text = "";
                    e.Handled = true;
                }
            }
            //小数点只能输入一次  
            if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1)
            {
                MessageBox.Show("请输入正确的数字");
                text = "";
                e.Handled = true;
            }
            //第一位不能为小数点  
            if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")
            {
                MessageBox.Show("请输入正确的数字");
                text = "";
                e.Handled = true;
            }
            //第一位是0，第二位必须为小数点  
            if (e.KeyChar != (char)('.') && ((TextBox)sender).Text == "0")
            {
                MessageBox.Show("请输入正确的数字");
                text = "";
                e.Handled = true;
            }
            //第一位是负号，第二位不能为小数点  
            if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.'))
            {
                MessageBox.Show("请输入正确的数字");
                text = "";
                e.Handled = true;
            }
        }

        private void tB_Up_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tB_Up.Text, sender, e);
        }

        private void tB_Down_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tB_Down.Text, sender, e);
        }

        private void tB_Step_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tB_Step.Text, sender, e);
        }

        private void tB_fRange_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tB_fRange.Text, sender, e);
        }

        private void tB_fStep_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tB_fStep.Text, sender, e);
        }

        private void tbAutoFocus_Click(object sender, EventArgs e)
        {
            m_work = WorkType.AutoFocus;
            // 调用对焦线程
            if (m_MeasureFile == null)
            {
                MessageBox.Show("请新建一个测量文件");
                listmsg.Items.Clear();
            }
            else
            {
                if (m_BackgroundWorker.IsBusy)
                {
                    MessageBox.Show("线程已经运行");
                    return;
                }
                m_BackgroundWorker.RunWorkerAsync(this);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            MeasureDB db = new MeasureDB(m_MeasureFile);
         
        }
    }
}
