using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MeasureData;
using System.Configuration;
using FileManager;
using System.IO;

namespace HOZProject
{
    public partial class UControl_Init : UserControl
    {
        #region 全局变量
        String[] sT;
        String[] firms;
        String[] WPZD;
        String[] WPZF;
        String[] WQGD;
        String[] WQGF;
        String[] WLZ;
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        private FormHOZMain formHOZMain;
        public FormHOZMain FormHOZMainObject { get => formHOZMain; set => formHOZMain = value; }
        //模板路径
        private string readConfigPath;
        public string ReadConfigPath { get => readConfigPath; set => readConfigPath = value; }
        //模板文件默认路径
        private string m_TemplateFilePath;
        #endregion

        #region 构造方法
        public UControl_Init(FormHOZMain formHOZ)
        {
            InitializeComponent();
            FormHOZMainObject = formHOZ;
        }
        #endregion

        private void UControl_Init_Load(object sender, EventArgs e)
        {

        }

        #region 关闭窗体
        private void btnClose_Click(object sender, EventArgs e)
        {
            Form fParent = this.ParentForm;
            fParent.Close();
        }
        #endregion

        #region 加载切孔文件，生成切孔列表
        private void pbCutHoleFile_Click(object sender, EventArgs e)
        {
            if (FormHOZMainObject.m_MeasureFile == null)
            {
                MessageBox.Show("请新建一个测量文件");
            }
            else
            {
                if (!FormHOZMainObject.m_MeasureFile.GetCutHolesFromFile(""))
                {
                    MessageBox.Show("导入切孔失败");
                }
                else
                {
                    List<CutHole> ListCutHole = FormHOZMainObject.m_MeasureFile.ListCutHole;
                    //文件路径
                    string CutHoleFilePath = FormHOZMainObject.m_MeasureFile.CutHoleFilePath;
                    FormHOZMainObject.CreateCutHoleList(ListCutHole);
                    //显示导入的切孔数量
                    lblCutHoleCount.Text = string.Format("成功导入{0}个切孔", ListCutHole.Count);
                    tbCutHoleFilePath.Text = CutHoleFilePath;
                }
            }
        }
        #endregion

        #region 根据一个切孔文件,自动计算其他切孔信息
        /// <summary>
        /// 根据一个切孔,自动计算其他切孔信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pbCutHoleAuto_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 加载PT模板文件
        private void pbTemplateFile_Click(object sender, EventArgs e)
        {
            //判断保存的路径是否存在
            if (!Directory.Exists(m_TemplateFilePath))
            {
                //创建路径
                Directory.CreateDirectory(m_TemplateFilePath);
            }
            string FilePathName;
            string fileNameWithoutExtension;
            //新建一个文件对话框
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            //设置默认打开路径(绝对路径)
            pOpenFileDialog.InitialDirectory =  m_TemplateFilePath;
            //设置对话框标题
            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.txtWPTF.Text = FilePathName;
            }
        }
        #endregion

        #region 加载FIB模板文件
        private void pbFIBTemplateFile_Click(object sender, EventArgs e)
        {
            //判断保存的路径是否存在
            if (!Directory.Exists(m_TemplateFilePath))
            {
                //创建路径
                Directory.CreateDirectory(m_TemplateFilePath);
            }
            string FilePathName;
            string fileNameWithoutExtension;
            //新建一个文件对话框
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            //设置默认打开路径(绝对路径)
            pOpenFileDialog.InitialDirectory = m_TemplateFilePath;
            //设置对话框标题
            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.txtWFIBF.Text = FilePathName;
            }
        }
        #endregion

        #region 创建与读取样品参数、配置文件
        private void btnCreateConfig_Click(object sender, EventArgs e)
        {
            SaveTemplateFile();
        }
        private void SaveTemplateFile()
        {
            MeasureParam cfm = new MeasureParam();
            cfm.Is_Photograph = chkWIsP.Checked;
            cfm.PT = chkWPT.Checked;
            cfm.PTTemp = txtWPTF.Text;
            cfm.FIBTemp = txtWFIBF.Text;
            cfm.Stretch_Magnification = Convert.ToDouble(cbbWLZ.Text);
            cfm.Location_Magnification = Convert.ToDouble(cbbWQGF.Text);
            cfm.Location_Voltage = Convert.ToDouble(cbbWQGD.Text);
            cfm.Photograph_Magnification = Convert.ToDouble(cbbWPZF.Text);
            cfm.Photograph_Voltage = Convert.ToDouble(cbbWPZD.Text);
            if (cbbWXZ.SelectedIndex == 0)
            {
                cfm.Correction_Angle = 36.0;
            }
            else
            {
                cfm.Correction_Angle = 54.0;
            }

            cfm.SampleName = cbbWYP.Text;
            cfm.Firm = cbbWCS.Text;
            ConfigFile cf = new ConfigFile(cfm);
            if (!m_TemplateFilePath.Equals(""))
            {
                if (!Directory.Exists(m_TemplateFilePath))
                {
                    //创建路径
                    Directory.CreateDirectory(m_TemplateFilePath);
                }
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            //设置默认打开路径(绝对路径)
            saveFileDialog.InitialDirectory = m_TemplateFilePath;
            saveFileDialog.Filter = "样品参数文件|*.cfg";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                cf.Save(saveFileDialog.FileName);
            }
            else
            {
                return;
            }
            //编辑Config文件
            EditConfig();
        }
        /// <summary>
        /// 编辑confing 文件信息
        /// </summary>
        public bool EditConfig()
        {
            try
            {
                //设置数据源信息
                //样品类型
                List<String> _sT = sT.ToList();
                if (_sT.IndexOf(cbbWYP.Text) < 0)
                {
                    _sT.Add(cbbWYP.Text);
                    string wsT = string.Join(",", _sT.ToArray());
                    config.AppSettings.Settings["Sample_Type"].Value = wsT;
                }
                //厂商
                List<String> _firms = firms.ToList();
                if (_firms.IndexOf(cbbWCS.Text) < 0)
                {
                    _firms.Add(cbbWCS.Text);
                    string wFirms = string.Join(",", _firms.ToArray());
                    config.AppSettings.Settings["Firm"].Value = wFirms;
                }
                //拍照电压
                List<String> _WPZD = WPZD.ToList();
                if (_WPZD.IndexOf(cbbWPZD.Text) < 0)
                {
                    _WPZD.Add(cbbWPZD.Text);
                    string wWPZD = string.Join(",", _WPZD.ToArray());
                    config.AppSettings.Settings["WPZD"].Value = wWPZD;
                }
                //拍照放大位数
                List<String> _WPZF = WPZF.ToList();
                if (_WPZF.IndexOf(cbbWPZF.Text) < 0)
                {
                    _WPZF.Add(cbbWPZF.Text);
                    string wWPZF = string.Join(",", _WPZF.ToArray());
                    config.AppSettings.Settings["WPZF"].Value = wWPZF;
                }
                //定位切割电压
                List<String> _WQGD = WQGD.ToList();
                if (_WQGD.IndexOf(cbbWQGD.Text) < 0)
                {
                    _WQGD.Add(cbbWQGD.Text);
                    string wWQGD = string.Join(",", _WQGD.ToArray());
                    config.AppSettings.Settings["WQGD"].Value = wWQGD;
                }
                //定位切割放大位数
                List<String> _WQGF = WQGF.ToList();
                if (_WQGF.IndexOf(cbbWQGF.Text) < 0)
                {
                    _WQGF.Add(cbbWQGF.Text);
                    string wWQGF = string.Join(",", _WQGF.ToArray());
                    config.AppSettings.Settings["WQGF"].Value = wWQGF;
                }
                //拉直操作放大位数
                List<String> _WLZ = WLZ.ToList();
                if (_WLZ.IndexOf(cbbWLZ.Text) < 0)
                {
                    _WLZ.Add(cbbWLZ.Text);
                    string wWLZ = string.Join(",", _WLZ.ToArray());
                    config.AppSettings.Settings["WLZ"].Value = wWLZ;
                }

                MeasureParam cfm = new MeasureParam();
                cfm.Is_Photograph = chkWIsP.Checked;
                cfm.PT = chkWPT.Checked;
                cfm.PTTemp = txtWPTF.Text;
                cfm.FIBTemp = txtWFIBF.Text;
                cfm.Stretch_Magnification = Convert.ToDouble(cbbWLZ.Text);
                cfm.Location_Magnification = Convert.ToDouble(cbbWQGF.Text);
                cfm.Location_Voltage = Convert.ToDouble(cbbWQGD.Text);
                cfm.Photograph_Magnification = Convert.ToDouble(cbbWPZF.Text);
                cfm.Photograph_Voltage = Convert.ToDouble(cbbWPZD.Text);
                if (cbbWXZ.SelectedIndex == 0)
                {
                    cfm.Correction_Angle = 36.0;
                }
                else
                {
                    cfm.Correction_Angle = 54.0;
                }
                

                cfm.SampleName = cbbWYP.Text;
                cfm.Firm = cbbWCS.Text;
                //设置配置文件默认值
                config.AppSettings.Settings["Is_Photograph"].Value = cfm.Is_Photograph.ToString();
                config.AppSettings.Settings["PT_Depostion"].Value = cfm.PT.ToString();
                config.AppSettings.Settings["PT_ELYFile"].Value = cfm.PTTemp;
                config.AppSettings.Settings["FIB_ELYFile"].Value = cfm.FIBTemp;
                config.AppSettings.Settings["Stretch_Magnification"].Value = cfm.Stretch_Magnification.ToString();
                config.AppSettings.Settings["Location_Magnification"].Value = cfm.Location_Magnification.ToString();
                config.AppSettings.Settings["Location_Voltage"].Value = cfm.Location_Voltage.ToString();
                config.AppSettings.Settings["Photograph_Magnification"].Value = cfm.Photograph_Magnification.ToString();
                config.AppSettings.Settings["Photograph_Voltage"].Value = cfm.Photograph_Voltage.ToString();
                config.AppSettings.Settings["Correction_Angle"].Value = cfm.Correction_Angle.ToString();
                config.AppSettings.Settings["SampleName"].Value = cfm.SampleName;
                config.AppSettings.Settings["Firms"].Value = cfm.Firm;

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
                return true;
            }
            catch (Exception ex)
            {
                LogManager.LogError(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 删除config文件节点中内容信息
        /// </summary>
        public bool DelConfigNodeContentInfo(string delControlName, string selName)
        {
            try
            {
                switch (delControlName)
                {
                    case "WYP":
                        //样品类型
                        List<String> _sT = sT.ToList();
                        _sT.Remove(selName);
                        string wsT = string.Join(",", _sT.ToArray());
                        config.AppSettings.Settings["Sample_Type"].Value = wsT;
                        break;
                    case "WCS":
                        //厂商
                        List<String> _firms = firms.ToList();
                        _firms.Remove(selName);
                        string wFirms = string.Join(",", _firms.ToArray());
                        config.AppSettings.Settings["Firm"].Value = wFirms;
                        break;
                    case "WPZD":
                        //拍照电压
                        List<String> _WPZD = WPZD.ToList();
                        _WPZD.Remove(selName);
                        string wWPZD = string.Join(",", _WPZD.ToArray());
                        config.AppSettings.Settings["WPZD"].Value = wWPZD;
                        break;
                    case "WPZF":
                        //拍照放大位数
                        List<String> _WPZF = WPZF.ToList();
                        _WPZF.Remove(selName);
                        string wWPZF = string.Join(",", _WPZF.ToArray());
                        config.AppSettings.Settings["WPZF"].Value = wWPZF;
                        break;
                    case "WQGD"://定位切割电压
                        List<String> _WQGD = WQGD.ToList();
                        _WQGD.Remove(selName);
                        string wWQGD = string.Join(",", _WQGD.ToArray());
                        config.AppSettings.Settings["WQGD"].Value = wWQGD;
                        break;
                    case "WQGF": //定位切割放大位数
                        List<String> _WQGF = WQGF.ToList();
                        _WQGF.Remove(selName);
                        string wWQGF = string.Join(",", _WQGF.ToArray());
                        config.AppSettings.Settings["WQGF"].Value = wWQGF;
                        break;
                    case "WLZ":
                        //拉直操作放大位数
                        List<String> _WLZ = WLZ.ToList();
                        _WLZ.Remove(selName);
                        string wWLZ = string.Join(",", _WLZ.ToArray());
                        config.AppSettings.Settings["WLZ"].Value = wWLZ;
                        break;
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
                return true;
            }
            catch (Exception ex)
            {
                LogManager.LogError(ex.Message);
                return true;
            }
        }

        /// <summary>
        /// 绑定下拉菜单
        /// </summary>
        /// <param name="cb"></param>
        /// <param name="strGroup"></param>
        private void BindComboxData(ComboBox cb, string[] strGroup)
        {
            for (int i = 0; i < strGroup.Length; i++)
            {
                if (!strGroup[i].Equals(""))
                {
                    cb.Items.Add(strGroup[i]);
                }
            }
        }

        /// <summary>
        /// 读取Config文件信息
        /// </summary>
        public void ReloadConfig()
        {
            cbbWYP.Items.Clear();
            cbbWCS.Items.Clear();
            cbbWPZD.Items.Clear();
            cbbWPZF.Items.Clear();
            cbbWQGD.Items.Clear();
            cbbWQGF.Items.Clear();
            cbbWLZ.Items.Clear();

            m_TemplateFilePath = config.AppSettings.Settings["TemplateFilePath"].Value.ToString();
            string sample_Type = config.AppSettings.Settings["Sample_Type"].Value.ToString();
            string firm = config.AppSettings.Settings["Firm"].Value.ToString();
            string WPZDTemp = config.AppSettings.Settings["WPZD"].Value.ToString();
            string WPZFTemp = config.AppSettings.Settings["WPZF"].Value.ToString();
            string WQGDTemp = config.AppSettings.Settings["WQGD"].Value.ToString();
            string WQGFTemp = config.AppSettings.Settings["WQGF"].Value.ToString();
            string WLZTemp = config.AppSettings.Settings["WLZ"].Value.ToString();
            //样品类型
            sT = sample_Type.Split(',');
            BindComboxData(cbbWYP, sT);
            //厂商
            firms = firm.Split(',');
            BindComboxData(cbbWCS, firms);
            //拍照电压
            WPZD = WPZDTemp.Split(',');
            BindComboxData(cbbWPZD, WPZD);
            //拍照放大位数
            WPZF = WPZFTemp.Split(',');
            BindComboxData(cbbWPZF, WPZF);
            //定位切割电压
            WQGD = WQGDTemp.Split(',');
            BindComboxData(cbbWQGD, WQGD);
            //定位切割放大位数
            WQGF = WQGFTemp.Split(',');
            BindComboxData(cbbWQGF, WQGF);
            //拉直操作放大位数
            WLZ = WLZTemp.Split(',');
            BindComboxData(cbbWLZ, WLZ);
            
            //设置配置文件默认值
            chkWIsP.Checked=Convert.ToBoolean(config.AppSettings.Settings["Is_Photograph"].Value);
            chkWPT.Checked = Convert.ToBoolean(config.AppSettings.Settings["PT_Depostion"].Value);
            txtWPTF.Text = config.AppSettings.Settings["PT_ELYFile"].Value;
            txtWFIBF.Text = config.AppSettings.Settings["FIB_ELYFile"].Value;
            cbbWLZ.Text = config.AppSettings.Settings["Stretch_Magnification"].Value;
            cbbWQGF.Text = config.AppSettings.Settings["Location_Magnification"].Value;
            cbbWQGD.Text = config.AppSettings.Settings["Location_Voltage"].Value;
            cbbWPZF.Text = config.AppSettings.Settings["Photograph_Magnification"].Value;
            cbbWPZD.Text = config.AppSettings.Settings["Photograph_Voltage"].Value;
            string Correction_Angle = config.AppSettings.Settings["Correction_Angle"].Value;
            if (Correction_Angle == "36")
            {
                cbbWXZ.SelectedIndex = 0;
            }
            else
            {
                cbbWXZ.SelectedIndex = 1;
            }
            cbbWYP.Text = config.AppSettings.Settings["SampleName"].Value;
            cbbWCS.Text = config.AppSettings.Settings["Firms"].Value;
        }

        /// <summary>
        /// 根据所选路径，读取模板文件
        /// </summary>
        public void ReadConfigInfo()
        {
            if (!ReadConfigPath.Equals(""))
            {
                ReloadConfig();
                ConfigFile cfm = new ConfigFile(new MeasureParam());
                cfm.Read(ReadConfigPath);
                chkWIsP.Checked = cfm.m_Config.Is_Photograph;
                chkWPT.Checked = cfm.m_Config.PT;
                txtWPTF.Text = cfm.m_Config.PTTemp;
                txtWFIBF.Text = cfm.m_Config.FIBTemp;
                cbbWLZ.Text = cfm.m_Config.Stretch_Magnification.ToString();
                cbbWQGF.Text = cfm.m_Config.Location_Magnification.ToString();
                cbbWQGD.Text = cfm.m_Config.Location_Voltage.ToString();
                cbbWPZF.Text = cfm.m_Config.Photograph_Magnification.ToString();
                cbbWPZD.Text = cfm.m_Config.Photograph_Voltage.ToString();
                string Correction_Angle = cfm.m_Config.Correction_Angle.ToString();
                if (Correction_Angle == "36")
                {
                    cbbWXZ.SelectedIndex = 0;
                }
                else
                {
                    cbbWXZ.SelectedIndex = 1;
                }
                cbbWYP.Text = cfm.m_Config.SampleName;
                cbbWCS.Text = cfm.m_Config.Firm;
            }
        }

        /// <summary>
        /// 修改配置文件默认值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveDefalutPara_Click(object sender, EventArgs e)
        {
            if (EditConfig())
            {
                MessageBox.Show("保存成功!", "提示");
            }
        }
        #endregion

        #region 删除下拉菜单选择项

        private void DelComboBoxItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否删除所选项信息？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                PictureBox pbDel = (PictureBox)sender;
                string ctrlName = pbDel.Name.Substring(5, pbDel.Name.Length - 5);
                if (DelComboBoxItem(ctrlName))
                {
                    //重新加载
                    ReloadConfig(); 
                }
            }
        }

        /// <summary>
        /// 删除下拉菜单选择项
        /// </summary>
        public bool DelComboBoxItem(string controlName)
        {
            string delName = controlName;
            foreach (Control item in this.Controls)
            {
                if (item is ComboBox)
                {
                    if (item.Name.Contains(delName))
                    {
                        ComboBox cb = (ComboBox)item;
                        return DelConfigNodeContentInfo(delName, cb.Text);
                    }
                }
            }
            return false;
        }
        #endregion

        #region 根据是否仅拍照，进行逻辑判断
        private void chkWIsP_CheckedChanged(object sender, EventArgs e)
        {
            if (chkWIsP.Checked)
            {
                chkWPT.Checked = false;
                chkWPT.Visible = false;
            }
            else
            {
                chkWPT.Visible = true;
            }
        }
        #endregion
        
    }
}
