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;
using Mesnac.Action.ChemicalWeighing.Entity.PptPlan;
using FastReport.Data;
using Mesnac.Action.ChemicalWeighing.XlPlcHelper;
using Mesnac.Action.ChemicalWeighing.Report;
using Mesnac.Action.ChemicalWeighing.BinManage;

namespace Mesnac.Action.ChemicalWeighing.Product.XlPlan
{
    /// <summary>
    /// 手动下发计划
    /// </summary>
    public class ManualRefreshAction : 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;
        #endregion

        #region IAction接口实现

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

            #region 手动下传计划

            lock (string.Empty)
            {
                DbMCControl clientGridControl = this.GetDbMCControlByKey(Mesnac.Basic.DataSourceFactory.MCDbType.Local, "xl_plan").FirstOrDefault();
                if (clientGridControl == null)
                {
                    ICSharpCode.Core.LoggingService<StopAction>.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;
                }
                

                string planState = clientGridView.SelectedRows[0].Cells["Plan_State"].Value.ToString();
                if (planState== "8")
                {
                    MessageBox.Show("该计划已完成,无法手动下发!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (planState == "7")
                {
                    MessageBox.Show("该计划已终止,无法手动下发!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (planState == "3")
                {
                    MessageBox.Show("该计划正在运行中,无法手动下发!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                selectedPlanId = clientGridView.SelectedRows[0].Cells["Plan_Id"].Value as string;
                bool IsExec = Product.XlPlan.PlanHelper.GetXlPlanState(selectedPlanId);//检查当前任务是否还处于执行中
                if (IsExec)
                {
                    MessageBox.Show("该计划正在执行中,请勿重新下发!", Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ICSharpCode.Core.LoggingService<StopAction>.Error("{生产计划-手动下发计划}  该计划正在执行中...");
                    return;
                }
                //获取选中计划、获取选中物料、//获取选中工位
                List<Xl_DowLoadPlan> materialList = XlPlan.PlanHelper.GetXlPlan2(selectedPlanId);
           
                if (materialList.Count() == 0 || materialList == null)
                {
                    ICSharpCode.Core.LoggingService<PlcPlanHelper>.Debug(String.Format("未查询到数据", selectedPlanId));
                    return;
                }
                //下传计划给PLC
                bool IsSucess = PlcPlanHelper.ManualXlPlanToPlc(materialList);
                if (IsSucess)
                {
                    Pmt_Shiftime shiftTime = PlanHelper.GetShiftClass();
                    //回写计划任务状态 3:任务执行中
                    PlanHelper.UpdateStartPlanState(selectedPlanId, 3, shiftTime.Shift_id, shiftTime.Shift_name);
                    MessageBox.Show("计划任务下发成功!");
                    ICSharpCode.Core.LoggingService<PlcPlanHelper>.Debug(String.Format("[{0}]计划信息下传完毕...", selectedPlanId));
                }
                else
                {
                    MessageBox.Show("计划任务下发失败!请检查配方是否设置完整、PLC是否正常");
                    ICSharpCode.Core.LoggingService<PlcPlanHelper>.Debug(String.Format("[{0}]计划信息下传失败...", selectedPlanId));
                }
                IsFirstRun = false;
            }

            #endregion

            this.DoWork();
        }

        #endregion

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

            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

    }
}