using RGD.DBUtility;
using RGD.Model;
using System;
using System.Collections.Generic;
using System.Data;

namespace RGD.DataService
{
    public static class BaseDeviceService
    {
        private static Dictionary<int, Model.MError> _DeviceErrors;

        public static Dictionary<int, Model.MError> DeviceErrors
        {
            get { return _DeviceErrors; }
            set { _DeviceErrors = value; }
        }

        public static void SetDeviceMessage(Model.MDevice deviceinfo)
        {
            _DeviceInfo[deviceinfo.DeviceIndex].ReturnMessage = deviceinfo.ReturnMessage;
        }

        /// <summary>
        /// 初始化设备故障信息
        /// </summary>
        public static void AddDeviceErrors()
        {
            _DeviceErrors = new Dictionary<int, Model.MError>();
            DataView dv = DbHelperSQL.Query("SELECT F_ErrorIndex, F_DeviceKindIndex, F_DeviceErrorIndex, F_ErrorName, F_ErrorLevel, F_ManageStatus FROM T_Base_Device_State where F_DeviceErrorIndex>=30").Tables[0].DefaultView;
            for (int i = 0; i < dv.Count; i++)
            {
                Model.MError errs = new Model.MError();
                errs.ErrorIndex = Convert.ToInt32(dv[i]["F_ErrorIndex"]);
                errs.DeviceErrorIndex = Convert.ToInt32(dv[i]["F_DeviceErrorIndex"]);
                errs.DeviceKindIndex = Convert.ToInt32(dv[i]["F_DeviceKindIndex"]);
                errs.DeviceErrorIndex = Convert.ToInt32(dv[i]["F_DeviceErrorIndex"]);
                errs.ErrorName = dv[i]["F_ErrorName"].ToString();
                errs.ErrorLevel = Convert.ToInt32(dv[i]["F_ErrorLevel"]);
                errs.ManageStatus = Convert.ToInt32(dv[i]["F_ManageStatus"]);
                _DeviceErrors.Add(Convert.ToInt32(errs.DeviceKindIndex.ToString() + errs.DeviceErrorIndex.ToString()), errs);
            }
        }

        /// <summary>
        /// 通过设备类型+设备故障代码获取故障信息
        /// </summary>
        /// <param name="errID">设备类型+设备故障代码</param>
        /// <returns></returns>
        public static Model.MError GetErrorInfo(int errID)
        {
            MError value;
            if (false == _DeviceErrors.TryGetValue(errID, out value))
            {
                // value = _DeviceErrors[1111];
            }
            return value;
        }

        #region 设备集合

        private static Dictionary<int, Model.MDevice> _DeviceInfo;

        /// <summary>
        /// 加载到内存中的设备信息集合
        /// </summary>
        public static Dictionary<int, Model.MDevice> DeviceInfo
        {
            get { return _DeviceInfo; }
            set { _DeviceInfo = value; }
        }

        /// <summary>
        /// 向内存中添加设备信息
        /// </summary>
        public static void AddDeviceInfo()
        {
            _DeviceInfo = new Dictionary<int, Model.MDevice>();
            DataView dv = DbHelperSQL.Query("select * from T_Base_Device ").Tables[0].DefaultView;
            for (int i = 0; i < dv.Count; i++)
            {
                Model.MDevice devinfo = new Model.MDevice();
                if (dv[i]["F_AppendBarcode"] == DBNull.Value)
                {
                    devinfo.AppendBarcode = 0;
                }
                else
                {
                    devinfo.AppendBarcode = (int)dv[i]["F_AppendBarcode"];
                }
                if (dv[i]["F_BeDetected"] == DBNull.Value)
                {
                    devinfo.BeDetected = null;
                }
                else
                {
                    devinfo.BeDetected = dv[i]["F_BeDetected"].ToString();
                }
                if (dv[i]["F_BindingDevice"] == DBNull.Value)
                {
                    devinfo.BindingDevice = null;
                }
                else
                {
                    devinfo.BindingDevice = dv[i]["F_BindingDevice"].ToString();
                }
                if (dv[i]["F_BindingDeviceOut"] == DBNull.Value)
                {
                    devinfo.BindingDeviceOut = null;
                }
                else
                {
                    devinfo.BindingDeviceOut = dv[i]["F_BindingDeviceOut"].ToString();
                }
                if (dv[i]["F_CommType"] == DBNull.Value)
                {
                    devinfo.CommType = null;
                }
                else
                {
                    devinfo.CommType = dv[i]["F_CommType"].ToString();
                }

                if (dv[i]["F_DBW1Address"] == DBNull.Value)
                {
                    devinfo.Dbw1Address = -1;
                }
                else
                {
                    devinfo.Dbw1Address = (int)(dv[i]["F_DBW1Address"]);
                }
                if (dv[i]["F_DBWSendLength"] == DBNull.Value)
                {
                    devinfo.Dbw1SendLength = 0;
                }
                else
                {
                    devinfo.Dbw1SendLength = (int)dv[i]["F_DBWSendLength"];
                }
                if (dv[i]["F_DBW2Address"] == DBNull.Value)
                {
                    devinfo.Dbw2Address = -1;
                }
                else
                {
                    devinfo.Dbw2Address = (int)dv[i]["F_DBW2Address"];
                }
                if (dv[i]["F_DBWGetLength"] == DBNull.Value)
                {
                    devinfo.Dbw2Getlength = 0;
                }
                else
                {
                    devinfo.Dbw2Getlength = (decimal)dv[i]["F_DBWGetLength"];
                }
                if (dv[i]["F_DeviceIndex"] == DBNull.Value)
                {
                    devinfo.DeviceIndex = 0;
                }
                else
                {
                    devinfo.DeviceIndex = (int)dv[i]["F_DeviceIndex"];
                }
                if (dv[i]["F_DeviceKindIndex"] == DBNull.Value)
                {
                    devinfo.DeviceKind = 0;
                }
                else
                {
                    devinfo.DeviceKind = (int)dv[i]["F_DeviceKindIndex"];
                }
                if (dv[i]["F_DeviceName"] == DBNull.Value)
                {
                    devinfo.DeviceName = null;
                }
                else
                {
                    devinfo.DeviceName = (string)dv[i]["F_DeviceName"];
                }
                if (dv[i]["F_DeviceVisual"] == DBNull.Value)
                {
                    devinfo.DeviceVisual = 0;
                }
                else
                {
                    devinfo.DeviceVisual = (int)dv[i]["F_DeviceVisual"];
                }
                if (dv[i]["F_KeyDevice"] == DBNull.Value)
                {
                    devinfo.IfKeyDevice = '0';
                }
                else
                {
                    devinfo.IfKeyDevice = Convert.ToChar(dv[i]["F_KeyDevice"]);
                }
                if (dv[i]["F_MaxSendCount"] == DBNull.Value)
                {
                    devinfo.MaxSendCount = 0;
                }
                else
                {
                    devinfo.MaxSendCount = (int)dv[i]["F_MaxSendCount"];
                }
                if (dv[i]["F_NeedOptimize"] == DBNull.Value)
                {
                    devinfo.NeedOptimize = '0';
                }
                else
                {
                    devinfo.NeedOptimize = Convert.ToChar(dv[i]["F_NeedOptimize"]);
                }
                if (dv[i]["F_SendInterval"] == DBNull.Value)
                {
                    devinfo.SendInterval = 0;
                }
                else
                {
                    devinfo.SendInterval = (int)dv[i]["F_SendInterval"];
                }
                if (dv[i]["F_LocalIP"] == DBNull.Value)
                {
                    devinfo.LocalIP = "";
                }
                else
                {
                    devinfo.LocalIP = (string)dv[i]["F_LocalIP"];
                }
                if (dv[i]["F_LocalPort"] == DBNull.Value)
                {
                    devinfo.LocalPort = 0;
                }
                else
                {
                    devinfo.LocalPort = (int)dv[i]["F_LocalPort"];
                }
                if (dv[i]["F_RemoteIP"] == DBNull.Value)
                {
                    devinfo.RemoteIP = "";
                }
                else
                {
                    devinfo.RemoteIP = (string)dv[i]["F_RemoteIP"];
                }
                if (dv[i]["F_RemotePort"] == DBNull.Value)
                {
                    devinfo.RemotePort = 0;
                }
                else
                {
                    devinfo.RemotePort = (int)dv[i]["F_RemotePort"];
                }
                if (dv[i]["F_OPCProgID"] == DBNull.Value)
                {
                    devinfo.OPCProgID = "";
                }
                else
                {
                    devinfo.OPCProgID = (string)dv[i]["F_OPCProgID"];
                }
                if (dv[i]["F_ErrorTaskNo"] == DBNull.Value)
                {
                    devinfo.ErrorTaskNo = 0;
                }
                else
                {
                    devinfo.ErrorTaskNo = (int)dv[i]["F_ErrorTaskNo"];
                }
                if (dv[i]["F_SendOutDetect"] == DBNull.Value)
                {
                    devinfo.SendOutDetect = "0";
                }
                else
                {
                    devinfo.SendOutDetect = dv[i]["F_SendOutDetect"].ToString();
                }
                //
                if (dv[i]["F_OnlyDetectIO"] == DBNull.Value)
                {
                    devinfo.OnlyDetectIO = "0";
                }
                else
                {
                    devinfo.OnlyDetectIO = dv[i]["F_OnlyDetectIO"].ToString();
                }
                if (dv[i]["F_UseCommonDB"] == DBNull.Value)
                {
                    devinfo.UseCommonDB = "0";
                }
                else
                {
                    devinfo.UseCommonDB = dv[i]["F_UseCommonDB"].ToString();
                }
                if (dv[i]["F_IfCorrelDoubleFork"] == DBNull.Value)
                {
                    devinfo.IfCorrelDoubleFork = "0";
                }
                else
                {
                    devinfo.IfCorrelDoubleFork = dv[i]["F_IfCorrelDoubleFork"].ToString();
                }
                if (dv[i]["F_DoubleForkDetect"] == DBNull.Value)
                {
                    devinfo.DoubleForkDetect = "0";
                }
                else
                {
                    devinfo.DoubleForkDetect = dv[i]["F_DoubleForkDetect"].ToString();
                }
                if (dv[i]["F_DoubleFork"] == DBNull.Value)
                {
                    devinfo.DoubleFork = "0";
                }
                else
                {
                    devinfo.DoubleFork = dv[i]["F_DoubleFork"].ToString();
                }
                //20100609
                if (dv[i]["F_SerialPort"] == DBNull.Value)
                {
                    devinfo.SerialPort = 0;
                }
                else
                {
                    devinfo.SerialPort = Convert.ToInt32(dv[i]["F_SerialPort"]);
                }
                //20100609
                if (dv[i]["F_CommSettings"] == DBNull.Value)
                {
                    devinfo.CommSettings = "0";
                }
                else
                {
                    devinfo.CommSettings = dv[i]["F_CommSettings"].ToString();
                }
                //20100714
                if (dv[i]["F_S7Connection"] == DBNull.Value)
                {
                    devinfo.S7Connection = "S7:[S7 connection_1]";
                }
                else
                {
                    devinfo.S7Connection = dv[i]["F_S7Connection"].ToString();
                }
                //20101118
                if (dv[i]["F_SplitByte"] == DBNull.Value)
                {
                    devinfo.SplitByte = -1;
                }
                else
                {
                    devinfo.SplitByte = Convert.ToInt32(dv[i]["F_SplitByte"]);
                }
                _DeviceInfo.Add(devinfo.DeviceIndex, devinfo);
            }
        }

        /// <summary>
        /// 更新内存中的设备可变信息：故障码，是否有物，运行状态，任务号，当前X、Y坐标，控制方式，托盘条形码
        /// </summary>
        /// <param name="deviceinfo"></param>
        public static void SetDeviceInfo(Model.MDevice deviceinfo)
        {
            _DeviceInfo[deviceinfo.DeviceIndex].ErrorCode = deviceinfo.ErrorCode;
            _DeviceInfo[deviceinfo.DeviceIndex].HaveGoods = deviceinfo.HaveGoods;
            _DeviceInfo[deviceinfo.DeviceIndex].RunState = deviceinfo.RunState;
            _DeviceInfo[deviceinfo.DeviceIndex].TaskNo = deviceinfo.TaskNo;
            _DeviceInfo[deviceinfo.DeviceIndex].XCoor = deviceinfo.XCoor;
            _DeviceInfo[deviceinfo.DeviceIndex].YCoor = deviceinfo.YCoor;
            _DeviceInfo[deviceinfo.DeviceIndex].ControlMode = deviceinfo.ControlMode;
            _DeviceInfo[deviceinfo.DeviceIndex].Barcode = deviceinfo.Barcode;
        }

        /// <summary>
        /// 通过设备索引反馈设备信息
        /// </summary>
        /// <param name="DeviceIndex">设备索引</param>
        /// <returns></returns>
        public static Model.MDevice GetDeviceInfo(int DeviceIndex)
        {
            if (_DeviceInfo.ContainsKey(DeviceIndex) == true)
            {
                return _DeviceInfo[DeviceIndex];
            }
            else
            {
                return null;
            }
        }

        #endregion 设备集合

        #region 设备集合查询

        /// <summary>
        /// 获得设备类型索引
        /// </summary>
        /// <param name="devIdx">设备索引</param>
        /// <returns>设备类型索引</returns>
        public static int GetDeviceKindIdx(int devIdx)
        {
            try
            {
                return GetDeviceInfo(devIdx).DeviceKind;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 发送设备的送出指令时，需要检测的光电开关设备索引
        /// </summary>
        /// <param name="devinx"></param>
        /// <returns></returns>
        public static string GetSendOutDetect(int devinx)
        {
            MDevice devinfo = BaseDeviceService.GetDeviceInfo(devinx);
            if (devinfo.SendOutDetect == null) return "";
            return devinfo.SendOutDetect;
        }

        /// <summary>
        ///设备状态变化时更新设备上一次的状态
        /// </summary>
        /// <param name="deviceinfo"></param>
        public static void SetDeviceLastRunState(Model.MDevice deviceinfo)
        {
            _DeviceInfo[deviceinfo.DeviceIndex].LastRunState = deviceinfo.LastRunState;
        }

        #endregion 设备集合查询
    }
}