using ProductionControl.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProductionControl
{
    public partial class FrmProductInfo2 : Form
    { 
        Service.ProductService service = new Service.ProductService();
        Models.Product model = new Models.Product();
        public FrmProductInfo2(Models.Product m=null)
        {
            InitializeComponent();
            this.dgvBatchList.AutoGenerateColumns = false;

            if (m!=null)
            {
                model = m;
                this.txtCode.Text = m.Code;
                this.txtName.Text = m.Name;
                this.txtSpec.Text = m.Spec;
                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);
                if(model.AttachmentList.Count > 0)
                {
                    this.btnOpenFile.Text = model.AttachmentList[0].Name;
                    this.btnOpenFile.Visible = true;
                }
            } 

        } 
        private void FrmProductInfo_Load(object sender, EventArgs e)
        { 
        }

        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 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 (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.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.numPTBaseValue.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;

                model.ModifyUserCode = Config.loginUser.Code;
                model.ModifyTime = DateTime.Now; 
                bool result;
                if (model.Id == 0)
                {
                    model.BatchId = szBatchId;
                    model.TargetCount = liTargetCount;
                    model.CompleteCount = 0; 
                    model.CreateUserCode = Config.loginUser.Code;
                    model.CreateTime = DateTime.Now;
                    result = service.InsertNav(model);
                }
                else
                {
                    if (model.BatchId != szBatchId && !string.IsNullOrEmpty(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
            {
                //.dwg /.dxf /.dws /.dwt
                string filePath = FileUtil.selectFile("dwg文件|*.dwg|dxf文件|*.dxf|dws文件|*.dws|dwt文件|*.dwt");
                if (string.IsNullOrEmpty(filePath))
                    return;
                
                string fileName=Path.GetFileName(filePath);
                string fileExtend=Path.GetExtension(filePath);
                long nameTimestamp=DateTime.Now.Ticks;

                //未删除原文件，保留记录
                string targFilePath = Application.StartupPath + "\\Attachment\\Product\\";
                if (!Directory.Exists(targFilePath)) 
                    Directory.CreateDirectory(targFilePath);
                targFilePath += nameTimestamp + fileExtend; 
                //File.Copy(res.file_path, defectFileName + ".bmp", true);
                bool result = API.CopyFile(filePath, targFilePath, false);//更快  //false-覆盖
                if (!result)
                    throw new Exception("移动文件失败！");

                //
                if (model.AttachmentList.Count > 0)
                {
                    model.AttachmentList[0].NameTimestamp= nameTimestamp;
                    model.AttachmentList[0].Name = fileName;
                    model.AttachmentList[0].ExtendName = fileExtend; 
                }
                else
                {
                    model.AttachmentList.Add(new Models.Attachment()
                    {
                        TBName = "product",
                        NameTimestamp = nameTimestamp,
                        Name = fileName,
                        ExtendName = fileExtend,
                    });
                }
                if (!service.UpdateNav(model))
                    throw new Exception("保存文件失败！");

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

        private void btnOpenFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (model.AttachmentList.Count < 1)
                MessageBox.Show("还未上传！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            string filePath = Application.StartupPath + "\\Attachment\\Product\\" + model.AttachmentList[0].Id + model.AttachmentList[0].ExtendName;
            Process.Start(filePath);
        }
    }
}
