using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using ICSharpCode.Core;
using Mesnac.Controls.Base;
using Mesnac.Action.Base;
using Mesnac.Codd.Session;
using Mesnac.Action.ChemicalWeighing.Entity;
using Mesnac.Action.ChemicalWeighing.Technical;

namespace Mesnac.Action.ChemicalWeighing.Technical.PmtRecipe
{
    public class RefreshAction : ChemicalWeighingAction,IAction
    {
        #region 事件定义

        /// <summary>
        /// 刷新计划事件
        /// </summary>
        public static event EventHandler OnRefreshRecipe;

        #endregion

        #region 字段定义

        private static bool IsFirstRun = true;  //是否首次执行
        private RuntimeParameter _runtime;
        private DbMCControl _clientGridControl = null;      //配方树控件
        private DbMCControl _materialControl = null;    //配方关联物料信息控件
        private DbMCControl _recipeGridControl = null; // 配方信息控件

        #endregion

        #region IAction接口实现

        public void Run(RuntimeParameter runtime)
        {
            base.RunIni(runtime);       //必须要调用的
            this._runtime = runtime;

            ICSharpCode.Core.LoggingService<RefreshAction>.Debug("配方管理—刷新配方业务...");

            #region 事件订阅

            if (true)
            {
                //通用调用刷新计划事件订阅

                Mesnac.Basic.InvokeHelper.OnRefreshRecipe -= Process_Event;
                Mesnac.Basic.InvokeHelper.OnRefreshRecipe += Process_Event;

                //添加计划后,要刷新计划
                InsertAction.OnInsertRecipe -= Insert_Event;
                InsertAction.OnInsertRecipe += Insert_Event;



                //删除计划后,要刷新本地计划
                DeleteAction.OnDeleteRecipe -= Insert_Event;
                DeleteAction.OnDeleteRecipe += Insert_Event;

                //修改次数数后,要刷新本地计划
                ModifyRecipeAction.OnModifyRecipe -= Insert_Event;
                ModifyRecipeAction.OnModifyRecipe += Insert_Event;

                SetCratParam.OnSetCratParam -= SetCartPrarm_Event;
                SetCratParam.OnSetCratParam += SetCartPrarm_Event;

                SaveRecipe.SaveAsRecipe -= Process_Event;
                SaveRecipe.SaveAsRecipe += Process_Event;

                IsFirstRun = false;
            }

            #endregion

            List<DbMCControl> recipeControlList = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "Base_RecipeInfo");

            DbMCControl clientGridControl = recipeControlList.Where(x => x.BaseControl is TreeView).FirstOrDefault();

            if (clientGridControl == null || !(clientGridControl.BaseControl is TreeView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少配方树网格控件...");
                return;
            }

            DbMCControl recipeGridControl = recipeControlList.Where(x => x.BaseControl is DataGridView).FirstOrDefault();

            if (recipeGridControl == null || !(recipeGridControl.BaseControl is DataGridView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少配方信息网格控件...");
                return;
            }

            DbMCControl materialGridControl = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "Base_RecipeMaterial").FirstOrDefault();         //获取配方管理控件

            if (materialGridControl == null || !(materialGridControl.BaseControl is DataGridView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少物料信息网格控件...");
                return;
            }

            this._clientGridControl = clientGridControl;
            this._materialControl = materialGridControl;
            this._recipeGridControl = recipeGridControl;

            this.DoWork();
        }

        #endregion

        #region 方法定义

        /// <summary>
        /// 刷新计划
        /// </summary>
        protected void DoWork()
        {
            #region 业务实现
            
            string equipCode = base.CurrEquipCode;      //当前机台

            //配方树初始化
            DataTable dataTable = RecipeHelper.GetBaseRecipeInfo("");

            TreeNode tn = new TreeNode();
            tn.Name = "全部";
            tn.Text = "全部";

            //将数据集加载到树形控件当中
            foreach (DataRow row in dataTable.Rows)
            {
                string strValue = row["recipe_Type"].ToString();
                if (tn.Nodes.Count > 0)
                {
                    if (!tn.Nodes.ContainsKey(strValue))
                    {
                        BindTreeData(tn, dataTable, strValue);
                    }
                }
                else
                {
                    BindTreeData(tn, dataTable, strValue);
                }
            }
            TreeView treeView = (this._clientGridControl.BaseControl as TreeView);
            treeView.Nodes.Clear();

            treeView.Nodes.Add(tn);
            treeView.ExpandAll();

            //配方信息初始化
            lock (String.Empty)
            {
                if (this._recipeGridControl != null && this._recipeGridControl.BaseControl != null)
                {
                    this._recipeGridControl.BaseControl.BindDataSource = null;
                    this._recipeGridControl.BaseControl.BindDataSource = dataTable;
                }
                else
                {
                    ICSharpCode.Core.LoggingService<RefreshAction>.Warn("刷新配方信息失败:配方信息控件为Null...");
                }
            }
            
            //配方关联物料信息初始化
            DataTable materialDataTable = RecipeHelper.GetRecipeMaterialInfo("");
            lock (String.Empty)
            {
                if (this._materialControl != null && this._materialControl.BaseControl != null)
                {
                    this._materialControl.BaseControl.BindDataSource = null;
                    this._materialControl.BaseControl.BindDataSource = materialDataTable;
                }
                else
                {
                    ICSharpCode.Core.LoggingService<RefreshAction>.Warn("刷新配方信息失败:物料信息控件为Null...");
                }
            }
            #endregion

            #region 触发事件, 刷新客户端计划

            if (OnRefreshRecipe != null)
            {
                OnRefreshRecipe(this._runtime.BaseControl.MCRoot, System.EventArgs.Empty);
            }

            #endregion
        }

        private void BindTreeData(TreeNode tn, DataTable dtData, string strValue)
        {
            TreeNode tn1 = new TreeNode();
            tn1.Name = strValue;
            tn1.Text = strValue;
            tn.Nodes.Add(tn1);

            DataRow[] rows = dtData.Select(string.Format("recipe_Type='{0}'", strValue));
            if (rows.Length > 0)
            {
                foreach (DataRow dr in rows)
                {
                    TreeNode tn2 = new TreeNode();
                    tn2.Name = dr["recipe_Id"].ToString();
                    tn2.Text = dr["recipe_Name"].ToString();
                    
                    tn1.Nodes.Add(tn2);
                }
            }
        }

        #endregion

        #region 事件处理方法

        private void Process_Event(object sender, EventArgs e)
        {
            if (sender is RuntimeParameter)
            {
                this.Run(sender as RuntimeParameter);
            }
            else
            {
                this.refresh(this._runtime);
            }
        }
        private void Insert_Event(object sender, EventArgs e)
        {
            this.DoWork();
        }
        #endregion

        private void SetCartPrarm_Event(object sender, EventArgs e)
        {
            this.refresh(this._runtime);

            ICSharpCode.Core.LoggingService<RefreshAction>.Debug("配方管理—刷新配方业务...");

            //获取所有控件
            List<DbMCControl> recipeControlList = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "Base_RecipeInfo");

            DbMCControl clientGridControl = recipeControlList.Where(x => x.BaseControl is TreeView).FirstOrDefault();

            if (clientGridControl == null || !(clientGridControl.BaseControl is TreeView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少配方树网格控件...");
                return;
            }

            DbMCControl recipeGridControl = recipeControlList.Where(x => x.BaseControl is DataGridView).FirstOrDefault();

            if (recipeGridControl == null || !(recipeGridControl.BaseControl is DataGridView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少配方信息网格控件...");
                return;
            }

            DbMCControl materialGridControl = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "Base_RecipeMaterial").FirstOrDefault();         //获取配方管理控件

            if (materialGridControl == null || !(materialGridControl.BaseControl is DataGridView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少物料信息网格控件...");
                return;
            }

            DbMCControl cartParamGridControl = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "Base_CratParam").FirstOrDefault();         //获取配方管理控件

            if (cartParamGridControl == null || !(cartParamGridControl.BaseControl is DataGridView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少物料参数信息网格控件...");
                return;
            }

            //根据选中的配方编号刷新物料信息、工艺参数
            TreeView clientGridView = clientGridControl.BaseControl as TreeView;
            DataGridView dataGridView = cartParamGridControl.BaseControl as DataGridView;

            string recipeCode = clientGridView.SelectedNode.Name as string;
            string materialCode = dataGridView.SelectedRows[0].Cells["material_Id"].Value as string;
            DataTable info = RecipeHelper.GetCratParamByRecipeAndMaterial(recipeCode, "");

            lock (String.Empty)
            {
                if (cartParamGridControl != null && cartParamGridControl.BaseControl != null)
                {
                    cartParamGridControl.BaseControl.BindDataSource = null;
                    cartParamGridControl.BaseControl.BindDataSource = info;
                }
                else
                {
                    ICSharpCode.Core.LoggingService<RefreshAction>.Warn("刷新配方信息失败:物料信息控件为Null...");
                }
            }
        }

        private void refresh(RuntimeParameter runtime)
        {
            ICSharpCode.Core.LoggingService<RefreshAction>.Debug("配方管理—刷新配方业务...");

            //获取所有控件
            List<DbMCControl> recipeControlList = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "Base_RecipeInfo");

            DbMCControl clientGridControl = recipeControlList.Where(x => x.BaseControl is TreeView).FirstOrDefault();

            if (clientGridControl == null || !(clientGridControl.BaseControl is TreeView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少配方树网格控件...");
                return;
            }

            DbMCControl recipeGridControl = recipeControlList.Where(x => x.BaseControl is DataGridView).FirstOrDefault();

            if (recipeGridControl == null || !(recipeGridControl.BaseControl is DataGridView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少配方信息网格控件...");
                return;
            }

            DbMCControl materialGridControl = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "Base_RecipeMaterial").FirstOrDefault();         //获取配方管理控件

            if (materialGridControl == null || !(materialGridControl.BaseControl is DataGridView))
            {
                ICSharpCode.Core.LoggingService<RefreshAction>.Error("{配方管理—刷新配方}缺少物料信息网格控件...");
                return;
            }
            //根据选中的配方编号刷新物料信息、工艺参数
            try
            {
                TreeView clientGridView = clientGridControl.BaseControl as TreeView;
                string selectRecipeName = clientGridView.SelectedNode.Name as string;
                DataTable info = RecipeHelper.GetRecipeMaterialInfo(selectRecipeName);

                lock (String.Empty)
                {
                    if (this._materialControl != null && this._materialControl.BaseControl != null)
                    {
                        this._materialControl.BaseControl.BindDataSource = null;
                        this._materialControl.BaseControl.BindDataSource = info;
                    }
                    else
                    {
                        ICSharpCode.Core.LoggingService<RefreshAction>.Warn("刷新配方信息失败:物料信息控件为Null...");
                    }
                }
            }
            catch (Exception ex)
            {

            }
           
        }


    }
}