using OpenCvSharp;
using ProductionControl.UI;
using ProductionControl.UIExtend;
using ProductionControl.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
using System.Windows.Forms;

namespace ProductionControl
{
    public partial class FrmProductInfo : Form
    {
        Service.ClassesService svcClasses = new Service.ClassesService();
        Service.ProductService service = new Service.ProductService();
        Models.Product model = new Models.Product();

        string MapPath = "";
        public FrmProductInfo(Models.Product m=null)
        {
            InitializeComponent();
            this.dgvBatchList.AutoGenerateColumns = false;
            checkCustomerVer();
            //this.cbMarkType.SelectedIndex = -1;
            if (m!=null)
            {
                model = m;
                this.Text += $" (ID:{m.Id})";
                this.txtCode.Text = m.Code;
                this.txtName.Text = m.Name;
                this.txtSpec.Text = m.Spec;

                this.cmbHoleCount.Text = m.HoleCount.ToString();

                this.txtBatchId.Text = m.BatchId;
                this.numTargetCount.Value = m.TargetCount;
                this.toolTip1.SetToolTip(this.numTargetCount,"已完成:"+m.CompleteCount);  

                this.numTensionBaseValue.Value = (decimal)m.TensionBaseValue;
                this.numTensionUpFloatValue.Value = (decimal)m.TensionUpFloatValue;
                this.numTensionDownFloatValue.Value = (decimal)m.TensionDownFloatValue;
                this.numHeightBaseValue.Value = (decimal)m.HeightBaseValue;
                this.numHeightUpFloatValue.Value = (decimal)m.HeightUpFloatValue;
                this.numHeightDownFloatValue.Value = (decimal)m.HeightDownFloatValue;
                this.txtHeightBaseDec.Text = m.HeightBaseDec;
                this.numLineWidthBaseValue.Value = (decimal)m.LineWidthBaseValue;
                this.numLineWidthUpFloatValue.Value = (decimal)m.LineWidthUpFloatValue;
                this.numLineWidthDownFloatValue.Value = (decimal)m.LineWidthDownFloatValue;
                this.numPTBaseValue.Value = (decimal)m.PTBaseValue;
                this.numPTUpFloatValue.Value = (decimal)m.PTUpFloatValue;
                this.numPTDownFloatValue.Value = (decimal)m.PTDownFloatValue;
                //if (m.Type > 0)
                //{
                //    this.txtCode.Enabled = false;
                //    this.txtName.Width = this.txtCode.Width;
                //    this.txtSpec.Enabled = false;
                //}
                
                this.tsbtnAddFile.Enabled = true;
                this.tsbtnNewBatchId.Enabled = true;
                this.dgvBatchList.DataSource = new BindingSource(m.BatchHistoryList, null);
                //2023-11-2 mark
                this.cbMarkType.SelectedIndex = m.MarkType;
                this.numMarkSize.Value = (decimal)m.MarkSize;
                //2023-12-18 主栅
                this.cbMarkDisturb.Checked = (m.MarkDisturb == 1);
                this.cbMainGrid.Checked = (m.MainGrid == 1);

                this.cbHavePad.Checked = (m.HavePad == 1);

                Models.Attachment attachmentFile = model.AttachmentList.FirstOrDefault(x => x.Type == 0);
                if (attachmentFile!=null)
                {
                    this.btnOpenFile.Text = attachmentFile.Name;
                    this.btnOpenFile.Visible = true;
                    //为兼容老版本，发现图纸图片地址为空，检索图片地址
                    if (string.IsNullOrEmpty(model.MapPath))
                    {
                        string targFilePath = Application.StartupPath + $"\\Attachment\\product\\{model.Id}\\";
                        targFilePath += attachmentFile.Name;
                        model.MapPath = targFilePath.Substring(0, targFilePath.Length - 4) + ".bmp";
                    }
                }

            }

            initDataView();
        } 
        private void FrmProductInfo_Load(object sender, EventArgs e)
        {
            //this.cbMarkType.SelectedIndex = -1;
        }  
        private void checkCustomerVer()
        {
            if (Config.CustomerVer != "B")
            {
                tabControl1.TabPages.RemoveAt(3);
            }
        }
        private void initDataView()
        {
            //显示的数据 
            this.cmbClasses.DisplayMember = "Name";
            this.cmbClasses.ValueMember = "Id"; 
            var list = svcClasses.GetListNav(0); 
            this.cmbClasses.DataSource = list; 
            if (model.ClassesId>0)
                this.cmbClasses.SelectedValue = model.ClassesId;


            //缺陷项
            var lstDefect = Utils.EnumUtil.GetArrayList<DefectCodeEnum>();
            foreach(DictionaryEntry item in lstDefect)
            {
                DefectCountOfSizeControl userCon = new DefectCountOfSizeControl();
                userCon.Code = item.Value.ToString();
                userCon.Title = ((DefectNameEnum)(int)item.Key).ToString();
                if (model != null && model.QualifiedCriterionList!=null)
                {
                    var qalifiedItem = model.QualifiedCriterionList.FirstOrDefault(m => m.DefectCode == userCon.Code);
                    if(qalifiedItem != null)
                    {
                        userCon.Checked = true;
                        userCon.SizeValue = (decimal)qalifiedItem.Size;
                        userCon.MaxDefectCount = qalifiedItem.MaxDefectCount;
                    }
                }

                this.flpQualifiedPannel.Controls.Add(userCon);
            }

            //模型文件
            string strDefectModelFile = Application.StartupPath + @"\onnxFiles\";
            if(!Directory.Exists(strDefectModelFile))
                Directory.CreateDirectory(strDefectModelFile);
            string[] onnxFiles=Directory.GetFiles(strDefectModelFile,"*.onnx");
            string onlyName;
            foreach (string onnxFile in onnxFiles)
            {
                onlyName = Path.GetFileName(onnxFile);
                cmbDefectModelFile.Items.Add(onlyName);
                if (!string.IsNullOrWhiteSpace(model.DefectModelFile) && onlyName.ToLower()== model.DefectModelFile.ToLower()) 
                    this.cmbDefectModelFile.SelectedItem = model.DefectModelFile; 
            }          
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string szCode = this.txtCode.Text.Trim();
                string szName = this.txtName.Text.Trim();
                string szSpec = this.txtSpec.Text.Trim();
                string szHoleCount = this.cmbHoleCount.Text.Trim();
                string szBatchId = this.txtBatchId.Text.Trim();
                int liTargetCount = (int)this.numTargetCount.Value;
                string szHeightBaseDec=this.txtHeightBaseDec.Text.Trim().Trim(new char[] { ';', ',' });
                if (szCode == "" || szName == "")
                    throw new Exception("请填写料号和名称！");
                if(this.cmbClasses.SelectedIndex<0)
                    throw new Exception("请选择产品类型！");
                if (szHoleCount==""||! Util.IsNumber(szHoleCount))
                    throw new Exception("请正确填写产品目数！");
                if (this.cmbDefectModelFile.SelectedIndex < 0)
                    throw new Exception("请选择检测模型文件！");

                if (this.cbMarkType.SelectedIndex < 0)
                    throw new Exception("请选择Mark！");
                //if (szBatchId == "")// || liTargetCount < 1 
                //    throw new Exception("请填写批次号");// 和批次目标数量！");
                if (szHeightBaseDec != "")
                {
                    double num;
                    string[] szs= szHeightBaseDec.Split(new char[] { ';',','});
                    foreach(string s in szs)
                    {
                        if (!double.TryParse(s, out num))
                            throw new Exception(s+" 非数值！");
                    }
                }

                model.Code = szCode;
                model.Name = szName;
                model.Spec = szSpec;
                model.ClassesId = (int)this.cmbClasses.SelectedValue;
                model.HoleCount = Convert.ToInt32(szHoleCount);
                model.DefectModelFile = this.cmbDefectModelFile.Text.Trim();

                model.TensionBaseValue= (double)this.numTensionBaseValue.Value;
                model.TensionUpFloatValue = (double)this.numTensionUpFloatValue.Value;
                model.TensionDownFloatValue = (double)this.numTensionDownFloatValue.Value;
                model.HeightBaseValue = (double)this.numHeightBaseValue.Value;
                model.HeightUpFloatValue = (double)this.numHeightUpFloatValue.Value;
                model.HeightDownFloatValue = (double)this.numHeightDownFloatValue.Value;
                model.HeightBaseDec = szHeightBaseDec;
                model.LineWidthBaseValue = (double)this.numLineWidthBaseValue.Value;
                model.LineWidthUpFloatValue = (double)this.numLineWidthUpFloatValue.Value;
                model.LineWidthDownFloatValue = (double)this.numLineWidthDownFloatValue.Value;
                model.PTBaseValue = (double)this.numPTBaseValue.Value;
                model.PTUpFloatValue = (double)this.numPTUpFloatValue.Value;
                model.PTDownFloatValue = (double)this.numPTDownFloatValue.Value;
                if (model.QualifiedCriterionList == null)
                    model.QualifiedCriterionList = new List<Models.QualifiedCriterion>();
                else
                    model.QualifiedCriterionList.Clear();

                if (string.IsNullOrEmpty(model.MapPath))
                {
                    model.MapPath = "";
                    model.GetPointList = "";
                }

                foreach (DefectCountOfSizeControl defectControl in this.flpQualifiedPannel.Controls)
                {
                    if (defectControl.Checked)
                    {
                        model.QualifiedCriterionList.Add(
                            new Models.QualifiedCriterion()
                            {
                                DefectCode = defectControl.Code,
                                Size = (float)defectControl.SizeValue,
                                MaxDefectCount = (int)defectControl.MaxDefectCount,
                                ModifyUserCode = Config.loginUser.Code,
                                CreateUserCode = Config.loginUser.Code
                            });
                    }
                }
                model.ModifyUserCode = Config.loginUser.Code;

                //2023-11-2 mark
                model.MarkType = this.cbMarkType.SelectedIndex;
                model.MarkSize = (double)this.numMarkSize.Value;
                //2023-12-18 主栅
                model.MarkDisturb = this.cbMarkDisturb.Checked?1:0;
                model.MainGrid = this.cbMainGrid.Checked ? 1 : 0;
                model.HavePad = this.cbHavePad.Checked?1: 0;

                bool result;
                if (model.Id == 0)
                {
                    model.BatchId = szBatchId;
                    model.TargetCount = liTargetCount;
                    model.CompleteCount = 0; 
                    model.CreateUserCode = Config.loginUser.Code; 
                    result = service.InsertNav(model);
                }
                else
                {
                    if (model.BatchId != szBatchId && !string.IsNullOrWhiteSpace(model.BatchId))
                    {
                        if (model.CompleteCount<model.TargetCount 
                            && MessageBox.Show($"本批次完成数量未达到目标数量，确定更换批次号？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                            return;
                        if (model.BatchHistoryList.FirstOrDefault(m => m.BatchId == szBatchId) != null)
                            throw new Exception("当前批次号与历史中所用批次号重复，请重新填写！");

                        model.BatchHistoryList.Add(new Models.BatchHistory()
                        {
                            BatchId = model.BatchId,
                            TargetCount = model.TargetCount,
                            CompleteCount = model.CompleteCount,
                            CreateUserCode = Config.loginUser.Code,
                            ModifyUserCode = Config.loginUser.Code
                        });
                        model.CompleteCount = 0;
                    }
 
                    model.BatchId = szBatchId;
                    model.TargetCount = liTargetCount;
                    result = service.UpdateNav(model);
                }
                if (!result)
                    throw new Exception("保存失败！");

                this.tsbtnAddFile.Enabled = true;
                this.tsbtnNewBatchId.Enabled = true;
                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tsbtnNewBatchId_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 2;
            Application.DoEvents();
        }

        private void btnAddFile_Click(object sender, EventArgs e)
        { 
            try
            {
                if (this.cbMarkType.SelectedIndex < 0)
                    throw new Exception("请选择Mark！");
                //.dwg /.dxf /.dws /.dwt
                string filePath = FileUtil.selectFile("gbx,gbr文件|*.gb?");
                if (string.IsNullOrWhiteSpace(filePath))
                    return;

                string fileName=Path.GetFileName(filePath);
                string fileExtend=Path.GetExtension(filePath);
                string fileOnlyName = fileName.Substring(0, fileName.Length - fileExtend.Length);

                //
                string targFilePath = Application.StartupPath + $"\\Attachment\\product\\{model.Id}\\";
                if (!Directory.Exists(targFilePath))
                    Directory.CreateDirectory(targFilePath);
                else//删除原文件
                    FileUtil.delFilesInFolder(targFilePath);

                targFilePath +=  fileName; 
                //File.Copy(res.file_path, defectFileName + ".bmp", true);
                bool result = API.CopyFile(filePath, targFilePath, false);//更快  //false-覆盖
                if (!result)
                    throw new Exception("移动文件失败！");

                //后台线程转BMP与JPG
                string tempClass = this.cmbClasses.Text;
                int tempIndex = this.cbMarkType.SelectedIndex;
                double tempValue = (double)this.numMarkSize.Value;
                //2023-12-18
                int tMarkDistrub = this.cbMarkDisturb.Checked ? 1 : 0;
                int tMainGrid = this.cbMainGrid.Checked ? 1 : 0;
                //2024-1-24
                int tHavePad = this.cbHavePad.Checked ? 1 : 0;

                Task.Run(() =>
                {
                    Yolo5.Yolo_Class yolo = new Yolo5.Yolo_Class();
                    string bmpPath = targFilePath.Substring(0, targFilePath.Length - 4) + ".bmp";
                    //2023-11-3 mark
                    
                    //yolo.gerber2image(targFilePath, bmpPath);
                    double[] markParam = new double[7];
                    if(tempClass.Contains("乳剂"))
                        markParam[0] = 2;
                    else if (tempClass.Contains("PI"))
                        markParam[0] = 1;
                    else
                        markParam[0] = 0;
                    if (tempIndex == 0)
                    {
                        //默认情况 实心圆，0.5mm
                        markParam[1] = 2;
                        markParam[2] = 0.5;
                        markParam[3] = 1;
                        markParam[4] = 0;
                        markParam[5] = 0;
                        markParam[6] = 0;
                    }
                    else
                    {
                        markParam[1] = tempIndex - 1;
                        markParam[2] = tempValue;
                        markParam[3] = tempIndex == 1 ? 0 : 1;
                        markParam[4] = tMarkDistrub;
                        markParam[5] = tMainGrid;
                        markParam[6] = tHavePad;
                    }
                    yolo.gerber2image(targFilePath, bmpPath, markParam);

                    //换背景JPG
                    Mat mat = Cv2.ImRead(bmpPath);
                    Cv2.CvtColor(mat, mat, ColorConversionCodes.RGB2GRAY);//转灰度图
                    for (int i = 0; i < mat.Height; i++)
                    {
                        for (int j = 0; j < mat.Width; j++)
                        {
                            if (mat.At<byte>(i, j) == 255)//白色 
                                mat.Set<byte>(i, j, 0);
                            else
                                mat.Set<byte>(i, j, 255);
                        }
                    }
                    model.MapPath = bmpPath;
                    //灰转彩
                    //Cv2.CvtColor(mat, mat, ColorConversionCodes.GRAY2RGB);
                    //for (int i = 0; i < mat.Height; i++)
                    //{
                    //    for (int j = 0; j < mat.Width; j++)
                    //    {
                    //        if (mat.At<byte>(i, j) == 255)//白色 
                    //            mat.Set<byte>(i, j, 0); //黄色
                    //    }
                    //} 
                    bmpPath = targFilePath.Substring(0, targFilePath.Length - 4) + ".jpg";
                    //model.MapPath = bmpPath;
                    OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat).Save(bmpPath, ImageFormat.Jpeg);
                });//不能加.Start();
               
                Models.Attachment attachmentFile = model.AttachmentList.FirstOrDefault(m => m.Type == 0);
                if (attachmentFile!=null)
                {
                    attachmentFile.Type = 0;//图纸
                    attachmentFile.NameTimestamp= $"{model.Id}\\{fileOnlyName}";
                    attachmentFile.Name = fileName;
                    attachmentFile.ExtendName = fileExtend; 
                }
                else
                {
                    model.AttachmentList.Add(new Models.Attachment()
                    {
                        TBName = "product",
                        Type = 0,
                        NameTimestamp = $"{model.Id}\\{fileOnlyName}",
                        Name = fileName,
                        ExtendName = fileExtend,
                        CreateUserCode = Config.loginUser.Code,
                        ModifyUserCode = Config.loginUser.Code
                    });
                }
                if (!service.UpdateNav(model))
                    throw new Exception("保存文件失败！");

                model=service.GetModelNav(model.Code); 
                this.btnOpenFile.Text = fileName;
                this.btnOpenFile.Visible = true; 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }
         

        private void btnOpenFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Models.Attachment attachmentFile = model.AttachmentList.FirstOrDefault(m => m.Type == 0);
            if (attachmentFile == null )
                MessageBox.Show("还未上传！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            string filePath = Application.StartupPath + $"\\Attachment\\product\\{model.Id}\\" + attachmentFile.NameTimestamp + attachmentFile.ExtendName;
            if(File.Exists(filePath))
                Process.Start(filePath);
        }

        private void tbtnGetPos_Click(object sender, EventArgs e)
        {
            if ((model.MapPath == null)||(string.IsNullOrEmpty(model.MapPath)))
            {
                MessageBox.Show("还未上传图纸！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var list = model.GetPointList.Split(',');
            List<double> dList = new List<double>();
            if (list.Length < 28)
            {
                for (int i = 0; i < 28; i++)
                {
                    dList.Add(0);
                }
            }
            else
            { 
                for (int i = 0; i < list.Length; i++)
                {
                    dList.Add(double.Parse(list[i]));
                }
            }
            FrmGetPosByPic frm = new FrmGetPosByPic(model.MapPath, dList.ToArray());
            frm.ShowDialog();
            model.GetPointList = string.Join(",", frm.GetPoints()); ;
            model.MapPath = frm.GetMapPath();

            if (!service.UpdateNav(model))
                throw new Exception("保存文件失败！");

            model = service.GetModelNav(model.Code);
        }
    }
}
