using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DBFactory;
using CommLayerFactory;
using ICommLayer;
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 如果正在运行的设备有AheadTrigger信息，则在T_Base_Route_Detail表找到AheadTrigger
    /// 的设备索引和命令字；根据调度任务类型和调度任务索引找到T_Monitor_Task表对应的
    /// 设备指令索引是否存在，存在而且处于等待执行状态那就发送提前触发命令（发送前检查是否符合发送命令条件）。
    /// </summary>
    public class CAheadTriggerMoveDevice
    {
        DBOperator dbo =CStaticClass.dbo;
        string _CControlError = "";//监控调度类错误说明
        public string CControlError
        {
            get { return _CControlError; }
            set { _CControlError = value; }
        }

        /// <summary>
        /// 发送设备的提前触发移动设备和命令
        /// </summary>
        /// <param name="manKindIdx">调度任务类型索引</param>
        /// <param name="manIdx">调度任务索引</param>
        /// <param name="AheadTrigger">提前触发移动设备-命令</param>
        public CAheadTriggerMoveDevice()
        {
            int manKindIdx; int manIdx; int DetailIndex; string AheadTrigger;
            int devIdx, devOrder;
            char[] cc = new char[1] {'-' };
            string[] spl;
            
            DataView dvm,dv;
            dv = dbo.ExceSQL("SELECT F_ManageTaskKindIndex,F_ManageTaskIndex,T_Base_Route_Detail.F_DetailIndex, T_Base_Route_Detail.F_AheadTrigger FROM T_Base_Route_Detail,T_Monitor_Task WHERE T_Base_Route_Detail.F_DetailIndex = T_Monitor_Task.F_DetailIndex AND (T_Base_Route_Detail.F_AheadTrigger IS NOT NULL) AND (T_Base_Route_Detail.F_AheadTrigger <> '') AND (T_Monitor_Task.F_Status = 1)").Tables[0].DefaultView;
            if (dv.Count <= 0) return;
            for(int i=0;i<dv.Count ;i++)
            {
                manKindIdx = Convert.ToInt32(dv[i]["F_ManageTaskKindIndex"]);
                manIdx = Convert.ToInt32(dv[i]["F_ManageTaskIndex"]);
                DetailIndex = Convert.ToInt32(dv[i]["F_DetailIndex"]);
                AheadTrigger = dv[i]["F_AheadTrigger"].ToString();
                spl = AheadTrigger.Split(cc);
                devIdx = Convert.ToInt32(spl[0]);
                devOrder = Convert.ToInt32(spl[1]);
                dvm = dbo.ExceSQL("SELECT F_ManageTaskIndex, F_ManageTaskKindIndex,F_MonitorIndex, F_DeviceIndex, F_DeviceCommandIndex," +
                    " F_Status FROM T_Monitor_Task WHERE F_ManageTaskKindIndex=" +
                    manKindIdx + " AND F_ManageTaskIndex=" + manIdx + " AND F_DeviceIndex=" + devIdx +
                    " AND F_DeviceCommandIndex=" + devOrder + " AND F_Status=0").Tables[0].DefaultView;

                if (dvm.Count > 0)
                {
                    CControl cct = new CControl();
                    CCommonFunction ccf = new CCommonFunction();
                    bool sendok = false;
                    if (cct.GetFirstDeviceIFLocked(Convert.ToInt32(dvm[0]["F_MonitorIndex"]),true ) == false)
                    {
                        int[] gc = ccf.GetCoordinatesFromMonitorTask(Convert.ToInt32(dvm[0]["F_MonitorIndex"]));//获得坐标
                        if (gc != null)
                        {
                            //发送此设备命令
                            ISendDeviceOrder sdo;
                            //CStaticClass.MessageIndex++;
                            CStaticClass.MessageIndex = 1;
                            int msgIdx = (CStaticClass.MessageIndex);
                            sdo = CommModeCreate.CreateSendDeviceOrder(devIdx);
                            //1：堆垛机；4：RGV；6：AGV如果需要优化调度（设备表的F_NeedOptimize='1'）
                            //直接写入表：T_Monitor_Task_Child，不发送命令
                            if (ccf.NeedOptimize(devIdx) == true)
                            {
                                ccf.InsertMonitorOptimizeChildTask(Convert.ToInt32(dvm[0]["F_MonitorIndex"]));
                                sendok = true;
                            }
                            else
                            {
                                sendok = sdo.SendDeviceOrder(msgIdx, Convert.ToInt32(dvm[0]["F_MonitorIndex"]), devOrder,
                                    devIdx, gc[0], gc[1], gc[2], gc[3], gc[4], gc[5]);
                            }
                            if (sendok == false)
                            {
                                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf(sdo.CommLayerError) < 0)
                                {
                                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", sdo.CommLayerError, true);

                                }
                            }
                            else
                            {
                                ccf.SendOrderSuccess(manKindIdx, manIdx, Convert.ToInt32(dvm[0]["F_MonitorIndex"]), devIdx, DetailIndex);

                            }
                        }
                        else
                        {
                            this._CControlError += "发送命令时不能取得设备坐标！";

                        }
                    }
                }
            }
                
        }
    }
}
