using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Resources;

using DBFactory;
using ICommLayer;
using CommLayerFactory;
namespace CommonLibrary
{
    /// <summary>
    /// 获得设备状态
    /// </summary>
    public class CGetState
    {
        DBOperator dbo1 = new DBOperator();
        DBOperator dbo = new DBOperator();
        DBOperator dboM = new DBOperator("ManConnString", "ManDBFactory");
        string _CGetStateError = "";//监控调度类错误说明
        public string CGetStateError
        {
            get { return _CGetStateError; }
            set { _CGetStateError = value; }
        }
        public int[] _States;
        int _fid;
        int _mti;
        int _iotype=0;
        int _endnode=0;
        /// <summary>
        /// 获得所有正在执行设备的状态
        /// </summary>
        public CGetState()
        {
            dbo.Open();
            if (dboM.Open() == false)
            {
                //if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("连接管理数据库失败！！！") < 0)
                //{
                    
                //    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "连接管理数据库失败！！！", true);
                //}
            }
            
        }
        
       
        /// <summary>
        /// 报告完成
        ///电器反馈该设备的"完成"时 删除监控任务 , 解除设备表占用状态F_LockedState=0；
        ///路径明细表F_LockedDeviceIndex里的所有对应设备索引解锁
        /// 
        ///判断是最后一个监控任务吗? 是,回写管理任务IO_Control的FSTATUS=2即"搬运完成";
        /// T_Base_Manage_Task的正在执行状态FSTATUS=2 ；
        /// </summary>
        /// <param name="DeviceIdx">设备索引</param>
        /// <param name="TaskIdx">监控任务索引</param>
        public void ActionComplete(int DeviceIdx,int TaskIdx)
        {
            int ccfreturn;
            
            dbo.TransBegin();
            try
            {
                string  retu=GetDetailIndexFromMonitor(TaskIdx);

                GetManage_Kind(TaskIdx);
                int fid = _fid ;
                int mti = _mti ;
                string cap;
                DataSet ds = dbo.ExceSQL("select count(F_MonitorIndex) as counts from T_Base_Monitor_Task "+
                    " where F_ManageTaskIndex =" + fid + " and F_ManageTaskKindIndex= "+mti);
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    if ((Convert.ToInt32(ds.Tables[0].DefaultView[0]["counts"]) == 1) && (CStaticClass.RouteSearchMode == "0")) 
                    {
                        //管理任务的fid的最后一个监控分解任务完成
                        //回写管理任务IO_Control的FSTATUS=2即"搬运完成";T_Base_Manage_Task的正在执行状态FSTATUS=2 ；

                        if (mti == 1)
                        {
                            cap = "管理任务";
                            //判断是否为软确认任务，是就改为FSTATUS=4；
                            dboM.ExceSQL("update IO_Control set FSTATUS='4' where FID=" + fid);
                        }
                        else if (mti == 4)
                        {
                            cap = "手工任务";
                        }
                        else
                        {
                            cap = "临时任务";
                        }
                        //回写管理表
                        ReturnManageInfo(fid, mti,cap,true);
                    }
                    
                }
               
                if ((CStaticClass.RouteSearchMode == "1"))
                {
                    if (mti == 4)
                    {
                        //回写管理表
                        cap = "手工任务";
                        ReturnManageInfo(fid, mti,cap,true);
                        
                    }
                    else
                    {
                        cap = "临时任务";
                        //根据路径索引，在详细路径中找到设备和命令，判断是否为该设备的最后一个命令
                        //判断命令是否包含“;”，没有此字符就是最后一个命令；如果有此字符就判断是否为最后一个
                        if (retu == "") return;
                        char[] cc = new char[1] { '-' };
                        string[] split=retu.Split(cc);
                        if (IFDeviceLastOrder(Convert.ToInt32(split[0]),DeviceIdx,Convert.ToInt32(split[1]) ) == true)
                        {
                            ccfreturn = ccf.StepsRouteSearch(false, fid, mti, _iotype, DeviceIdx, _endnode);
                            if (ccfreturn == 9999)
                            {
                                if (mti == 1)
                                {
                                    //判断是否为软确认任务，是就改为FSTATUS=4；
                                    dboM.ExceSQL("update IO_Control set FSTATUS='4' where FID=" + fid);
                                }
                                //回写管理表
                                ReturnManageInfo(fid, mti,cap,true);
                            }
                        }
                    }
                   
                }
                //判断此设备是否为码盘机器人码盘完成后的任务，在表T_BASE_STACK_ROBOT查找DeviceIdx
                dbo.ExceSQL("UPDATE T_BASE_STACK_ROBOT SET F_ManageID = NULL WHERE F_StackPositionDeviceIndex = " + DeviceIdx);

                //解除设备表占用状态F_LockedState=0；路径明细表F_LockedDeviceIndex里的所有对应设备索引解锁 ,删除监控任务 
                dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + DeviceIdx);
                dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_LockedState=" + TaskIdx);
                dbo.ExceSQL("delete from T_Base_Monitor_Task   where F_MonitorIndex=" + TaskIdx);
                dbo.TransCommit();

                //刷新监控中心显示
                //显示监控任务
                RefreshControlMonitor(DeviceIdx);
            }
            catch (Exception ex)
            {
                dbo.TransRollback();
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("报告完成时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "报告完成时：" + ex.Message, true);
                    
                }
                //throw ex;
            }
        }
        /// <summary>
        /// 回写设备错误状态字（IO_Control,T_Base_Manage_task,T_Monitor_task）
        /// </summary>
        /// <param name="DeviceIdx">设备索引</param>
        /// <param name="TaskIdx">监控任务索引</param>
        /// <param name="ErrId">错误编号</param>
        public void ActionError(int DeviceIdx, int TaskIdx,int ErrId)
        {
            dbo.TransBegin();
            try
            {
                
                GetManage_Kind(TaskIdx);
                int fid = _fid;
                int mti = _mti;
                DataSet ds = dbo.ExceSQL("SELECT F_ErrorIndex,F_ErrorName,T_Base_Device_State.F_DeviceKindIndex," +
                    " F_DeviceErrorIndex,F_ManageStatus,F_DeviceIndex,F_DeviceName FROM T_Base_Device_State,T_Base_Device Where " +
                    " T_Base_Device_State.F_DeviceKindIndex = T_Base_Device.F_DeviceKindIndex and F_DeviceIndex="
                    + DeviceIdx + " and F_DeviceErrorIndex= " + ErrId);
                DataView dv = ds.Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    FrmMain.FormInstance.notifyIcon1.ShowBalloonTip(10000, "警告", dv[0]["F_DeviceName"].ToString()+"发生故障：" + dv[0]["F_ErrorName"].ToString(), System.Windows.Forms.ToolTipIcon.Warning);
                    if (mti == 1)
                    {
                        if (dv[0]["F_ManageStatus"] == DBNull.Value)
                        {
                            dboM.ExceSQL("update IO_Control set FSTATUS=" + ErrId + " where FID=" + fid);
                        }
                        else
                        {
                            dboM.ExceSQL("update IO_Control set FSTATUS=" + Convert.ToInt32(dv[0]["F_ManageStatus"]) + " where FID=" + fid);
                        }
                    }
                    ds = dbo.ExceSQL("SELECT F_DeviceIndex, F_ErrorIndex FROM T_Base_Device_Error_Log Where F_DeviceIndex=" + DeviceIdx + " and F_ErrorIndex=" + Convert.ToInt32(dv[0]["F_ErrorIndex"]));
                    if (ds.Tables[0].DefaultView.Count > 0)
                    {
                        dbo.ExceSQL("UPDATE T_Base_Device_Error_Log SET F_DateTime ='" + DateTime.Now.ToString("u") + "'  Where F_DeviceIndex=" + DeviceIdx + " and F_ErrorIndex=" + Convert.ToInt32(dv[0]["F_ErrorIndex"]));
                    }
                    else
                    {
                        dbo.ExceSQL("INSERT INTO T_Base_Device_Error_Log (F_DeviceIndex, F_ErrorIndex, F_DateTime) VALUES ("+ DeviceIdx  +","+ Convert.ToInt32( dv[0]["F_ErrorIndex"])+",'"+DateTime.Now.ToString("u") +"')");
                    }
                }
                dbo.ExceSQL("update T_Base_Monitor_Task set F_Status= " + ErrId + "  where F_MonitorIndex= " + TaskIdx);
                dbo.ExceSQL("update T_Base_Manage_task set FSTATUS='" + ErrId.ToString() + "' where FID=" + fid + " and F_ManageTaskKindIndex= " + mti);
                
                dbo.TransCommit();
                //根据设备类型判断错误编号
                ISendDeviceOrder sdo;
                CCommonFunction ccf = new CCommonFunction();
                if (ccf.GetDeviceKindIdx(DeviceIdx) == 2)
                {//输送机故障清零
                    sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                    sdo.SendDeviceOrder(0, 0, 0, DeviceIdx);
                }
                if (ccf.GetDeviceKindIdx(DeviceIdx) == 1) //堆垛机
                {

                    sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                    sdo.SendDeviceOrder(0, 0, 0, DeviceIdx, 0, 0, 0, 0, 0, 0);
                }
                //刷新监控中心显示
                RefreshControlMonitor(DeviceIdx);
            }
            catch (Exception ex)
            {
                dbo.TransRollback();
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("向管理反馈设备错误时：" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "向管理反馈设备错误时：" + ex.Message, true);
                    
                }
                //throw ex;
            }

        }
        /// <summary>
        /// 删除监控任务。如果是最后一个监控任务，回写管理任务IO_Control的FSTATUS=-1。
        /// </summary>
        /// <param name="DeviceIdx">设备索引</param>
        /// <param name="TaskIdx">监控任务索引</param>
        public void ActionDelete(int DeviceIdx, int TaskIdx)
        {

            CCommonFunction ccf = new CCommonFunction();

            DataView dvstate = dbo.ExceSQL("SELECT F_MonitorIndex, F_Status FROM " +
                "T_Base_Monitor_Task where F_MonitorIndex=" + TaskIdx + " and F_Status>=1").Tables[0].DefaultView;

            if (dvstate.Count > 0) //正在运行
            {
                ISendDeviceOrder sdo;
                sdo = CommModeCreate.CreateSendDeviceOrder(DeviceIdx);
                sdo.SendDeviceOrder(0, 0, 0, DeviceIdx);
            }
            dbo.TransBegin();
            try
            {
                string retu = GetDetailIndexFromMonitor(TaskIdx);

                GetManage_Kind(TaskIdx);
                int fid = _fid;
                int mti = _mti;
                string cap;
                DataSet ds = dbo.ExceSQL("select count(F_MonitorIndex) as counts from T_Base_Monitor_Task " +
                    " where F_ManageTaskIndex =" + fid + " and F_ManageTaskKindIndex= " + mti);
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    if ((Convert.ToInt32(ds.Tables[0].DefaultView[0]["counts"]) == 1) && (CStaticClass.RouteSearchMode == "0"))
                    {
                        //管理任务的fid的最后一个监控分解任务完成
                        //回写管理任务IO_Control的FSTATUS=-1

                        if (mti == 1)
                        {
                            cap = "管理任务";
                            dboM.ExceSQL("update IO_Control set FSTATUS='-1' where FID=" + fid);
                        }
                        else if (mti == 4)
                        {
                            cap = "手工任务";
                        }
                        else
                        {
                            cap = "临时任务";
                        }
                        //回写管理表
                        ReturnManageInfo(fid, mti, cap, false);
                    }

                }

                if ((CStaticClass.RouteSearchMode == "1"))
                {
                    if (mti == 4)
                    {
                        //回写管理表
                        cap = "手工任务";
                        ReturnManageInfo(fid, mti, cap, false);

                    }
                    else
                    {
                        cap = "临时任务";
                        //根据路径索引，在详细路径中找到设备和命令，判断是否为该设备的最后一个命令
                        //判断命令是否包含“;”，没有此字符就是最后一个命令；如果有此字符就判断是否为最后一个
                        if (retu == "") return;
                        char[] cc = new char[1] { '-' };
                        string[] split = retu.Split(cc);
                        if (IFDeviceLastOrder(Convert.ToInt32(split[0]), DeviceIdx, Convert.ToInt32(split[1])) == true)
                        {
                            //ccfreturn = ccf.StepsRouteSearch(false, fid, mti, _iotype, DeviceIdx, _endnode);
                            //if (ccfreturn == 9999)
                            //{
                            if (mti == 1)
                            {

                                dboM.ExceSQL("update IO_Control set FSTATUS='-1' where FID=" + fid);
                            }
                            //回写管理表
                            ReturnManageInfo(fid, mti, cap, false);
                            //}
                        }
                    }

                }

                //20080728
                //修改货位表的货架执行状态和货架是否有盘状态；


                //判断此设备是否为码盘机器人码盘完成后的任务，在表T_BASE_STACK_ROBOT查找DeviceIdx
                dbo.ExceSQL("UPDATE T_BASE_STACK_ROBOT SET F_ManageID = NULL WHERE F_StackPositionDeviceIndex = " + DeviceIdx);

                //解除设备表占用状态F_LockedState=0；路径明细表F_LockedDeviceIndex里的所有对应设备索引解锁 ,删除监控任务 
                dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=" + DeviceIdx);
                dbo.ExceSQL("update T_Base_Device set F_LockedState=0 where F_LockedState=" + TaskIdx);
                dbo.ExceSQL("delete from T_Base_Monitor_Task   where F_MonitorIndex=" + TaskIdx);
                dbo.TransCommit();

                //刷新监控中心显示
                //显示监控任务
                RefreshControlMonitor(DeviceIdx);
            }
            catch (Exception ex)
            {
                dbo.TransRollback();
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("报告完成时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "报告完成时：" + ex.Message, true);
                }
                //throw ex;
            }
        }
       
    }
}
