using NEIntelligentControl2.Models;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Service.User;
using NEIntelligentControl2.Service.WebSocket;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NEIntelligentControl2.Service.Windturbine
{
    /// <summary>
    /// 风机控制服务
    /// </summary>
    public class ControlManager
    {
        private WEBHelper _WEBHelper;
        private UrlManager _UrlManager;
        private string _Url;
        private string[] _ErrorInfo;
        public ControlManager(WEBHelper web, UrlManager urlm)
        {
            _WEBHelper = web;
            _UrlManager = urlm;
            _Url = _UrlManager.ServicePath;


            InitErrorCode();
        }

        private void InitErrorCode()
        {
            _ErrorInfo = new string[]
            {
                "控制成功",
                "控制命令发送失败",
                "无效的控制地址",
                "被控设备异常",
                "无效的控制功能",
                "网络未连接",
                "命令已发送，但是读取结果超时",
                "发送指令失败",
                "控制的命令出错",
                "未知错误",
                "未知错误",
                "未知错误",
                "风机操作过频繁",
                "风机被挂牌",
                "风机操作与风机状态不符"
            };
        }

        internal string SendLock(Dictionary<string, ControlInstruction> cis)
        {
            try
            {
                var cc = _WEBHelper.HttpPostBody<Dictionary<string, ControlInstruction>>($"{_Url}/api/control/lock", cis);

                StringBuilder sb = new StringBuilder();
                foreach (var v in cc)
                {
                    if (v.Value.ErrorCode != "0")
                    {
                        int.TryParse(v.Value.ErrorCode, out int i);
                        if (i < _ErrorInfo.Length)
                        {
                            sb.Append(v.Value.WindturbineId).Append("挂牌失败：").Append(_ErrorInfo[i]).Append("\n");
                        }
                    }
                }
                return sb.ToString();
            }
            catch { }
            return null;
        }

        /// <summary>
        /// 发送指令，不检查用户
        /// </summary>
        /// <returns></returns>
        public string SendCmdNotCheck(Dictionary<string, ControlInstruction> cis)
        {
            try
            {
                var cc = _WEBHelper.HttpPostBody<Dictionary<string, ControlInstruction>>($"{_Url}/api/control/", cis);

                StringBuilder sb = new StringBuilder();
                foreach (var v in cc)
                {
                    if (v.Value.ErrorCode != "0")
                    {
                        bool b = int.TryParse(v.Value.ErrorCode, out int i);
                        if (!b) i = 9;
                        if (i < _ErrorInfo.Length)
                        {
                            sb.Append(v.Value.WindturbineId).Append("控制失败：").Append(_ErrorInfo[i]).Append("\n");
                        }
                    }
                }
                return sb.ToString();
            }
            catch { }
            return null;
        }

        public string SendCmd(Dictionary<string, ControlInstruction> cis)
        {
            try
            {
                var cc = _WEBHelper.HttpPostBody<Dictionary<string, ControlInstruction>>($"{_Url}/api/control/", cis);

                StringBuilder sb = new StringBuilder();
                foreach (var v in cc)
                {
                    if (v.Value.ErrorCode != "0")
                    {
                        bool b = int.TryParse(v.Value.ErrorCode, out int i);
                        i = !b ? 9 : i;
                        if (i < _ErrorInfo.Length)
                        {
                            sb.Append(v.Value.WindturbineId).Append("控制失败：").Append(_ErrorInfo[i]).Append("\n");
                        }
                    }
                }
                return sb.ToString();
            }
            catch { }
            return null;
        }

        public ControlRecordPage GetControlRecord(string stationId, string startTime, string endTime)
        {
            try
            {
                var v = _WEBHelper.HttpGetJSON<ControlRecordPage>($"{_Url}/control-record/search?stationId={stationId}&startTime={startTime}&endTime={endTime}&pageSize=5000&pageIndex=1");
                return v;
            }
            catch { }
            return null;
        }

        /// <summary>
        /// 获取控制日志
        /// </summary>
        /// <returns></returns>
        public string GetControlLog()
        {
            try
            {
                var vs = _WEBHelper.HttpGetJSON<List<ControlLog>>($"{_Url}/control-record/log");
                if (vs == null || vs.Count <= 0) return "";
                var sb = new StringBuilder();
                foreach (var v in vs)
                {
                    sb.Append(v.ToString()).Append("\n");
                }
                return sb.ToString();
            }
            catch { }
            return "";
        }
    }

    class ControlLog
    {
        private static string[] errorCodes;
        /// <summary>
        /// 时间戳
        /// </summary>
        public long Timestamp { get; set; }
        /// <summary>
        /// 风机ID
        /// </summary>
        public string WindturbineId { get; set; }
        /// <summary>
        /// 错误码
        /// </summary>
        public int ErrorCode { get; set; }
        /// <summary>
        /// 控制类型
        /// </summary>
        public OperateStyle Type { get; set; }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            var vs = WindturbineId.Split('_');
            var name = $"{vs[0].Substring(0, vs[0].Length - 2)}{vs[1]}";
            sb.Append(Timestamp.GetTimeString()).Append("\t").Append(name).Append("\t").Append(Type.GetStringValue());
            if (ErrorCode == 0)
            {
                sb.Append("\t控制成功");
            }
            else
            {
                sb.Append("[失败]\t[原因]").Append(GetErrorInfo(ErrorCode));
            }
            return sb.ToString();
        }

        private string GetErrorInfo(int errorCode)
        {
            if (errorCodes == null)
            {
                errorCodes = new string[]
            {
                "未知错误",
                "控制命令发送失败",
                "无效的控制地址",
                "被控设备异常",
                "无效的控制功能",
                "网络未连接",
                "命令已发送，但是读取结果超时",
                "发送指令失败",
                "控制的命令出错",
                "未知错误",
                "未知错误",
                "未知错误",
                "风机操作过频繁",
                "风机被挂牌",
                "风机操作与风机状态不符"
            };
            }
            if (errorCode < 0 || errorCode >= errorCodes.Length)
            {
                return errorCodes[0];
            }
            return errorCodes[errorCode];
        }
    }
}
