using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;

namespace Mesnac.Action.ChemicalWeighing.Product.PptPlan
{
    /// <summary>
    /// 生产管理-修改计划数业务
    /// </summary>
    public class ModifyPlanNumAction : ChemicalWeighingAction, IAction
    {
        #region 字段定义

        private RuntimeParameter _runtime;
        private DbMCControl _clientGridControl = null;      //网格计划控件

        #endregion

        #region 事件定义

        /// <summary>
        /// 修改计划数事件定义
        /// </summary>
        public static event EventHandler OnModifyPlanNum;

        #endregion

        #region 业务入口

        public void Run(RuntimeParameter runtime)
        {
            base.RunIni(runtime);       //必须要调用的
            this._runtime = runtime;
            ICSharpCode.Core.LoggingService<ModifyPlanNumAction>.Debug("生产计划-修改计划数...");
            try
            {
                #region 0 定义变量

                string selectedPlanId = null;                 //选中的计划号
                int selectedPlanSerial = 0;                   //保存选中的计划序号
                int selectedPlanCommand = 3;                  //计划命令:pcStart = 1 , pcHold = 2 , pcEdit = 3 , pcDelete = 4 , pcTerminate=5
                int selectedPlanNum = 0;                      //保存选中计划的计划数
                int selectedPlanUnfinished = 0;               //计划的剩余数
                int realNum = 0;
                int newPlanNum = 0;                           //新设定的计划数量

                #endregion

                #region 1 判断当班计划界面是否打开

                if (PlanHelper.IsInit == false)
                {
                    string msg1 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_PptPlan_ModifyPlanNumAction_msg1"));          // 当班计划还未初始化,请先打开当班计划,再进行此操作!
                    MessageBox.Show(msg1, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                #endregion

                #region 2 获取界面控件

                DbMCControl clientGridControl = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "RT_plan").FirstOrDefault();
                if (clientGridControl == null)
                {
                    ICSharpCode.Core.LoggingService<StopAction>.Error("{生产计划-修改计划数}  缺少计划列表网格控件...");
                    return;
                }
                this._runtime = runtime;
                this._clientGridControl = clientGridControl;
                DataGridView clientGridView = this._clientGridControl.BaseControl as DataGridView;

                #endregion

                #region 3 检验执行修改计划数的条件

                #region 3.2 判断是否选择了要修改计划数的计划

                if (clientGridView.SelectedRows.Count != 1)
                {
                    string msg1_1 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_PptPlan_ModifyPlanNumAction_msg1_1"));          //请选择一条要修改计划数的计划!
                    MessageBox.Show(msg1_1, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this._runtime.IsReturn = true;
                    return;
                }

                selectedPlanId = clientGridView.SelectedRows[0].Cells["Plan_Id"].Value as string;                                       //获取选中的计划号
                selectedPlanSerial = Convert.ToInt32(clientGridView.SelectedRows[0].Cells["Plan_Serial"].Value);                        //获取选中的计划序号
                selectedPlanNum = Convert.ToInt32(clientGridView.SelectedRows[0].Cells["Plan_Num"].Value);                              //获取选中的计划数

                #endregion

                #region 3.3 判断计划状态是否合法

                //PlanState planState = (PlanState)Convert.ToInt32(clientGridView.SelectedRows[0].Cells["Plan_State"].Value);
                PlanState planState = (PlanState)PlanHelper.StateToValue(clientGridView.SelectedRows[0].Cells["Plan_StateText"].Value.ToString());

                if (planState == PlanState.Terminated)
                {
                    string msg7 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_PptPlan_ModifyPlanNumAction_msg1_2"));      //当前计划已终止,不能执行此操作!
                    MessageBox.Show(msg7, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (planState == PlanState.Completed)
                {
                    string msg7 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_PptPlan_ModifyPlanNumAction_msg1_3"));      //当前计划已完成,不能执行此操作!
                    MessageBox.Show(msg7, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                #endregion

                #region 3.4 获取选中计划数据

                Entity.RT_Plan currentPlan = PlanHelper.GetPlanDataEntity(selectedPlanId);       //获取当前计划数据
                if (currentPlan == null)
                {
                    ICSharpCode.Core.LoggingService<ModifyPlanNumAction>.Warn("生产管理-修改计划数-获取当前计划数据失败...");
                    return;
                }

                realNum = (int)currentPlan.Real_Num;

                #endregion

                #endregion

                #region 4 执行修改计划数

                FrmModifyPlanNum frmModifyPlanNum = new FrmModifyPlanNum(selectedPlanNum);
                //FrmModifyPlanNum frmModifyPlanNum = new FrmModifyPlanNum();
                DialogResult result = frmModifyPlanNum.ShowDialog();
                if (result == DialogResult.OK)
                {
                    newPlanNum = frmModifyPlanNum.NewPlanNum;
                    
                    frmModifyPlanNum.Dispose();

                    #region 4.1 验证新计划数的合法性

                    if (newPlanNum <= realNum)
                    {
                        string msg30 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_PptPlan_ModifyPlanNumAction_msg1_4"));        //当前计划设定数[{0}]不能低于完成数[{1}]!
                        MessageBox.Show(msg30, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    int numModifyMin = BasePlcHelper.Instance.MinPlanNum;               //获取下位机允许修改的最小计划数(此处的最小计划数由PLC实时读取)
                    if (newPlanNum < numModifyMin)
                    {
                        string msg40 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_PptPlan_ModifyPlanNumAction_msg1_5"));      //当前计划设定数[{0}]不能低于下位机允许的最小车数[{1}]!
                        MessageBox.Show(msg40, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    #endregion

                    string msg14 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_PptPlan_ModifyPlanNumAction_msg1_6"));      //确认修改设定次数为{0}?
                    msg14 = String.Format(msg14, newPlanNum);
                    if (MessageBox.Show(msg14, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        #region 4.2 修改PLC计划数

                        selectedPlanUnfinished = newPlanNum - realNum;     //获取选中的剩余数
                        List<string> msgList = new List<string>();
                        if (!ChemicalWeighingPlc.PlcPlanHelper.ExecModifyPlanNum(selectedPlanSerial, selectedPlanCommand, newPlanNum, selectedPlanUnfinished, true, msgList))
                        {
                            if (msgList.Count > 0)
                            {
                                base.DBLog(Mesnac.Basic.DataProcessor.CombineMsgList(msgList));
                            }
                            return;
                        }

                        #endregion

                        #region 4.3 记录操作日志

                        string logContent = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Product_PptPlan_ModifyPlanNumAction_logContent"));      //修改计划数,计划号{0}的计划数从{1}车改到{2}车!
                        logContent = String.Format(logContent, selectedPlanId, selectedPlanNum, newPlanNum);
                        //base.DBLog(logContent);

                        #endregion

                        #region 4.4 更新数据库

                        PlanHelper.UpdatePlanNum(selectedPlanId, newPlanNum);
                        
                        #endregion

                        #region 4.5 触发刷新计划事件

                        if (OnModifyPlanNum != null)
                        {
                            OnModifyPlanNum(runtime, System.EventArgs.Empty);
                        }

                        #endregion
                    }
                }
                else
                {
                    frmModifyPlanNum.Dispose();
                }

                #endregion
            }
            catch (Exception ex)
            {
                ICSharpCode.Core.LoggingService<ModifyPlanNumAction>.Error("修改计划数失败:" + ex.Message, ex);
                MessageBox.Show(ex.Message, Mesnac.Basic.LanguageHelper.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #endregion
    }
}