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

namespace AssistClient
{
    public partial class FrmStepInfo : Form
    {
        Service.StepService service = new Service.StepService();
        Models.Step model=new Models.Step();
        public FrmStepInfo(Models.Step m=null)
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            dataGridView2.AutoGenerateColumns = false;
            //显示行号与列宽度自动调整
            dataGridView2.RowHeadersVisible = true;
            dataGridView2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            dataGridView2.RowPostPaint += (sender, e) =>
            {
                Utils.Util.showRowNum_onDataGrid_RowPostPaint(this.dataGridView2, sender, e);
            };
             
            if (m == null)
                model.ProcessList = new List<Models.StepProcess>();
            else
                model = m;
            model.Tag = 1;//*
        }
        private void initDataView()
        { 
            dataGridView1.Columns.Add("colCode", "code");
            dataGridView1.Columns.Add("colName", "工序");
            dataGridView1.Columns[0].Visible = false;
            dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            foreach (var item in Config.dicDevType) 
                dataGridView1.Rows.Add(item.Key, item.Value); 

            //
            this.txtCode.Text = model.Code;
            this.txtName.Text = model.Name;
            this.numStartTimeIndex.Value = model.StartTimeIndex;
            if (model.ProcessList!=null)
                dataGridView2.DataSource = new BindingSource(model.ProcessList, null); 
        } 
        private class Process
        {
            public Process(string code, string name)
            {
                Code = code;
                Name = name;
            }
            public string Code { get; set; }
            public string Name { get; set; }
        }
        private void FrmStepInfo_Load(object sender, EventArgs e)
        {
            initDataView();
        }
        #region private
        private void reOrderProcess()
        {
            for (int i = 0; i < model.ProcessList.Count; i++)
                model.ProcessList[i].Order = i;
        }
        private void refreshDataGridView()
        {
            dataGridView2.DataSource = null;
            dataGridView2.DataSource = new BindingSource(model.ProcessList, null);
        }
        #endregion
        private bool saveExit=false;
        private void tsbtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string szCode = this.txtCode.Text.Trim();
                string szName = this.txtName.Text.Trim();
                if (szCode == "" || szName == "")
                    throw new Exception("请填写编号和名称！");
                if (model.ProcessList == null || model.ProcessList.Count == 0)
                    throw new Exception("请添加流程工序！");
                foreach(var item in model.ProcessList)
                {
                    if (string.IsNullOrWhiteSpace(item.ProcessParams))
                        throw new Exception($"{Config.dicDevType[item.ProcessCode]} 配方未设置！");
                }

                model.Code = szCode;
                model.Name = szName;
                model.StartTimeIndex = (int)numStartTimeIndex.Value;
                model.ModifyUserCode = Config.loginUser.Code; 
                bool result;
                if (model.Id == 0)
                {
                    model.CreateUserCode=Config.loginUser.Code; 
                    result = service.InsertNav(model);
                }
                else
                    result = service.UpdateNav(model); 
                if (!result)
                    throw new Exception("保存失败！");

                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                saveExit=true;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.SelectedRows.Count != 1)
                    throw new Exception("请选择要插入的工序！");

                string processCode = this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); 
                model.ProcessList.Add(new Models.StepProcess()
                {
                    ProcessCode = processCode,
                    ProcessName= Config.dicDevType[processCode],
                    ModifyUserCode = Config.loginUser.Code,
                    CreateUserCode = Config.loginUser.Code
                });
                reOrderProcess();
                this.refreshDataGridView();
                this.dataGridView2.Rows[this.dataGridView2.Rows.Count-1].Selected = true;
                dataGridView2.CurrentCell = dataGridView2.Rows[this.dataGridView2.Rows.Count - 1].Cells[1];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnInsert_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.SelectedRows.Count != 1)
                    throw new Exception("请选择要插入的工序！");

                string processCode= this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                int liInsertIndex = this.dataGridView2.Rows.Count;
                if (this.dataGridView2.SelectedRows.Count > 0)
                    liInsertIndex = this.dataGridView2.SelectedRows[0].Index;
                model.ProcessList.Insert(liInsertIndex, new Models.StepProcess()
                {
                    ProcessCode = processCode,
                    ProcessName = Config.dicDevType[processCode],
                    Order = liInsertIndex,
                    ModifyUserCode=Config.loginUser.Code,
                    CreateUserCode=Config.loginUser.Code
                });
                reOrderProcess();
                this.refreshDataGridView();
                this.dataGridView2.Rows[liInsertIndex].Selected = true;
                dataGridView2.CurrentCell = dataGridView2.Rows[liInsertIndex].Cells[1];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView2.SelectedRows.Count != 1)
                    throw new Exception("请选择要删除的工序！");

                int liRowIndex = this.dataGridView2.SelectedRows[0].Index;
                model.ProcessList.RemoveAt(liRowIndex);
                if(liRowIndex>= dataGridView2.Rows.Count-1)
                    liRowIndex= dataGridView2.Rows.Count-1;
                dataGridView2.CurrentCell = dataGridView2.Rows[liRowIndex].Cells[1];
                //reOrderProcess();
                this.refreshDataGridView();

                if (dataGridView2.Rows.Count < 1)
                    return;
                if (liRowIndex >= dataGridView2.Rows.Count)
                    liRowIndex = dataGridView2.Rows.Count - 1;
                dataGridView2.CurrentCell = dataGridView2.Rows[liRowIndex].Cells[1];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView2.SelectedRows.Count != 1)
                    throw new Exception("请选择要调整顺序的工序！");
                int liSelIndex = this.dataGridView2.SelectedRows[0].Index;
                if (liSelIndex == 0)
                    return;

                model.ProcessList.Insert(liSelIndex - 1, model.ProcessList[liSelIndex]);
                model.ProcessList.RemoveAt(liSelIndex + 1);
                reOrderProcess();
                this.refreshDataGridView();
                this.dataGridView2.Rows[liSelIndex-1].Selected = true;
                dataGridView2.CurrentCell = dataGridView2.Rows[liSelIndex - 1].Cells[1];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView2.SelectedRows.Count != 1)
                    throw new Exception("请选择要调整顺序的工序！");
                int liSelIndex = this.dataGridView2.SelectedRows[0].Index;
                if (liSelIndex == this.dataGridView2.Rows.Count-1)
                    return;

                model.ProcessList.Insert(liSelIndex +2, model.ProcessList[liSelIndex]);
                model.ProcessList.RemoveAt(liSelIndex);
                reOrderProcess();
                this.refreshDataGridView();
                this.dataGridView2.Rows[liSelIndex+1].Selected = true;
                dataGridView2.CurrentCell = dataGridView2.Rows[liSelIndex + 1].Cells[1];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        } 

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

        private void dataGridView2_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        { 
            for(int i=0;i<  dataGridView2.Rows.Count;i++)
            {
                dataGridView2.Rows[i].Cells["colTypeName"].Value = Config.dicDevType[dataGridView2.Rows[i].Cells[0].Value.ToString()];
            }
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int Index = this.dataGridView2.CurrentRow.Index;//获取当前选中行的索引 
            if (Index < this.dataGridView2.Rows.Count && this.dataGridView2.CurrentCell.Value.ToString() == "设置")
            {
                string processCode = this.dataGridView2.Rows[Index].Cells["colProcessCode"].Value.ToString();
                string processParams="";
                if(this.dataGridView2.Rows[Index].Cells["colProcessParams"].Value!=null)
                    processParams=this.dataGridView2.Rows[Index].Cells["colProcessParams"].Value.ToString();
                FrmSetParams frm=new FrmSetParams(processCode, processParams); 
                if (frm.ShowDialog() == DialogResult.OK)
                    this.dataGridView2.Rows[Index].Cells["colProcessParams"].Value = frm.ParamsData;
            }
        }

        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
         
        //单元格编译完成
        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var value = dataGridView2.Rows[e.RowIndex].Cells["colProcessName"].Value;
            if (value==null || value.ToString().Trim() == "")
            {
                dataGridView2.Rows[e.RowIndex].Cells["colProcessName"].Value = dataGridView2.Rows[e.RowIndex].Cells["colTypeName"].Value;
            }
        }

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