using ICSharpCode.Core;
using Mesnac.Action.ChemicalWeighing.Entity;
using Mesnac.Action.ChemicalWeighing.Entity.material;
using Mesnac.Action.ChemicalWeighing.Station;
using Mesnac.Action.ChemicalWeighing.Technical.PmtRecipe;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mesnac.Action.ChemicalWeighing.Technical.XlRecipe
{
    public partial class FrmRecipe : Form
    {
        #region 字段定义

        private ActionType _actionType = ActionType.Add;    //操作类型,0-为添加,1-为修改
        private string _recipeName = null;
        private string _recipeVerson = null;
        private int _mixerNum = 0;
        private int _groutBags = 0;
        private string _remark = null;
        private Entity.xl_recipe pmt_Recipe = null;
        private List<xl_material> pmt_Materials = new List<xl_material>();    //所有物料集合
        private decimal _totalWeight = 0M;
        private decimal _totalError = 0M;
        private decimal _totalError2 = 0M;
        private string _recipeCode = string.Empty;
        private string _curRecipeID = null;
        private List<xl_weigh> pmt_Weighs = null;  //待写入数据库的配方物料信息List
        private string creator = Mesnac.Basic.UserInfo.Instance.UserName;//创建人
        private string creatDateTime = Mesnac.Basic.UserInfo.Instance.UserGUID;//创建时间
        #endregion

        #region 属性定义 

        public string RecipeName { get; set; }
        public  List<xl_station_sub> stationsub { get; set; }//设置
        public int MixerNum { get; set; }
        public int GroutBags { get; set; }
        public string Remark { get; set; }
        public xl_recipe xl_Recipe { get; set; }  //确定后要插入到数据库中,供Action使用
        public List<xl_material> Pmt_Materials { get; set; }
        public decimal TotalWeight { get; set; }
        public decimal TotalError { get; set; }
        public string CurRecipeID { get; set; }

        #endregion

        #region 构造方法

        public FrmRecipe()
        {
            InitializeComponent();
          
        }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="actionType">操作类型,0-为添加,1-为修改</param>
        public FrmRecipe(ActionType actionType)
        {
            InitializeComponent();
            this._actionType = actionType;
            pmt_Recipe = new xl_recipe
            {
                ID = Guid.NewGuid().ToString("N")
            };
            pmt_Weighs = new List<xl_weigh>();
        }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="actionType">操作类型,0-为添加,1-为修改</param>
        public FrmRecipe(ActionType actionType,string selectRecipeID, string recipeCodeStr, string recipeNameStr,string recipeVersion, int mixerNumStr, string groutBagsStr, string remarkStr,decimal totalError)
        {
            InitializeComponent();
            this._actionType = actionType;
            this._recipeCode=recipeCodeStr;
            _recipeName = recipeNameStr;
            _recipeVerson =recipeVersion;
            _mixerNum = mixerNumStr;
            if (string.IsNullOrEmpty(groutBagsStr))
            {
                _groutBags = 0;
            }
            else
            {
                _groutBags = Convert.ToInt32(groutBagsStr);
            }
            _remark = remarkStr;
            _totalError2 = totalError;
            pmt_Recipe = RecipeHelper.GetRecipeByName(selectRecipeID);
            pmt_Weighs = Product.XlPlan.PlanHelper.Getxl_weighList(pmt_Recipe.ID);
        }

        #endregion

        #region 方法定义

        /// <summary>
        /// 物料/工位名称集合获取
        /// </summary>
        public void InitCombox()
        {
            pmt_Materials = Product.XlPlan.PlanHelper.GetAllMaterial();
        }

        /// <summary>
        /// 初始化界面文本
        /// </summary>
        public void InitUI()
        {
            if (this._actionType == ActionType.Add)
            {
                this.Text = "添加新配方";
                txtRecipeName.Enabled = true;
                txtTotalError.Enabled = false;
            }
            else if (this._actionType == ActionType.Modify)
            {
                this.Text = "修改配方";
                textRecipeCode.Text = _recipeCode;
                txtRecipeName.Text = _recipeName;
                cmbRecipeVersion.Text = _recipeVerson;
                cmbRecipeVersion.Enabled = false;
                txtRecipeName.Enabled = false;
                txtTotalError.Text = _totalError2.ToString();
                txtTotalError.Enabled = false;
                

                txtRemark.Text = _remark;
                if (pmt_Recipe.Recipe_Verify == 1)
                {
                    checkBox1.Checked = true;
                }
                else
                {
                    checkBox1.Checked = false;
                }
            }
            this.btnOk.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_btnOK"));
            this.btnCancel.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_btnCancel"));
        }

        /// <summary>
        /// 初始化配方信息
        /// </summary>
        public void InitData()
        {
            if (this._actionType == ActionType.Add)
            {
                this.DGVMaterialSet.Rows.Add();
            }
            if (this._actionType == ActionType.Modify)
            {
                //先添加好空行
                if (pmt_Weighs != null && pmt_Weighs.Count > 0)
                {
                    for (int i = 0; i < pmt_Weighs.Count; i++)
                    {
                        this.DGVMaterialSet.Rows.Add();
                        //再将数据填入
                        for (int j = 0; j < this.DGVMaterialSet.ColumnCount; j++)
                        {
                            if (j == 0)
                            {
                                string tempMaterialName = GetMaterialName(pmt_Weighs[i].Material_ID);
                                if (!string.IsNullOrEmpty(tempMaterialName))
                                {
                                    this.DGVMaterialSet.Rows[i].Cells[j].Value = tempMaterialName;
                                }
                            }
                            else if (j == 1)
                            {
                                this.DGVMaterialSet.Rows[i].Cells[j].Value = pmt_Weighs[i].Set_Weight;
                            }
                            else if (j == 2)
                            {
                                this.DGVMaterialSet.Rows[i].Cells[j].Value = pmt_Weighs[i].Set_Error;
                            }
                        }
                    }
                }
            }
        }

        #region 填充物料信息List
        /// <summary>
        /// 填充物料信息List
        /// </summary>
        public void GetPmtWeightList()
        {
            pmt_Weighs.Clear();
            for (int i = 0; i < DGVMaterialSet.Rows.Count; i++)
            {
                xl_weigh pmt_Weigh = new xl_weigh();
                //pmt_Weigh.ID = Guid.NewGuid().ToString("N");
                pmt_Weigh.Recipe_ID = pmt_Recipe.ID;
                pmt_Weigh.Weight_Id = i + 1;
                for (int j = 0; j < DGVMaterialSet.ColumnCount; j++)
                {
                    if (j == 0)
                    {
                        //根据物料名称获取物料ID
                        string materialNameStr = DGVMaterialSet.Rows[i].Cells[j].Value.ToString();
                        if (pmt_Materials.Exists(x => x.Material_name == materialNameStr))
                        {
                            pmt_Weigh.Material_ID = GetMaterialID(materialNameStr);
                        }
                    }
                    else if (j == 1)
                    {
                        pmt_Weigh.Set_Weight = Convert.ToDecimal(DGVMaterialSet.Rows[i].Cells[j].Value.ToString());
                    }
                    else if (j == 2)
                    {
                        pmt_Weigh.Set_Error = Convert.ToDecimal(DGVMaterialSet.Rows[i].Cells[j].Value.ToString());
                    }
                }
                pmt_Weighs.Add(pmt_Weigh);
            }
        } 
        #endregion

        #region 根据物料名称查找物料ID
        /// <summary>
        /// 根据物料名称查找物料ID
        /// </summary>
        public string GetMaterialID(string materialName)
        {
            xl_material findPmt_Material = pmt_Materials.FindLast(x => x.Material_name == materialName);
            return findPmt_Material.ID;
        } 
        #endregion

        #region 根据物料ID查找物料名称
        /// <summary>
        /// 根据物料ID查找物料名称
        /// </summary>
        public string GetMaterialName(string materialID)
        {
            xl_material findPmt_Material = pmt_Materials.FindLast(x => x.ID == materialID);
            if (findPmt_Material!=null)
            {
                return findPmt_Material.Material_name;
            }
            return null;
        } 
        #endregion

        #region 计算TotalWeight和TotalError
        /// <summary>
        /// 计算TotalWeight和TotalError
        /// </summary>
        public void GetTotalWeightErrorValue()
        {
            for (int i = 0; i < DGVMaterialSet.Rows.Count; i++)
            {
                for (int j = 1; j < DGVMaterialSet.ColumnCount; j++)
                {
                    if (j == 1)
                    {
                        double tempd = Convert.ToDouble(DGVMaterialSet.Rows[i].Cells[j].Value.ToString());
                        _totalWeight = _totalWeight + (decimal)tempd;
                    }
                    if (j == 2)
                    {
                        double tempe = Convert.ToDouble(DGVMaterialSet.Rows[i].Cells[j].Value.ToString());
                        _totalError = _totalError + (decimal)tempe;

                    }
                }
            }
        }
        #endregion

        #region 向数据库中插入新配方数据
        /// <summary>
        /// 向数据库中插入新配方数据
        /// </summary>
        public void NewRecipeAdd()
        {
            pmt_Recipe.Recipe_Code = textRecipeCode.Text;
            pmt_Recipe.Recipe_Name = txtRecipeName.Text;
            pmt_Recipe.Equip_Code = ConfigurationManager.AppSettings["EquipCode"];
            pmt_Recipe.Version = this.cmbRecipeVersion.Text;
            if (_groutBags == 0)
            {
                pmt_Recipe.GroupBags = null;
            }
            else
            {
                pmt_Recipe.GroupBags = _groutBags;
            }
            pmt_Recipe.Remark = txtRemark.Text;
            pmt_Recipe.End_datetime = DateTime.Now.ToString();
            if (checkBox1.Checked)
            {
                pmt_Recipe.Recipe_Verify = 1;
            }
            else
            {
                pmt_Recipe.Recipe_Verify = 0;
            }
            pmt_Recipe.Total_Weight = _totalWeight;
            if (chcIsEnable.Checked)
            {
                pmt_Recipe.Total_Error =Convert.ToDecimal(this.txtTotalError.Text);
            }
            else
            {
                pmt_Recipe.Total_Error = _totalError;
            }
                

            _curRecipeID = RecipeHelper.InsertRecipe(pmt_Recipe);
        }

        /// <summary>
        /// 配方物料信息插入数据库
        /// </summary>
        public void NewWeighAdd()
        {
            if (pmt_Weighs != null && pmt_Weighs.Count > 0)
            {
                foreach (xl_weigh tempPmt_Weigh in pmt_Weighs)
                {
                    RecipeHelper.InsertWeigh(tempPmt_Weigh);
                }
            }
        }
        #endregion

        #region 配方物料信息删除
        /// <summary>
        /// 配方物料信息删除
        /// </summary>
        public void WeighDelByRecipeID(string recipeID)
        {
            RecipeHelper.DelWeighByRecipeID(recipeID);
        }
        #endregion

        #region 物料名称重复检查
        /// <summary>
        /// 物料名称重复检查
        /// </summary>
        /// <returns></returns>
        private bool DGVMaterialRepeatCheck()
        {
            bool checkResult = false;

            if (DGVMaterialSet.Rows.Count == 1)
            {
                checkResult = false;
            }
            else
            {
                for (int i = 0; i < DGVMaterialSet.Rows.Count; i++)
                {
                    if (DGVMaterialSet.Rows[i].Cells[0].Value == null)
                    {
                        return true;
                    }

                    string material1Name = DGVMaterialSet.Rows[i].Cells[0].Value.ToString();
                    for (int j = i + 1; j < DGVMaterialSet.Rows.Count; j++)
                    {
                        if (DGVMaterialSet.Rows[j].Cells[0].Value == null)
                        {
                            return true;
                        }
                        if (DGVMaterialSet.Rows[j].Cells[0].Value.ToString() == material1Name)
                        {
                            checkResult = true;
                            break;
                        }
                    }
                    if (checkResult)
                    {
                        break;
                    }
                }
            }

            return checkResult;
        }

        #endregion

        #region 物料名称重复检查
        /// <summary>
        /// 物料名称重复检查
        /// </summary>
        /// <returns></returns>
        private bool RecipeCheck(string Version,string Name)
        {
            bool checkResult = false;

            if (true)
            {

            }
           

            return checkResult;
        }

        #endregion

        #endregion

        #region 事件处理

        private void FrmPlan_Load(object sender, EventArgs e)
        {
            this.InitCombox();
            this.InitUI();
            this.InitData();
        }

        private void FrmPlan_Activated(object sender, EventArgs e)
        {
            if (this._actionType == ActionType.Modify)
            {
                this.txtRecipeName.Focus();
            }
            else
            {
                this.txtRecipeName.Focus();
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            #region 信息验证

            if (String.IsNullOrEmpty(this.txtRecipeName.Text))
            {
                MessageBox.Show("请输入新配方的名称!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (String.IsNullOrEmpty(this.cmbRecipeVersion.Text))
            {
                MessageBox.Show("请选择新配方的版本!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
           
            if (DGVMaterialSet == null)
            {
                MessageBox.Show("请设置配方的物料信息!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (DGVMaterialRepeatCheck())
            {
                MessageBox.Show("物料列表中存在重复物料或者空物料,请修改.", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (DGVMaterialRepeatCheck())
            {
                MessageBox.Show("物料列表中存在重复物料或者空物料,请修改.", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (DGVMaterialSet != null && DGVMaterialSet.Rows.Count > 0)
            {
                bool errorFlag = false;
                for (int i = 0; i < DGVMaterialSet.Rows.Count; i++)
                {
                    for (int j = 0; j < DGVMaterialSet.ColumnCount; j++)
                    {
                        if (DGVMaterialSet.Rows[i].Cells[j].Value == null)
                        {
                            errorFlag = true;
                            break;
                        }
                    }
                    if (errorFlag)
                    {
                        break;
                    }
                }
                if (errorFlag)
                {
                    MessageBox.Show("请将物料信息填写完整!或删除无用物料!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (_actionType == ActionType.Add && RecipeHelper.IsExistsName(this.txtRecipeName.Text, this.cmbRecipeVersion.Text))
            {
                MessageBox.Show("新配方的名称重复!请使用其他名称", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            #endregion

            #region 计算TotalWeight和TotalError

            GetTotalWeightErrorValue();

            #endregion

            #region 填充物料信息List

            GetPmtWeightList();

            #endregion

            #region 配方及物料信息写入数据库

            if (_actionType == ActionType.Add)
            {
                if (RecipeHelper.IsExists(this.txtRecipeName.Text, this.cmbRecipeVersion.Text))
                {
                    MessageBox.Show("新配方的版本已存在,请修改.", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                this.NewRecipeAdd();    //新配方数据插入数据库
                this.NewWeighAdd();     //配方对应的物料信息插入数据库
            }
            else if (_actionType == ActionType.Modify)
            {
                this.NewRecipeAdd();                        //更新配方数据到数据库
                this.WeighDelByRecipeID(pmt_Recipe.ID);     //清空配方对应的物料信息
                this.NewWeighAdd();                         //配方对应的物料信息重新插入数据库
            }

            #endregion

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void DGVMaterialSet_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            this.DGVMaterialSet.Refresh();
            int newRowNum = this.DGVMaterialSet.RowCount;
            if (pmt_Materials != null && pmt_Materials.Count > 0)
            {
                //(this.DGVMaterialSet.Rows[newRowNum - 1].Cells[0] as DataGridViewComboEditBoxCell).DataSource = pmt_Materials;

                foreach (xl_material pmt_Material in pmt_Materials)
                {
                    var combox = this.DGVMaterialSet.Rows[newRowNum - 1].Cells[0];
                    var editCombox = combox as DataGridViewComboBoxCell;
                    editCombox.Items.Add(pmt_Material.Material_name);
                }
            }
            
            this.DGVMaterialSet.Rows[newRowNum - 1].HeaderCell.Value = "+";
            this.DGVMaterialSet.CurrentCell = this.DGVMaterialSet[1, newRowNum - 1];
        }

        private void DGVMaterialSet_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            this.DGVMaterialSet.Rows.Add();
        }

        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            this.DGVMaterialSet.Rows.Add();
        }

        private void toolStripMenuItemDel_Click(object sender, EventArgs e)
        {
            if (this.DGVMaterialSet.CurrentCell != null)
            {
                this.DGVMaterialSet.Rows.RemoveAt(this.DGVMaterialSet.CurrentRow.Index);
            }
        }



        #endregion

        /// <summary>
        /// 手动设置总误差
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chcIsEnable_CheckedChanged(object sender, EventArgs e)
        {
            if (chcIsEnable.Checked)
            {
                txtTotalError.Enabled = true;
            }
            else
            {
                txtTotalError.Enabled = false;
            }
        }
    }
    /// <summary>
    /// 自定义可编辑下拉框单元
    /// </summary>
    public class DataGridViewComboEditBoxCell : DataGridViewComboBoxCell
    {
        public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);

            ComboBox comboBox = (ComboBox)base.DataGridView.EditingControl;
            if (comboBox != null)
            {
                comboBox.DropDownStyle = ComboBoxStyle.DropDown;
                comboBox.AutoCompleteMode = AutoCompleteMode.Suggest;
                comboBox.Validating += new CancelEventHandler(comboBox_Validating);
            }

        }

        protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
        {
            if (value != null && value.ToString().Trim() != string.Empty)
            {
                if (Items.IndexOf(value) == -1)// 如果下拉框中不存在填入的值,则添加到下拉框中
                {
                    //Items.Add(value);
                    //// 添加到该列所有单元所绑定的下拉列表中
                    //DataGridViewComboBoxColumn col = (DataGridViewComboBoxColumn)OwningColumn;
                    //col.Items.Add(value);
                    return null;
                }
            }

            return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context);
        }

        private void comboBox_Validating(object sender, CancelEventArgs e)
        {
            DataGridViewComboBoxEditingControl cbo = (DataGridViewComboBoxEditingControl)sender;
            if (cbo.Text.Trim() == string.Empty)
                return;

            DataGridView grid = cbo.EditingControlDataGridView;
            object value = cbo.Text;

            if (cbo.Items.IndexOf(value) == -1)
            {
                DataGridViewComboBoxColumn cboCol = (DataGridViewComboBoxColumn)grid.Columns[grid.CurrentCell.ColumnIndex];
                grid.CurrentCell.Value = value;
            }
        }

    }

    public class DataGridViewComboEditBoxColumn : DataGridViewComboBoxColumn
    {
        public DataGridViewComboEditBoxColumn()
        {
            DataGridViewComboEditBoxCell obj = new DataGridViewComboEditBoxCell();
            this.CellTemplate = obj;
        }
    }
}