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.Action.ChemicalWeighing.Entity.PptPlan;
using Mesnac.Action.ChemicalWeighing.ChemicalWeighingPlc;
using Mesnac.Action.ChemicalWeighing.Entity;
using Steema.TeeChart.Styles;

namespace Mesnac.Action.ChemicalWeighing.Product.PptPlan
{
    /// <summary>
    /// 手动下发计划
    /// </summary>
    public class PlanDownloadAction : ChemicalWeighingAction,IAction
    {
        #region 事件定义

        /// <summary>
        /// 手动下发计划
        /// </summary>
        public static event EventHandler OnRefreshPlan;

        #endregion

        #region 字段定义
        public int MyProperty { get; set; }
        private static bool IsFirstRun = true;  //是否首次执行
        private RuntimeParameter _runtime;
        //private DbMCControl _planDateControl = null;        //计划日期
        //private DbMCControl _pptShiftControl = null;        //班次
        private DbMCControl _clientGridControl = null;      //网格计划控件
        string selectedPlanId = string.Empty;                 //选中的计划号
        string selectedRecipeID = string.Empty; 
        List<MetagePlan> materialList = new List<MetagePlan>();
       
        #endregion

        #region IAction接口实现

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

            ICSharpCode.Core.LoggingService<RefreshAction>.Debug("当班计划—刷新计划业务...");

            #region 手动下传计划

            if (true)
            {
                DbMCControl clientGridControl = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "RT_plan").FirstOrDefault();
                if (clientGridControl == null)
                {
                    ICSharpCode.Core.LoggingService<PlanDownloadAction>.Error("{生产计划-下发}  缺少计划列表网格控件...");
                    return;
                }
                this._runtime = runtime;
                this._clientGridControl = clientGridControl;
                DataGridView clientGridView = this._clientGridControl.BaseControl as DataGridView;
                if (clientGridView.SelectedRows.Count != 1)
                {
                    string msg1_1 = StringParser.Parse("请选择一条要下传的计划!");//请选择一条要下传计划数的计划!
                    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;
                selectedRecipeID = clientGridView.SelectedRows[0].Cells["Recipe_ID"].Value as string;
                //判断任务是否完成
                //判断任务是在执行中
                string planState = clientGridView.SelectedRows[0].Cells["Plan_State"].Value.ToString();
                if (planState== "8")
                {
                    MessageBox.Show("该计划已完成,请选择其他计划!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                   // bool IsExec = Product.PptPlan.PlanHelper.GetRtPlanState(selectedPlanId);//检查当前任务是否还处于执行中
                if (planState == "3")
                {
                    MessageBox.Show("该计划正在执行中,请勿重新下发!");
                    ICSharpCode.Core.LoggingService<PlanDownloadAction>.Error("{生产计划-手动下发计划}  该计划正在执行中...");
                    return;
                }
                string weighbridge = clientGridView.SelectedRows[0].Cells["Weighbridge"].Value.ToString();
                if (string.IsNullOrEmpty(weighbridge))
                {
                    MessageBox.Show("地磅为空,不可以下发任务!");
                    ICSharpCode.Core.LoggingService<PlanDownloadAction>.Error("{生产计划-手动下发计划} 地磅为空.");
                    return;
                }
                //任务还在称量中,不允许下发计划
                //if (weighbridge == "1号地磅")
                //{
                //    int status = BasePlcHelper.Instance.solvent_SystemRuning.NowValue.ToInt();
                //    if (status == 1)
                //    {
                //        MessageBox.Show("配方还在正在执行中,请勿下发!");
                //        ICSharpCode.Core.LoggingService<PlanDownloadAction>.Error("{生产计划-手动下发计划} 配方正在执行中...");
                //        return;
                //    }
                //}
                //if (weighbridge == "2号地磅")
                //{
                //    int status = BasePlcHelper.Instance.solvent2_SystemRuning.NowValue.ToInt();
                //    if (status ==1)
                //    {
                //        MessageBox.Show("配方还在正在执行中,请勿下发!");
                //        ICSharpCode.Core.LoggingService<PlanDownloadAction>.Error("{生产计划-手动下发计划}  配方正在执行中...");
                //        return;
                //    }
                //}


                //获取选中计划、获取选中物料
                materialList = PlanHelper.GetPlan(selectedPlanId);
                List<MetagePlan> emptList = GetEmptList(materialList.Count());

                List<MetagePlan> list = (materialList.Concat(emptList)).ToList();
                //下传计划给PLC
               
                bool IsSucess=false;
                if (weighbridge=="1号地磅")
                {
                     IsSucess = PlcPlanHelper.DownloadPlanDataToWeighbridge1Plc(list);
                }
                if (weighbridge == "2号地磅")
                {
                    IsSucess = PlcPlanHelper.DownloadPlanDataToWeighbridge2Plc(list);
                }
                
                if (IsSucess)
                {
                    //回写计划任务状态 3:任务执行中
                    PlanHelper.UpdatePlanState1(selectedPlanId, 3);
                    MessageBox.Show("计划任务下发成功!");
                    ICSharpCode.Core.LoggingService<PlanDownloadAction>.Debug(String.Format("[{0}]计划信息下传完毕...", selectedPlanId));
                }
                else
                {
                    MessageBox.Show("计划任务下发失败!请检查配方是否设置完整、PLC是否正常");
                    ICSharpCode.Core.LoggingService<PlanDownloadAction>.Debug(String.Format("[{0}]计划信息下传失败...", selectedPlanId));
                }
                IsFirstRun = false;
            }

            #endregion

            this.DoWork();
        }

        #endregion

        #region 方法定义
        /// <summary>
        /// 刷新计划
        /// </summary>
        protected void DoWork()
        {
            #region 业务实现

            //int shiftID = Global.PublicVar.Instance.globalShiftID;
            //int.TryParse(this._pptShiftControl.BaseControl.MCValue.ToString(), out shiftID);
            string equipCode = base.CurrEquipCode;      //当前机台
            //DateTime selectedDate = Convert.ToDateTime(this._planDateControl.BaseControl.MCValue); 
            //DataTable table = PlanHelper.GetPlanData(selectedDate, shiftID);
            //DataTable table = PlanHelper.GetPlanData(selectedDate);
            DataTable table = PlanHelper.GetPlanData();
            lock (String.Empty)
            {
                //本地计划
                if (this._clientGridControl != null && this._clientGridControl.BaseControl != null)
                {
                    this._clientGridControl.BaseControl.BindDataSource = null;
                    this._clientGridControl.BaseControl.BindDataSource = table;

                    #region 根据计划状态处理背景色

                    DataGridView clientGrid = this._clientGridControl.BaseControl as DataGridView;
                    PlanHelper.SetBackColor(clientGrid);

                    #endregion
                }
                else
                {
                    ICSharpCode.Core.LoggingService<RefreshAction>.Warn("手动下传计划:本地计划控件为Null...");
                }
            }
            #endregion

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

            Global.PublicVar.Instance.LocalPlanIsRefresh = true;            //更新机台计划刷新标志

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

            #endregion
        }

        #endregion

        #region 事件处理方法

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

        #endregion

        public List<MetagePlan> GetEmptList(int k)
        {
            List<MetagePlan> EmptylList = new List<MetagePlan>();
            for (int i = (k+1); i <= 50; i++)
            {
                MetagePlan plan = new MetagePlan();
                plan.MID = 0;
                plan.Set_Weight = 0;
                plan.Set_Error = 0;
                EmptylList.Add(plan);
            }
            return EmptylList;
        }
    }
}