using Models;
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;

namespace ProductionControl
{
    public partial class FrmProductList : Form
    {
        Service.ProductService service = new Service.ProductService();
        public Models.Product Product { get; private set; }
        public FrmProductList(bool isProductRevise=false)
        {
            InitializeComponent(); 
            this.tsbtnAdd.Enabled=this.tsbtnDel.Enabled =this.tsbtnSetting.Enabled= !isProductRevise;
            this.tsbtnRevise.Visible=isProductRevise;
            if (isProductRevise)
            {
                this.Text = "产品基准厚度校正";
            }
            #region dataGridView设置
            dataGridView1.AutoGenerateColumns = false;//自动创建列
            dataGridView1.AllowUserToAddRows = dataGridView1.AllowUserToDeleteRows = false;//用户添加删除行
            dataGridView1.AllowUserToResizeRows = true;//用户调整行大小
                                                       //dataGridView1.AllowUserToResizeColumns = false;//用户调整列大小
                                                       //显示行号与列宽度自动调整
            dataGridView1.RowHeadersVisible = true;
            dataGridView1.RowHeadersWidth = 50;
            dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变
            dataGridView1.RowPostPaint += (sender, e) =>//序号列头
            {
                Utils.Util.showRowNum_onDataGrid_RowPostPaint(this.dataGridView1, sender, e);
            };
            dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            //for (int i = 0; i < dataGridView1.Columns.Count; i++)//禁止点击列头排序 
            //    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;

            //行列交叉处标题
            //if (dataGridView1.RowHeadersVisible) dataGridView1.TopLeftHeaderCell.Value = "SPH/CYL";
            #endregion
        }
        private void initDataView(int selIndex = -1)
        {
            Product = null;
            var list = service.GetListNav();
            tsslCount.Text = $"共 {list.Count} 条记录";
            int liIndex = 0;
            if (selIndex > 0) liIndex = selIndex;
            else if (this.dataGridView1.CurrentRow!=null) 
                liIndex=this.dataGridView1.CurrentRow.Index;
            dataGridView1.DataSource = new BindingSource(list, null);
            if (dataGridView1.Rows.Count > liIndex)
                dataGridView1.CurrentCell = dataGridView1[1, liIndex];
        } 
        private void FrmProductList_Load(object sender, EventArgs e)
        {
            initDataView();
        }
        private void tsbtnRefresh_Click(object sender, EventArgs e)
        {
            initDataView();
        }
        private void tsbtnAdd_Click(object sender, EventArgs e)
        {
            FrmProductInfo frm = new FrmProductInfo();
            frm.ShowDialog();
            initDataView();
        }

        private void tsbtnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.CurrentRow == null)
                    return;

                if (MessageBox.Show($"确认删除？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    var list = ((BindingSource)dataGridView1.DataSource).DataSource as List<Product>;
                    int liIndex = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引   
                    if (!service.DelNav(list[liIndex]))
                        throw new Exception("删除失败！");
                    MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //initDataView();
                    this.dataGridView1.Rows.RemoveAt(liIndex);
                    if(this.dataGridView1.Rows.Count == 0)
                        initDataView();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsbtnSetting_Click(object sender, EventArgs e)
        {
            if(this.dataGridView1.CurrentRow == null) return;

            var list = ((BindingSource)dataGridView1.DataSource).DataSource as List<Product>;
            int liIndex = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引   
            FrmProductStep frm = new FrmProductStep(list[liIndex]);
            frm.ShowDialog();
            initDataView();
        }
        private void tsbtnRevise_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.CurrentRow == null)
                    throw new Exception("请选择要校正的产品！");

                var list = ((BindingSource)dataGridView1.DataSource).DataSource as List<Product>;
                int liIndex = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引   
                if (list[liIndex].ReviseStepId==null || list[liIndex].ReviseStepId<1)
                    throw new Exception("此产品未设置校正流程！");

                if (MessageBox.Show($"确认执行校正产品流程？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Product=list[liIndex];
                    this.DialogResult = DialogResult.Yes;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!this.tsbtnAdd.Enabled) return;
            var list = ((BindingSource)dataGridView1.DataSource).DataSource as List<Product>;
            int liIndex = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引    
            FrmProductInfo frm = new FrmProductInfo(list[liIndex]);
            frm.ShowDialog(this);
            initDataView();
        }
          
        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            var list = ((BindingSource)dataGridView1.DataSource).DataSource as List<Product>;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (list[i].ClassesInfo != null) 
                    dataGridView1.Rows[i].Cells["colClasses"].Value = list[i].ClassesInfo.Name;
                if (list[i].StepInfo != null) 
                    dataGridView1.Rows[i].Cells["colStepName"].Value = list[i].StepInfo.Name;
                if (list[i].ReviseStepInfo != null)
                    dataGridView1.Rows[i].Cells["colReviseStepName"].Value = list[i].ReviseStepInfo.Name;
               
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void tsbtnClasses_Click(object sender, EventArgs e)
        {
            FrmClassesSingle frm = new FrmClassesSingle(0, "产品类型管理");
            if(frm.ShowDialog() == DialogResult.OK)
            {
                this.initDataView();    
            }
        }


        private void tsbtnDefectClasses_Click(object sender, EventArgs e)
        {

        }

        private void tsbtnClone_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请选择要克隆的产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var list = ((BindingSource)dataGridView1.DataSource).DataSource as List<Product>;
            int liIndex = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引   

            Product newProduct = new Product()
            {
                Code = list[liIndex].Code + "_clone",
                Name = $"{list[liIndex].Name} (克隆)",
                Spec = list[liIndex].Spec,
                ClassesId = list[liIndex].ClassesId,
                ClassesInfo = list[liIndex].ClassesInfo,
                HoleCount = list[liIndex].HoleCount,
                DefectModelFile = list[liIndex].DefectModelFile,
                AttachmentList = new List<Attachment>(),
                BatchId = list[liIndex].BatchId,
                TargetCount = list[liIndex].TargetCount,
                CompleteCount = list[liIndex].CompleteCount,
                BatchHistoryList = new List<BatchHistory>(),
                QualifiedCriterionList = new List<QualifiedCriterion>(),
                Note = list[liIndex].Note,
                TensionBaseValue = list[liIndex].TensionBaseValue,
                TensionUpFloatValue = list[liIndex].TensionUpFloatValue,
                TensionDownFloatValue = list[liIndex].TensionDownFloatValue,
                HeightBaseValue = list[liIndex].HeightBaseValue,
                HeightUpFloatValue = list[liIndex].HeightUpFloatValue,
                HeightDownFloatValue = list[liIndex].HeightDownFloatValue,
                LineWidthBaseValue = list[liIndex].LineWidthBaseValue,
                LineWidthUpFloatValue = list[liIndex].LineWidthUpFloatValue,
                LineWidthDownFloatValue = list[liIndex].LineWidthDownFloatValue,
                PTBaseValue = list[liIndex].PTBaseValue,
                PTUpFloatValue = list[liIndex].PTUpFloatValue,
                PTDownFloatValue = list[liIndex].PTDownFloatValue,
                HeightBaseDec = list[liIndex].HeightBaseDec,

                StepId = list[liIndex].StepId,
                StepInfo = list[liIndex].StepInfo,
                ProductProcessList = new List<ProductProcess>(),
                ReviseStepId = list[liIndex].ReviseStepId,
                ReviseStepInfo = list[liIndex].ReviseStepInfo,
                ProductReviseProcessList = new List<ProductReviseProcess>(),
                AssistStepId = list[liIndex].AssistStepId,
                AssistStepInfo = list[liIndex].AssistStepInfo,
                ProductAssistProcessList = new List<ProductAssistProcess>(),

                MarkType = list[liIndex].MarkType,
                MarkSize = list[liIndex].MarkSize,
                MapPath = "",
                GetPointList = "",
                //OrderList = new List<Order>(),

                ModifyUserCode = Config.loginUser.Code,
                CreateUserCode = Config.loginUser.Code
            };
            foreach (var item in list[liIndex].AttachmentList)
            {
                newProduct.AttachmentList.Add(new Attachment()
                {
                    TBName = item.TBName,
                    Type = item.Type,
                    Pid = item.Pid,
                    Name = item.Name,
                    NameTimestamp = item.NameTimestamp,
                    ExtendName = item.ExtendName,
                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                });
            }
            foreach (var item in list[liIndex].BatchHistoryList)
            {
                newProduct.BatchHistoryList.Add(new BatchHistory()
                {
                    Pid = item.Pid,
                    BatchId = item.BatchId,
                    TargetCount = item.TargetCount,
                    CompleteCount = item.CompleteCount,

                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                });
            }
            foreach (var item in list[liIndex].QualifiedCriterionList)
            {
                newProduct.QualifiedCriterionList.Add(new QualifiedCriterion()
                {
                    Pid = item.Pid,
                    DefectCode = item.DefectCode,
                    Size = item.Size,
                    MaxDefectCount = item.MaxDefectCount,

                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                });
            }
            foreach (var item in list[liIndex].ProductProcessList)
            {
                newProduct.ProductProcessList.Add(new ProductProcess()
                {
                    Pid = item.Pid,
                    ProcessCode = item.ProcessCode,
                    ProcessParams = item.ProcessParams,

                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                });
            }
            foreach (var item in list[liIndex].ProductReviseProcessList)
            {
                newProduct.ProductReviseProcessList.Add(new ProductReviseProcess()
                {
                    Pid = item.Pid,
                    ProcessCode = item.ProcessCode,
                    ProcessParams = item.ProcessParams,

                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                });
            }
            foreach (var item in list[liIndex].ProductAssistProcessList)
            {
                newProduct.ProductAssistProcessList.Add(new ProductAssistProcess()
                {
                    Pid = item.Pid,
                    ProcessCode = item.ProcessCode,
                    ProcessParams = item.ProcessParams,

                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                });
            }
            /*
            foreach (var item in list[liIndex].OrderList)
            {
                newProduct.OrderList.Add(new Order()
                {
                    ProductId = item.ProductId,
                    ProductInfo = item.ProductInfo,
                    SN = item.SN,

                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                });
            }*/

            try
            {
                bool result = service.InsertNav(newProduct);
                if (result)
                {
                    MessageBox.Show("克隆成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    initDataView(dataGridView1.Rows.Count);
                }
                else
                    throw new Exception("克隆失败！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
