using Models;
using Newtonsoft.Json.Linq;
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 FrmStepList : Form
    {
        Service.StepService service=new Service.StepService();
        public FrmStepList()
        {
            InitializeComponent(); 
            #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)
        {
            var list = service.GetListNav(0);
            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 FrmStepList_Load(object sender, EventArgs e)
        {
            initDataView();
        } 

        private void tsbtnAdd_Click(object sender, EventArgs e)
        {
            FrmStepInfo frm = new FrmStepInfo();
            frm.ShowDialog();
            initDataView();
        }

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

                var list = ((BindingSource)dataGridView1.DataSource).DataSource as List<Step>;
                int liIndex = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引   
                if (service.InUse(list[liIndex].Id))
                    throw new Exception("此流程已有产品在使用中,不可删除！");
                if (MessageBox.Show($"确认删除？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                { 
                    if (!service.DelNav(list[liIndex]))
                        throw new Exception("删除失败！");
                    MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    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 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<Step>;
            int liIndex = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引   

            Step newStep = new Step()
            {
                Code = list[liIndex].Code + "_clone",
                Name = $"{list[liIndex].Name} (克隆)",
                StartTimeIndex = list[liIndex].StartTimeIndex,
                ModifyUserCode = Config.loginUser.Code,
                CreateUserCode = Config.loginUser.Code,
                ProcessList = new List<StepProcess>()
            };
            foreach(var item in list[liIndex].ProcessList)
            {
                StepProcess sp;
                string spPrarms = "";
                if (item.ProcessCode == "Size")
                {
                    if (item.ProcessParams.IndexOf("MapPath") > 0)
                    {
                        JObject jo = JObject.Parse(item.ProcessParams);//解析成json
                        jo["MapPath"] = "";//修改需要的字段
                        jo["GetPointList"] = null;
                        spPrarms = Convert.ToString(jo);
                    }
                    else
                        spPrarms = item.ProcessParams;
                }
                else
                    spPrarms = item.ProcessParams;

                sp = new StepProcess()
                {
                    Order = item.Order,
                    ProcessCode = item.ProcessCode,
                    ProcessName = item.ProcessName,
                    ProcessParams = spPrarms,
                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                };
                
                newStep.ProcessList.Add(sp);
            }

            try
            {
                bool result = service.InsertNav(newStep);
                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);
            }
        }
        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            var list = ((BindingSource)dataGridView1.DataSource).DataSource as List<Step>;
            int liIndex = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引    
            FrmStepInfo frm = new FrmStepInfo(list[liIndex]);
            frm.ShowDialog(this);
            initDataView();
        }

       
    }
}
