using Models;
using Newtonsoft.Json;
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 AssistClient
{
    public partial class FrmProductStep : Form
    {
        Service.ProductService service = new Service.ProductService();
        Models.Product model = new Models.Product();
        private int? assistStepId;// stepId, reviseStepId;
        /// <summary>
        /// 产品配方 <StepId,List<Models.ProductProcess>>
        /// </summary>
        Dictionary<int, List<Models.ProductProcess>> dicProductProcess = new Dictionary<int, List<Models.ProductProcess>>();
   
        public FrmProductStep(Models.Product m)
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            //显示行号与列宽度自动调整
            dataGridView1.RowHeadersVisible = true;
            dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            dataGridView1.RowPostPaint += (sender, e) =>
            {
                Utils.Util.showRowNum_onDataGrid_RowPostPaint(this.dataGridView1, sender, e);
            };

            model = m;
            initDataView();
        }
        private void initDataView()
        {
            //显示的数据 
            this.cobStepList.DisplayMember = "Name";
            this.cobStepList.ValueMember = "Id";

            var list = service.GetStepList(1);
            foreach (var item in list)
                dicProductProcess.Add(item.Id, new List<Models.ProductProcess>());

            if (model.AssistStepId != null)
            {
                this.assistStepId = (int)model.AssistStepId;
                dicProductProcess[(int)model.AssistStepId] = cv2ProductProcess(model.ProductAssistProcessList);
            }
            this.cobStepList.DataSource = list;

            if (model.StepId != null) 
                this.cobStepList.SelectedValue = (int)model.StepId;  
        }
 
        private List<ProductProcess> cv2ProductProcess(List<ProductAssistProcess> list)
        {
            List<ProductProcess> result=new List<ProductProcess>();
            foreach (var item in list)
                result.Add(item);

            return result;
        }
        private List<ProductAssistProcess> cv2ProductAssistProcess(List<ProductProcess> list)
        {
            string json;
            List<ProductAssistProcess> result = new List<ProductAssistProcess>();
            foreach (var item in list)
            {
                json=JsonConvert.SerializeObject(item);
                result.Add(JsonConvert.DeserializeObject<ProductAssistProcess>(json));
            }

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

        }
        private void cobStepList_SelectedIndexChanged(object sender, EventArgs e)
        {
            var list = this.cobStepList.DataSource as List<Models.Step>;
            int liIndex=this.cobStepList.SelectedIndex;
            if (liIndex < 0)
                return;
            dataGridView1.DataSource = new BindingSource(list[liIndex].ProcessList, null);
            tsslCount.Text = $"共{list[liIndex].ProcessList.Count}条工序";
              
            this.assistStepId = (int)this.cobStepList.SelectedValue;
        }
        private void tsbtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (assistStepId == null)
                    throw new Exception("请设置产品流程！");
                model.AssistStepId = assistStepId; 
                model.ProductAssistProcessList = cv2ProductAssistProcess(dicProductProcess[(int)assistStepId]);
                //model.ModifyUserCode = Config.loginUser.Code;
                //model.ModifyTime = DateTime.Now;
                bool result  = service.UpdateNav(model);
                if (!result)
                    throw new Exception("保存失败！");

                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void tsbtnCls_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.CurrentRow == null)
                    throw new Exception("请选择要清除私有产品配方的工序！");
                if(this.dataGridView1.CurrentRow.Cells["colPrivateProcessParams"].Value.ToString() == "")
                    throw new Exception("此工序未配置私有配方，无需清除！");

                //
                int liNewStepId = (int)this.cobStepList.SelectedValue;
                string processCode= this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
                var m = dicProductProcess[liNewStepId].Find(x => x.ProcessCode == processCode);
                if (m != null)
                {
                    dicProductProcess[liNewStepId].Remove(m);
                    this.dataGridView1.CurrentRow.Cells["colProdctPrivate"].Value = "";
                    this.dataGridView1.CurrentRow.Cells["colPrivateProcessParams"].Value = "";
                    MessageBox.Show("清除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.cobStepList.SelectedValue == null)
                return;
            int liNewStepId = (int)this.cobStepList.SelectedValue;
            string processCode;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                processCode = dataGridView1.Rows[i].Cells[0].Value.ToString();
                //dataGridView1.Rows[i].Cells[1].Value = Config.dicDevType[processCode];

                var m= dicProductProcess[liNewStepId].Find(x=>x.ProcessCode==processCode);
                if (m != null)
                {
                    dataGridView1.Rows[i].Cells["colProdctPrivate"].Value = "是";
                    dataGridView1.Rows[i].Cells["colPrivateProcessParams"].Value = m.ProcessParams;
                }
                else
                {
                    dataGridView1.Rows[i].Cells["colProdctPrivate"].Value = "";
                    dataGridView1.Rows[i].Cells["colPrivateProcessParams"].Value = "";
                }
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int liNewStepId = (int)this.cobStepList.SelectedValue;
            int Index = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引 
            if (Index < this.dataGridView1.Rows.Count && this.dataGridView1.CurrentCell.Value.ToString() == "设置")
            { 
                string processCode = this.dataGridView1.Rows[Index].Cells["colProcessCode"].Value.ToString();
                string processParams = "";
                if (this.dataGridView1.Rows[Index].Cells["colPrivateProcessParams"].Value != null && this.dataGridView1.Rows[Index].Cells["colPrivateProcessParams"].Value.ToString()!="")
                    processParams = this.dataGridView1.Rows[Index].Cells["colPrivateProcessParams"].Value.ToString();
                else if (this.dataGridView1.Rows[Index].Cells["colStepProcessParams"].Value != null && this.dataGridView1.Rows[Index].Cells["colStepProcessParams"].Value.ToString()!="")
                    processParams = this.dataGridView1.Rows[Index].Cells["colStepProcessParams"].Value.ToString();
                FrmSetParams frm = new FrmSetParams(processCode, processParams);
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    this.dataGridView1.Rows[Index].Cells["colProdctPrivate"].Value = "是";
                    this.dataGridView1.Rows[Index].Cells["colPrivateProcessParams"].Value = frm.ParamsData;
                    var m = dicProductProcess[liNewStepId].Find(x => x.ProcessCode == processCode);
                    if (m == null)
                        dicProductProcess[liNewStepId].Add(new Models.ProductProcess()
                        {
                            Pid = model.Id,
                            ProcessCode = processCode,
                            ProcessParams = frm.ParamsData,
                            ModifyUserCode=Config.loginUser.Code, 
                            CreateUserCode = Config.loginUser.Code,
                        });
                    else
                    {
                        m.ProcessParams = frm.ParamsData;
                        m.ModifyUserCode = Config.loginUser.Code; 
                    }
                }
            }
        }

        private void FrmProductStep_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show($"确认修改已保存，是否退出？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                e.Cancel = true;
                return;
            }
        }

       
    }
}
