using CCDCount.DLL;
using CCDCount.MODEL.CameraClass;
using CCDCount.MODEL.ConfigModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CCDCount.Forms
{
    public partial class SettingForm : Form
    {
        int Nowindex = -1;
        List<MainThreadClass> LoadLsMainThread = null;
        List<MainThreadClass> NowLoadLsMianThread = new List<MainThreadClass>();
        MainThreadClass LoadMainThread  = null;
        SaveConfigModel NowLoadConfig = null;
        //从外部加载的信息
        List<SaveConfigModel> LoadConfigs = new List<SaveConfigModel>();

        //将要保存的信息
        List<SaveConfigModel> Configs = new List<SaveConfigModel>();

        CameraClass CameraClass  =  new CameraClass();

        public SettingForm(List<MainThreadClass> lsMainThread)
        {
            InitializeComponent();
            LoadLsMainThread = lsMainThread;
        }

        /// <summary>
        /// 保存参数
        /// </summary>
        public void SaveConfig()
        {
            if (!Directory.Exists(".\\Config\\")) Directory.CreateDirectory(".\\Config\\");
            {
                XmlStorage.SerializeToXml(Configs, ".\\Config\\CCDCountConfig.xml");
            }

        }

        private void SettingForm_Load(object sender, EventArgs e)
        {
            CameraConfig cameraConfig = null;
            ShuLiConfigClass shuLiConfig = null;
            for (int i = 0; i < LoadLsMainThread.Count; i++)
            {
                LoadLsMainThread[i].GetAllConfigValue(out cameraConfig, out shuLiConfig);
                LoadConfigs.Add(new SaveConfigModel() { 
                    CameraConfig = cameraConfig,
                    ShuLiConfigClass = shuLiConfig
                });
            }
            InitIdentifyCountCobBox();
            InitCameraCobox();
            radioButton1.Checked = true;
        }

        private void InitIdentifyCountCobBox()
        {
            IdentifyCountCobBox.Items.Clear();
            for (int i = 1; i <= 4; i++)
            {
                IdentifyCountCobBox.Items.Add(i);
            }
            IdentifyCountCobBox.SelectedIndex = 0;
        }

        private void InitCameraCobox()
        {
            List<CameraInfoClass> CameraInfoList = new List<CameraInfoClass>();
            CameraClass.GetCameraList(out CameraInfoList);
            if  (CameraInfoList.Count > 0)
            {
                CameraConbox.Items.Clear();
                CameraConbox.Items.Add("请选择相机");
                foreach (var item in CameraInfoList)
                {
                    CameraConbox.Items.Add(item.DeviceName + "_" + item.DeviceSN);
                }
                CameraConbox.SelectedIndex = 0;
            }
        }

        private void IdentifyCountCobBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabPanel.Controls.Clear();
            Configs.Clear();
            NowLoadLsMianThread.Clear();
            string ButtonText = string.Empty;
            for (int i = 1; i <= (int)IdentifyCountCobBox.SelectedItem; i++)
            {
                ButtonText = "数粒" + i;
                //创建一个按钮,加载与此相机绑定的配置
                if (i <= LoadConfigs.Count())
                {
                    string camername = LoadConfigs[i - 1].CameraConfig.CameraName;
                    if(camername == string.Empty) camername = "数粒" + i;
                    ButtonText = camername;
                    //重新的CameraNo排序
                    LoadConfigs[i-1].CameraConfig.CamerNo = i-1;
                    //将从外加载的配置文件复制进当前加载的配置文件
                    Configs.Add(LoadConfigs[i-1]);
                }
                //没有与此相机绑定的配置文件，创建一个配置实例
                else
                {
                    Configs.Add(new SaveConfigModel()
                    {
                        CameraConfig = new CameraConfig() { CamerNo = i - 1 },
                        ShuLiConfigClass = new ShuLiConfigClass()
                    });
                }
                if (i <= LoadLsMainThread.Count())
                {
                    NowLoadLsMianThread.Add(LoadLsMainThread[i-1]);
                }
                else
                {
                    NowLoadLsMianThread.Add(new MainThreadClass(
                        Configs[i - 1].ShuLiConfigClass,
                        Configs[i - 1].CameraConfig
                    ));
                }
                Button button = new Button()
                {
                    Text = ButtonText,
                    Name = string.Format("ShuLiConfigBtn_{0}", i-1),
                    Size = new Size(120, TabPanel.Height - 1),
                    Location = new Point(120 * (i - 1), 0)
                };
                if(i <= Configs.Count())
                {
                    button.Click += ShuLiConfigBtn_Click;
                }
                TabPanel.Controls.Add(button);
            }
        }

        private void ShuLiConfigBtn_Click(object sender, EventArgs e)
        {
            string buttonName = string.Empty;
            if (sender is Button thisbutton)
            {
                buttonName = thisbutton.Name;
            }
            if (buttonName != string.Empty)
            {
                Nowindex = Convert.ToInt32(buttonName.Split('_')[1]);
            }

            if (Nowindex < Configs.Count() && Nowindex != -1)
            {
                LoadMainThread = NowLoadLsMianThread[Nowindex];
                NowLoadConfig = Configs[Nowindex];
                LoadConfigToForm(Configs[Nowindex]);
            }
        }

        private void LoadConfigToForm(SaveConfigModel LoadConfig) 
        {
            if(LoadMainThread != null)
            {
                //判断是否已经绑定相机
                if(LoadMainThread.cameraConfig.CameraSNNum!=string.Empty)
                {
                    //相机选择框尝试选择绑定的相机
                    CameraConbox.SelectedItem = LoadMainThread.cameraConfig.DeviceName + "_" + LoadMainThread.cameraConfig.CameraSNNum;
                }
                if(CameraConbox.SelectedItem.ToString()!=string.Empty&&CameraConbox.SelectedItem.ToString()!= "请选择相机")
                {
                    ExposureTimeTbx.Text = NowLoadConfig.CameraConfig.ExposureTimeValue.ToString();
                    AcquistionLineRateLabTbx.Text = NowLoadConfig.CameraConfig.AcquistionLineRateValue.ToString();
                    ImageWidthTbx.Text = NowLoadConfig.CameraConfig.Width.ToString();
                    ImageHeightTbx.Text = NowLoadConfig.CameraConfig.Height.ToString();
                    CamUserNameTbx.Text = NowLoadConfig.CameraConfig.CameraName;
                    CamOffsetXTbx.Text = NowLoadConfig.CameraConfig.OffsetX.ToString();
                }
                RegionThresholdTbx.Text =  NowLoadConfig.ShuLiConfigClass.RegionThreshold.ToString();
                ChannelTbx.Text  =  NowLoadConfig.ShuLiConfigClass.Channel.ToString();
                NoiseFilterTbx.Text =  NowLoadConfig.ShuLiConfigClass.NoiseFilter_Threshold.ToString();
                //切换识别模式
                switch(NowLoadConfig.ShuLiConfigClass.PandingCode)
                {
                    case -1:
                        radioButton1.Checked = true;
                        break;
                    case 0:
                        radioButton2.Checked = true;
                        break;
                    case 1:
                        radioButton3.Checked = true;
                        break;
                    case 2:
                        radioButton4.Checked = true;
                        break;
                }
            }
        }

        private void SaveAllConfig_Click(object sender, EventArgs e)
        {
            SaveConfig();
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if(radioButton1.Checked)
            {
                PanDuanParaPanel.Controls.Clear();
                PanDuanParaPanel.Height = 10;
                if(NowLoadConfig == null) return;
                NowLoadConfig.ShuLiConfigClass.PandingCode = -1;
                Configs[Nowindex] = NowLoadConfig;
            }
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked)
            {
                PanDuanParaPanel.Controls.Clear();
                PanDuanParaPanel.Height = 150;
                if (NowLoadConfig == null) return;
                Label label5 = new Label()
                {
                    Text = "合格粒宽范围：",
                    Location = new Point(10, 10),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label5);

                TextBox textBox1 = new TextBox()
                {
                    Location = new Point(10, 30),
                    Name = "MIN_OBJECT_WIDTH_TBX",
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MIN_OBJECT_WIDTH.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox1);

                Label label2 = new Label()
                {
                    Text = "-",
                    Location = new Point(75, 35),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label2);

                TextBox textBox2 = new TextBox()
                {
                    Name = "MAX_OBJECT_WIDTH_TBX",
                    Location = new Point(100, 30),
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MAX_OBJECT_WIDTH.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox2);

                Label label3 = new Label()
                {
                    Text = "合格粒高范围：",
                    Location = new Point(10, 60),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label3);

                TextBox textBox3 = new TextBox()
                {
                    Location = new Point(10, 80),
                    Name = "MIN_OBJECT_HEIGHT_TBX",
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MIN_OBJECT_HEIGHT.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox3);

                Label label4 = new Label()
                {
                    Text = "-",
                    Location = new Point(75, 85),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label4);

                TextBox textBox4 = new TextBox()
                {
                    Location = new Point(100, 80),
                    Name = "MAX_OBJECT_HEIGHT_TBX",
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MAX_OBJECT_HEIGHT.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox4);

                NowLoadConfig.ShuLiConfigClass.PandingCode = 1;
                Configs[Nowindex] = NowLoadConfig;
            }
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton3.Checked)
            {
                PanDuanParaPanel.Controls.Clear();
                PanDuanParaPanel.Height = 100;
                if (NowLoadConfig == null) return;
                Label label5 = new Label()
                {
                    Text = "合格粒面积范围：",
                    Location = new Point(10, 10),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label5);

                TextBox textBox1 = new TextBox()
                {
                    Location = new Point(100, 30),
                    Name = "MaxArea_TBX",
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MaxArea.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox1);

                Label label2 = new Label()
                {
                    Text = "-",
                    Location = new Point(75, 35),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label2);

                TextBox textBox2 = new TextBox()
                {
                    Name = "MinArea_TBX",
                    Location = new Point(10, 30),
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MinArea.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox2);

                NowLoadConfig.ShuLiConfigClass.PandingCode = 2;
                Configs[Nowindex] = NowLoadConfig;
            }
        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton4.Checked)
            {
                PanDuanParaPanel.Controls.Clear();
                PanDuanParaPanel.Height = 160;
                if (NowLoadConfig == null) return;

                Label label5 = new Label()
                {
                    Text = "合格粒宽范围：",
                    Location = new Point(10, 10),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label5);

                TextBox textBox1 = new TextBox()
                {
                    Location = new Point(10, 30),
                    Name = "MIN_OBJECT_WIDTH_TBX",
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MIN_OBJECT_WIDTH.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox1);

                Label label2 = new Label()
                {
                    Text = "-",
                    Location = new Point(75, 35),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label2);

                TextBox textBox2 = new TextBox()
                {
                    Name = "MAX_OBJECT_WIDTH_TBX",
                    Location = new Point(100, 30),
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MAX_OBJECT_WIDTH.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox2);

                Label label3 = new Label()
                {
                    Text = "合格粒高范围：",
                    Location = new Point(10, 60),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label3);

                TextBox textBox3 = new TextBox()
                {
                    Location = new Point(10, 80),
                    Name = "MIN_OBJECT_HEIGHT_TBX",
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MIN_OBJECT_HEIGHT.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox3);

                Label label4 = new Label()
                {
                    Text = "-",
                    Location = new Point(75, 85),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label4);

                TextBox textBox4 = new TextBox()
                {
                    Location = new Point(100, 80),
                    Name = "MAX_OBJECT_HEIGHT_TBX",
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MAX_OBJECT_HEIGHT.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox4);

                Label label6 = new Label()
                {
                    Text = "合格粒面积范围：",
                    Location = new Point(10, 110),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label6);

                TextBox textBox5 = new TextBox()
                {
                    Location = new Point(10, 130),
                    Name = "MinArea_TBX",
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MinArea.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox5);

                Label label7 = new Label()
                {
                    Text = "-",
                    Location = new Point(75, 135),
                    AutoSize = true
                };
                PanDuanParaPanel.Controls.Add(label7);

                TextBox textBox6 = new TextBox()
                {
                    Name = "MaxArea_TBX",
                    Location = new Point(100, 130),
                    Width = 50,
                    Text = NowLoadConfig.ShuLiConfigClass.MaxArea.ToString(),
                };
                PanDuanParaPanel.Controls.Add(textBox6);

                NowLoadConfig.ShuLiConfigClass.PandingCode = 3;
                Configs[Nowindex] = NowLoadConfig;
            }
        }

        private void CameraConbox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string ThisItemSN = CameraConbox.SelectedItem.ToString();
            if(LoadMainThread == null || ThisItemSN == LoadMainThread.cameraConfig.DeviceName + "_" + LoadMainThread.cameraConfig.CameraSNNum) return;
            if (ThisItemSN != string.Empty && ThisItemSN != "请选择相机")
            {
                try
                {
                    ThisItemSN = ThisItemSN.Split('_')[1];
                }
                catch (Exception)
                {
                    ThisItemSN = string.Empty;
                }
                if (ThisItemSN == string.Empty) return;
                if (LoadMainThread.CameraRunStatic)
                {
                    var confirmResult = MessageBox.Show("检测到正在识别，切换相机需要关闭识别，是否继续切换",
                                      "切换确认", MessageBoxButtons.YesNo);
                    if (confirmResult == DialogResult.No)
                    {
                        CameraConbox.SelectedItem = LoadMainThread.cameraConfig.DeviceName + "_" + LoadMainThread.cameraConfig.CameraSNNum;
                        return;
                    }
                    LoadMainThread.StopMianThread();
                }
                if (LoadMainThread.ReLoadCamera(ThisItemSN))
                {
                    CameraConfig CameraConfig = LoadMainThread.GetCameraConfig();
                    if (CameraConfig != null)
                            {
                                ExposureTimeTbx.Text = CameraConfig.ExposureTimeValue.ToString();
                                NowLoadConfig.CameraConfig.ExposureTimeValue = CameraConfig.ExposureTimeValue;
                                AcquistionLineRateLabTbx.Text = CameraConfig.AcquistionLineRateValue.ToString();
                                NowLoadConfig.CameraConfig.AcquistionLineRateValue = CameraConfig.AcquistionLineRateValue;
                                ImageWidthTbx.Text = CameraConfig.Width.ToString();
                                NowLoadConfig.CameraConfig.Width = CameraConfig.Width;
                                ImageHeightTbx.Text = CameraConfig.Height.ToString();
                                NowLoadConfig.CameraConfig.Height = CameraConfig.Height;
                                CamUserNameTbx.Text = CameraConfig.CameraName;
                                NowLoadConfig.CameraConfig.CameraName = CameraConfig.CameraName;
                                CamOffsetXTbx.Text = CameraConfig.OffsetX.ToString();
                                NowLoadConfig.CameraConfig.OffsetX = CameraConfig.OffsetX;
                                NowLoadConfig.CameraConfig.CameraSNNum = CameraConfig.CameraSNNum;
                                NowLoadConfig.CameraConfig.CameraName = CameraConfig.CameraName;
                                NowLoadConfig.CameraConfig.DeviceName = CameraConfig.DeviceName;
                                NowLoadConfig.ShuLiConfigClass.CameraSN = CameraConfig.CameraSNNum; 
                                Configs[Nowindex] = NowLoadConfig;
                            }
                }
                else
                {
                    MessageBox.Show("切换相机失败！");
                    CameraConbox.SelectedItem = LoadMainThread.cameraConfig.DeviceName + "_" + LoadMainThread.cameraConfig.CameraSNNum;
                    return;
                }
            }
            else
            {
                if (LoadMainThread.CameraRunStatic)
                {
                    var confirmResult = MessageBox.Show("检测到正在识别，切换相机需要关闭识别，是否继续切换",
                                      "切换确认", MessageBoxButtons.YesNo);
                    if (confirmResult == DialogResult.No)
                    {
                        CameraConbox.SelectedItem = LoadMainThread.cameraConfig.DeviceName + "_" + LoadMainThread.cameraConfig.CameraSNNum;
                        return;
                    }
                    LoadMainThread.StopMianThread();
                }
                else
                {
                    LoadMainThread.DisposeCamera();
                }
                ExposureTimeTbx.Text = string.Empty;
                NowLoadConfig.CameraConfig.ExposureTimeValue = 0;
                AcquistionLineRateLabTbx.Text = string.Empty;
                NowLoadConfig.CameraConfig.AcquistionLineRateValue = 0;
                ImageWidthTbx.Text = string.Empty;
                NowLoadConfig.CameraConfig.Width = 0;
                ImageHeightTbx.Text = string.Empty;
                NowLoadConfig.CameraConfig.Height = 0;
                CamUserNameTbx.Text = string.Empty;
                NowLoadConfig.CameraConfig.CameraName = string.Empty;
                CamOffsetXTbx.Text = string.Empty;
                NowLoadConfig.CameraConfig.OffsetX = 0;
                NowLoadConfig.CameraConfig.CameraSNNum = string.Empty;
                NowLoadConfig.CameraConfig.CameraName = string.Empty;
                NowLoadConfig.CameraConfig.DeviceName = string.Empty;
                NowLoadConfig.ShuLiConfigClass.CameraSN = string.Empty;
                Configs[Nowindex] = NowLoadConfig;
            }
        }
    }
}
