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 System.Windows.Forms.DataVisualization.Charting;
using Extender;
using DBManager;
using MeasureData;
using System.Data.SQLite;

namespace OxfordTest
{
    public partial class Form1 : Form
    {

        //全局只有一个fatorySEM
        static ExtenderInterface factoryExtender = ExtenderInterface.Instance;
        //IExtenderControl iExtender = factoryExtender.IExtender;
        IExtenderControl iExtender ;
        public Form1()
        {
            InitializeComponent();
           
        }

        //获取电压
        private void button1_Click(object sender, EventArgs e)
        {
            tBHV.Text = iExtender.GetSEMVoltage().ToString();
        }

        //输入限制只能是数字
        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 button2_Click(object sender, EventArgs e)
        {
            iExtender.SetSEMVoltage(float.Parse(tBHVIn.Text));
        }

        //电压输入限制
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBHVIn.Text, sender, e);           
        }

        //获取工作距离
        private void button3_Click(object sender, EventArgs e)
        {
            tBWD.Text = iExtender.GetWorkingDistance().ToString();
        }

        //获取放大倍数 
        private void button4_Click(object sender, EventArgs e)
        {
            tBMag.Text = iExtender.GetMagnification().ToString();
        }
        //获取亮度
        private void button5_Click(object sender, EventArgs e)
        {
            tBBright.Text = iExtender.GetBrightness().ToString();
        }
        //获取对比度
        private void button6_Click(object sender, EventArgs e)
        {
            tBContast.Text = iExtender.GetContrast().ToString();
        }
        //设定工作距离
        private void button7_Click(object sender, EventArgs e)
        {
            iExtender.SetWorkingDistance(float.Parse(tBWDIn.Text));
        }
        //设定放大倍数
        private void button8_Click(object sender, EventArgs e)
        {
            iExtender.SetMagnification(float.Parse(tBMagIn.Text));
        }
        //设定亮度
        private void button9_Click(object sender, EventArgs e)
        {
            iExtender.SetBrightness(float.Parse(tBrightIn.Text));
        }
        //设定对比度
        private void button10_Click(object sender, EventArgs e)
        {
            iExtender.SetContrast(float.Parse(tBContrastIn.Text));
        }

        private void tBWDIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBWDIn.Text, sender, e);
        }

        private void tBMagIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBMagIn.Text, sender, e);
        }

        private void tBrightIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBrightIn.Text, sender, e);
        }

        private void tBContrastIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBContrastIn.Text, sender, e);
        }

        //获取X
        private void button11_Click(object sender, EventArgs e)
        {
            tBX.Text = iExtender.GetStageAtX().ToString();
        }
        //获取Y
        private void button12_Click(object sender, EventArgs e)
        {
            tBY.Text = iExtender.GetStageAtY().ToString();

        }
        //获取Z
        private void button13_Click(object sender, EventArgs e)
        {
            tBZ.Text = iExtender.GetStageAtZ().ToString();

        }
        //获取T
        private void button14_Click(object sender, EventArgs e)
        {
            tBT.Text = iExtender.GetStageAtT().ToString();

        }
        //获取R
        private void button15_Click(object sender, EventArgs e)
        {
            tBR.Text = iExtender.GetStageAtR().ToString();

        }
        //获取全部
        private void button21_Click(object sender, EventArgs e)
        {
            tBX.Text = iExtender.GetStageAtX().ToString();
            tBY.Text = iExtender.GetStageAtY().ToString();
            tBZ.Text = iExtender.GetStageAtZ().ToString();
            tBT.Text = iExtender.GetStageAtT().ToString();
            tBR.Text = iExtender.GetStageAtR().ToString();

        }
        //设定XY
        private void button22_Click(object sender, EventArgs e)
        {
            iExtender.MoveStageXY(float.Parse(tBXIn.Text), float.Parse(tBYIn.Text));
        }
        //设定全部
        private void button23_Click(object sender, EventArgs e)
        {
            float[] pos = new float[5];
            pos[0] = float.Parse(tBXIn.Text);
            pos[1] = float.Parse(tBYIn.Text);
            pos[2] = float.Parse(tBZIn.Text);
            pos[3] = float.Parse(tBTIn.Text);
            pos[4] = float.Parse(tBRIn.Text);
            iExtender.SetStagePosition(pos);
        }
        //设定X
        private void button16_Click(object sender, EventArgs e)
        {
            iExtender.SetStageGotoX(float.Parse(tBXIn.Text));
        }
        //设定Y
        private void button17_Click(object sender, EventArgs e)
        {
            iExtender.SetStageGotoY(float.Parse(tBYIn.Text));
        }
        //设定Z
        private void button18_Click(object sender, EventArgs e)
        {
            iExtender.SetStageGotoZ(float.Parse(tBZIn.Text));
        }
        //设定T
        private void button19_Click(object sender, EventArgs e)
        {
            iExtender.SetStageGotoT(float.Parse(tBTIn.Text));
        }
        //设定R
        private void button20_Click(object sender, EventArgs e)
        {
            iExtender.SetStageGotoR(float.Parse(tBRIn.Text));
        }

        private void tBXIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBXIn.Text, sender, e);
        }

        private void tBYIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBYIn.Text, sender, e);
        }

        private void tBZIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBZIn.Text, sender, e);
        }

        private void tBTIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBTIn.Text, sender, e);
        }

        private void tBRIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            textBox_KeyPress(tBRIn.Text, sender, e);
        }

        private void button24_Click(object sender, EventArgs e)
        {
            
            string path = System.Environment.CurrentDirectory;
            iExtender.GrabImage(path+"\\测试.tif", 0, 0, 0, 0, 0);
            Bitmap ExtenderImage = iExtender.GetBitmap();
            if (ExtenderImage != null)
            {
                pBImage.Image = ExtenderImage;
            }
        }

        int li = 0;
        //点采集
        private void button25_Click(object sender, EventArgs e)
        {
            
            long[] XrayData = new long[2000];
            Dictionary<string, double> listElement = new Dictionary<string, double>();
            iExtender.XrayPointCollecting(2000,Convert.ToInt32(txtpx1.Text), Convert.ToInt32(txtpy1.Text), out XrayData, out listElement);

            ShowData(XrayData, listElement);
            li++;
          
        }

        void ShowData(long[] XrayData, Dictionary<string, double> listElement)
        {
            Series series = chart1.Series[0];
            series.Points.Clear();

            for (int i = 0; i < 2000; i++)
            {
                series.Points.AddXY(i, XrayData[i]);
            }

            this.dataGridView1.Rows.Clear();
            int index = 0; 

            var ie = listElement.GetEnumerator();
            while (ie.MoveNext())
            {
                this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[index].Cells[0].Value = ie.Current.Key;
                this.dataGridView1.Rows[index].Cells[1].Value = ie.Current.Value;
                index++;
            }

        }

        void ShowReadData(long[] XrayData)
        {
            Series series = chart1.Series[1];
            series.Points.Clear();

            for (int i = 0; i < 2000; i++)
            {
                series.Points.AddXY(i, XrayData[i]);
            }

        }

        //面采集
        private void button26_Click(object sender, EventArgs e)
        {
            long[] XrayData = new long[2000];
            Dictionary<string, double> listElement = new Dictionary<string, double>();

            List<Segment> listSeg = new List<Segment>();

            Segment seg1 = new Segment();
            seg1.X = 1;
            seg1.Y = 1;
            seg1.Length = 10;

            listSeg.Add(seg1);

            Segment seg2 = new Segment();
            seg2.X = 1;
            seg2.Y = 10;
            seg2.Length = 10;

            listSeg.Add(seg2);

            iExtender.XrayAreaCollectiong(200, listSeg, out XrayData, out listElement);
            ShowData(XrayData, listElement);
        }

        private void btnCreateDB_Click(object sender, EventArgs e)
        {
            MeasureFile msf = new MeasureFile();
            //msf.FileName = @"E:\HOZ\Test\asd.msf";
            MeasureDB db = new MeasureDB(msf);
        }

        private void btnReadP_Click(object sender, EventArgs e)
        {
            SQLiteConnection m_db = new SQLiteConnection("data source =" + @"E:\HOZ\Test\MeasureDB.db");
            m_db.Open();

            String sql = "Select XrayData from XrayData where ID =" + NUDNum.Value.ToString();
            //SQLiteDataAdapter adapter = new SQLiteDataAdapter(sql, m_db);
            //DataSet ds = new DataSet();
            //adapter.Fill(ds);
            //DataTable dt = ds.Tables[0];

            SQLiteCommand cmd = new SQLiteCommand(sql, m_db);
            SQLiteDataReader sdr = cmd.ExecuteReader();
            sdr.Read();
            byte[] blob = null;
            blob = new byte[sdr.GetBytes(0, 0, null, 0, int.MaxValue)];
            sdr.GetBytes(0, 0, blob, 0, blob.Length);

            sdr.Close();
            m_db.Close();
            m_db.Dispose();

            long[] rd = new long[blob.Length / 4];
            for(int i=0;i<rd.Length;i++)
            {
                long temp = BitConverter.ToInt32(blob, i * 4);
                rd[i] = temp + 10;
            }

            ShowReadData(rd);
        }

        int xraydata_id = 1;
        int analysispoints_id = 1;
        private void btnTest_Click(object sender, EventArgs e)
        {
            List<Point> listPoints = new List<Point>();
            List<List<Segment>> listFeature = new List<List<Segment>>();
            List<Segment> ls = new List<Segment>();

            listPoints.Add(new Point(Convert.ToInt32(txtpx1.Text), Convert.ToInt32(txtpy1.Text)));
            listPoints.Add(new Point(Convert.ToInt32(txtpx2.Text), Convert.ToInt32(txtpy2.Text)));
            listPoints.Add(new Point(Convert.ToInt32(txtpx3.Text), Convert.ToInt32(txtpy3.Text)));
            listPoints.Add(new Point(Convert.ToInt32(txtpx4.Text), Convert.ToInt32(txtpy4.Text)));
            listPoints.Add(new Point(Convert.ToInt32(txtpx5.Text), Convert.ToInt32(txtpy5.Text)));

            Segment sgt = new Segment();
            sgt.X = Convert.ToInt32(txtarea1x1.Text);
            sgt.Y = Convert.ToInt32(txtarea1y1.Text);
            sgt.Length = Convert.ToInt32(txtarea1l1.Text);
            ls.Add(sgt);
            sgt = new Segment();
            sgt.X = Convert.ToInt32(txtarea1x2.Text);
            sgt.Y = Convert.ToInt32(txtarea1y2.Text);
            sgt.Length = Convert.ToInt32(txtarea1l2.Text);
            ls.Add(sgt);
            sgt = new Segment();
            sgt.X = Convert.ToInt32(txtarea1x3.Text);
            sgt.Y = Convert.ToInt32(txtarea1y3.Text);
            sgt.Length = Convert.ToInt32(txtarea1l3.Text);
            ls.Add(sgt);

            listFeature.Add(ls);

            ls = new List<Segment>();
            sgt = new Segment();
            sgt.X = Convert.ToInt32(txtarea2x1.Text);
            sgt.Y = Convert.ToInt32(txtarea2y1.Text);
            sgt.Length = Convert.ToInt32(txtarea2l1.Text);
            ls.Add(sgt);
            sgt = new Segment();
            sgt.X = Convert.ToInt32(txtarea2x2.Text);
            sgt.Y = Convert.ToInt32(txtarea2y2.Text);
            sgt.Length = Convert.ToInt32(txtarea2l2.Text);
            ls.Add(sgt);
            sgt = new Segment();
            sgt.X = Convert.ToInt32(txtarea2x3.Text);
            sgt.Y = Convert.ToInt32(txtarea2y3.Text);
            sgt.Length = Convert.ToInt32(txtarea2l3.Text);
            ls.Add(sgt);

            listFeature.Add(ls);

            //m_MeasDB.InsetAPoint(analysispoints_id, pname[analysispoints_id-1], @"D:\\", listPoints.Count, listFeature.Count);

            long[] XrayData = null;
            Dictionary<string, double> listElement = null;
            

            //点扫描数据存储
            for(int i=0;i<listPoints.Count;i++)
            {

                XrayData = new long[2000];
                listElement = new Dictionary<string, double>();

                iExtender.XrayPointCollecting(msf.MParam.EDSParam.DwellTime, listPoints[i].X, listPoints[i].Y, out XrayData, out listElement);

                //m_MeasDB.InsertAPointXay(analysispoints_id, xraydata_id, listPoints[i].X, listPoints[i].Y, XrayData, listElement);
                xraydata_id++;
            }

            //面扫描数据存储
            int AreasNo = 0;
            foreach (List<Segment> listSeg in listFeature)
            {
                XrayData = new long[2000];
                listElement = new Dictionary<string, double>();

                iExtender.XrayAreaCollectiong(msf.MParam.EDSParam.AreaTime, listSeg, out XrayData, out listElement);

                //写入数据库

                AreasNo++;
                //m_MeasDB.InsertAAreaXay(analysispoints_id, xraydata_id, AreasNo, listSeg, XrayData, listElement);
                xraydata_id++;
            }
        
            

            analysispoints_id++;

            MessageBox.Show("测试完成！");
        }

        MeasureDB m_MeasDB = null;
        MeasureFile msf = null;
        List<String> pname = new List<string>();
        private void Form1_Load(object sender, EventArgs e)
        {
            //向数据库插入分析点数据
            msf = new MeasureFile();
            msf.FileName = @"E:\HOZ\Test\asd.msf";
            msf.MParam.EDSParam.DwellTime = 200;
            msf.MParam.EDSParam.AreaTime = 200;
            m_MeasDB = new MeasureDB(msf);
            pname.Add("aaaa");
            pname.Add("bbbb");
            pname.Add("cccc");
            OTSMeasureOutputNlog lowWindow = new OTSMeasureOutputNlog();
            lowWindow.Visible = true;
        }

        private void button27_Click(object sender, EventArgs e)
        {
            try
            {
                 iExtender = factoryExtender.IExtender;
                MessageBox.Show("连接能谱成功");
            }
            catch (Exception x)
            {
                MessageBox.Show("oxford 初始化失败" + x.Message);
                
            }
           
        }

        private void button28_Click(object sender, EventArgs e)
        {
            var log = NLog.LogManager.GetCurrentClassLogger();
            log.Info("sfdasdfasdsafgasddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",false);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (iExtender != null)
            {
               iExtender.CloseExtender();
            }
        }
    }
}
