using Models;
using SqlSugar;
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 ProductionControl
{
    public partial class FrmClassesSingle : Form
    {
        Service.ClassesService service = new Service.ClassesService();
        List<Classes> lstClasses=new List<Classes>();
        private int Tag;
        ValType valType;
        public FrmClassesSingle(int tag,string subject="类别设置", ValType _valType = ValType.字符串)
        {
            InitializeComponent();
            this.Tag = tag;
            this.Text = subject;
            valType = _valType;
            dataGridView2.AutoGenerateColumns = false; 
            //显示行号与列宽度自动调整
            dataGridView2.RowHeadersVisible = true;
            dataGridView2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            dataGridView2.RowPostPaint += (sender, e) =>
            {
                Utils.Util.showRowNum_onDataGrid_RowPostPaint(this.dataGridView2, sender, e);
            }; 
        }
        private void FrmClassesSingle_Load(object sender, EventArgs e)
        {
            initDataView();
        }

        private void FrmClassesSingle_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.button1.Focus();
            if (!dataGridView2.EndEdit())
            {
                e.Cancel = true;
                return;
            }
            //if (!saveExit && MessageBox.Show($"确认修改已保存，是否退出？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            //{
            //    e.Cancel = true;
            //    return;
            //}
        }
        private void initDataView()
        {
            //dataGridView2.Rows.Clear();
            var exp1 = Expressionable.Create<Classes>()
                .And(m=>m.Tag == Tag)
                //.AndIF(dateTimePicker2.Checked, it => it.CreateTime < dateTimePicker2.Value)
                .ToExpression();//注意 这一句 不能少

            lstClasses = service.GetList(exp1).OrderBy(m => m.Order).ToList();
            if(lstClasses.Count < 1)//wlq 大坑：这个因为如果绑定数据源【list】是不为null但长度是0的 ，一旦点击新增 后 点击行就会抛出 索引为-1的相关错误。这个微软不知道咋设计的
            {
                lstClasses.Insert(0,new Classes());
                dataGridView2.DataSource = lstClasses;
                dataGridView2.DataSource = null;
                lstClasses.RemoveAt(0); 
            }
            dataGridView2.DataSource = lstClasses;// new BindingSource(lstClasses, null);
            //for(int i=0;i<lstClasses.Count;i++)
            //{
            //    lstClasses[i].Order = i;
            //    dataGridView2.Rows.Add(lstClasses[i].Id, lstClasses[i].Order, lstClasses[i].Name, lstClasses[i].Name);
            //} 
        }   
        #region private
        private void reOrderProcess()
        {
            for (int i = 0; i < lstClasses.Count; i++)
                lstClasses[i].Order = i;
        }
        private void refreshDataGridView()
        {
            dataGridView2.DataSource = null;
            dataGridView2.DataSource = new BindingSource(lstClasses, null);
        }
        #endregion
        private bool saveExit=false;
        private void tsbtnSave_Click(object sender, EventArgs e)
        {
            try
            { 
                if (lstClasses.Where(m=>string.IsNullOrWhiteSpace(m.Name)).Count() > 0)
                    throw new Exception("请填写名称！");  
                 
                bool result; 
                var lstInsert= lstClasses.Where(m => m.Id == 0).ToList();
                if (lstInsert.Count > 0)
                {
                    result = service.InsertRange(lstInsert);
                    if (!result)
                        throw new Exception("保存失败！");
                }
                var lstUpdate = lstClasses.Where(m => m.Id > 0).ToList();
                if (lstUpdate.Count > 0)
                {
                    result = service.UpdateRange(lstUpdate);
                    if (!result)
                        throw new Exception("保存失败！");
                }
                

                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                saveExit=true;
                this.DialogResult = DialogResult.OK;
                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 dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int Index = this.dataGridView2.CurrentRow.Index;//获取当前选中行的索引 
            if (Index < this.dataGridView2.Rows.Count && this.dataGridView2.CurrentCell.Value.ToString() == "设置")
            {
            }
        }

        //单元格编译完成
        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                var id = (int)dataGridView2.Rows[e.RowIndex].Cells["colId"].Value;
                var order = (int)dataGridView2.Rows[e.RowIndex].Cells["colOrder"].Value;
                var preValue = dataGridView2.Rows[e.RowIndex].Cells["colPreName"].Value.ToString();
                if (dataGridView2.Rows[e.RowIndex].Cells["colName"].Value == null || dataGridView2.Rows[e.RowIndex].Cells["colName"].Value.ToString() == "")
                {
                    dataGridView2.Rows[e.RowIndex].Cells["colName"].Value = preValue;
                    return;
                }

                var value = dataGridView2.Rows[e.RowIndex].Cells["colName"].Value.ToString(); 
                var count=lstClasses.Where(m =>m.Id!=id && m.Name == value.ToString()).Count();
                if (count > 0)
                {
                    if (!string.IsNullOrWhiteSpace(preValue))
                        dataGridView2.Rows[e.RowIndex].Cells["colName"].Value = preValue;
                    else
                        dataGridView2.Rows[e.RowIndex].Cells["colName"].Value = "";
                    throw new Exception("已存在相同名称！");
                }

                //
                if (id==0)
                {
                    if (string.IsNullOrWhiteSpace(value))
                        return;

                    var m = lstClasses[lstClasses.Count - 1];
                    lstClasses[lstClasses.Count - 1] = service.InsertReturnEntity(lstClasses[lstClasses.Count - 1]);
                    //if (!result)
                    //    throw new Exception("保存失败！"); 
                }
                else
                {
                    if (value.Equals(preValue))//未修改
                        return;

                    bool result = service.InsertOrUpdate(lstClasses[e.RowIndex]);
                    if (!result)
                        throw new Exception("保存失败！"); 
                }
                dataGridView2.Rows[e.RowIndex].Cells["colPreName"].Value = dataGridView2.Rows[e.RowIndex].Cells["colName"].Value;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsbtnNew_Click(object sender, EventArgs e)
        {
            if(dataGridView2.EndEdit())
            {
                //int index=dataGridView2.Rows.Add();
                if(lstClasses.Count<1 || lstClasses.Where(m => m.Id == 0).Count() < 1)
                {
                    var model = new Classes()
                    {
                        Tag = this.Tag,
                        Name = "",
                        Order = lstClasses.Count ,
                        CreateUserCode = Config.loginUser.Code,
                        ModifyUserCode = Config.loginUser.Code,
                    };
                    lstClasses.Add(model);
                    dataGridView2.DataSource = null;
                    dataGridView2.DataSource = lstClasses;
                    dataGridView2.Rows[dataGridView2.Rows.Count - 1].Selected = true;
                    dataGridView2.CurrentCell = dataGridView2.Rows[dataGridView2.Rows.Count- 1].Cells["colName"];
                    this.dataGridView2.BeginEdit(true);
                }

               
            } 
        }
        private void tsbtnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (!dataGridView2.EndEdit()) return;
                if (dataGridView2.SelectedRows.Count < 1) 
                    return;

                int index = dataGridView2.SelectedRows[0].Index;
                if (lstClasses[index].Id >0)
                { 
                    if (!service.DeleteById(lstClasses[index].Id))
                        throw new Exception("删除失败,此项可能已被使用！"); 
                }
                this.initDataView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void dataGridView2_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //var list = ((BindingSource)dataGridView2.DataSource).DataSource as List<Order>;
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                dataGridView2.Rows[i].Cells["colPreName"].Value = dataGridView2.Rows[i].Cells["colName"].Value;
            }
        }

    
    }
}
