using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using WebApi.Models;
using WebApi.Helpers;
using System.Reflection;
using Logger;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WebApi
{
    public class ServerController
    {
        private static readonly HttpClient httpClient;
        public static event Action<string> ShowMsg; // 记录日志事件

        static ServerController()
        {
            httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromSeconds(20); // 设置超时时间为20秒
        }

        /// <summary>
        /// UUID生成
        /// </summary>
        /// <returns></returns>
        public static string UuidUtil()
        {
            string result = Guid.NewGuid().ToString();
            return result;
        }

        public static int SaveWebApiReqLogo(string url, string JSON)
        {
            int AID = -1;
            try
            {
                //存储日志
                var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                var param = new Dictionary<string, Object>{
                    { "接口地址", url },
                    { "接口类型", 2 },
                    { "请求内容", JSON },
                    { "请求时间", CreateTime }
                };
                SqlServer.ExecuteProcedure("接口_IOT接口交互日志_请求记录", param, out DataTable dt, out string err);
                if (dt.Rows.Count > 0)
                {
                    AID = Convert.ToInt32(dt.Rows[0]["AID"]);
                }
            }
            catch (Exception ex)
            {
                Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
            }
            return AID;
        }

        public static int SaveWebApiResLogo(int AID, string JSON)
        {
            try
            {

                //new SqlParameter("@AID",AID),
                //new SqlParameter("@响应时间",CreateTime),
                //new SqlParameter("@响应内容",JsonConvert.SerializeObject(result))

                //存储日志
                var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                var param = new Dictionary<string, Object>{
                    { "AID", AID },
                    { "响应时间", CreateTime },
                    { "响应内容", JSON },
                };
                SqlServer.ExecuteProcedure("接口_IOT接口交互日志_响应记录", param, out DataTable dt, out string err);
                if (dt.Rows.Count > 0)
                {
                    AID = Convert.ToInt32(dt.Rows[0]["AID"]);
                }
            }
            catch (Exception ex)
            {
                Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
            }
            return AID;
        }

        /// <summary>
        /// 测试标准接口方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TestPost(string url, string json)
        {
            var result = new msgResHeader();
            //result.taskId = UuidUtil();
            result.Result = false;
            result.ErrMsg = "";
            result.Data = "";

            string errorMessage = "";
            int AID = -1;
            try
            {
                AID = SaveWebApiReqLogo(url, json);

                // 解析订单内容，存储数据库，根据实际业务来写
                test personnelBaseData = JsonConvert.DeserializeObject<test>(json);
                ShowMsg?.Invoke("【" + url + "】code" + personnelBaseData.code + ",msg:" + personnelBaseData.msg);
                //result.msg = errorMessage;

                AID = SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result));
            }
            catch (Exception err)
            {
                result.Result = false;
                result.ErrMsg = err.Message;
                result.Data = "ERROR";
                Log.FunError(err, MethodBase.GetCurrentMethod().Name);
            }

            return JsonConvert.SerializeObject(result);
        }

        /// <summary>
        /// 前端对AGV通用的接口转发
        /// </summary>
        /// <param name="url"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static async Task<string> MES_To_AGV_From_WEB(string url, string json)
        {
            var result = new msgResHeader();
            result.Result = false;
            result.ErrMsg = "";
            result.Data = "";

            string errorMessage = "";
            int AID = -1;
            try
            {
                // 显示一下接口日志
                ShowMsg?.Invoke("Receive【" + url + "】" + json);
                AID = SaveWebApiReqLogo(url, json);

                MES_To_AGV_From_WEB_Req personnelBaseData = JsonConvert.DeserializeObject<MES_To_AGV_From_WEB_Req>(json);
                // 验证必填字段
                if (!ValidationHelper.ValidateRequired(personnelBaseData, out errorMessage))
                {
                    ShowMsg?.Invoke($"****************{errorMessage}");
                    result.ErrMsg = errorMessage;
                    return JsonConvert.SerializeObject(result);
                }

                string AGVApiBaseUrl = Tools.AppConfigManage.ReadConfig("AGVApiBaseUrl");
                string AGVIP = Tools.AppConfigManage.ReadConfig("AGVIP");
                string AGVApiUrl = "http://" + AGVIP + AGVApiBaseUrl + personnelBaseData.url;

                // 发送POST请求
                var content = new StringContent(
                    JsonConvert.SerializeObject(personnelBaseData.data),
                    Encoding.UTF8,
                    "application/json"
                );

                var response = await httpClient.PostAsync(AGVApiUrl, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    result.Result = true;
                    result.Data = responseContent;
                }
                else
                {
                    result.Result = false;
                    result.ErrMsg = $"请求失败: {response.StatusCode} - {responseContent}";
                }

                AID = SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result));
            }
            catch (TaskCanceledException ex)
            {
                if (!ex.CancellationToken.IsCancellationRequested)
                {
                    ShowMsg?.Invoke("请求超时，请检查目标服务是否可达或响应过慢！");
                    result.ErrMsg = "请求超时，请检查目标服务是否可达或响应过慢！";
                }
                else
                {
                    ShowMsg?.Invoke("请求被主动取消！");
                    result.ErrMsg = "请求被主动取消！";
                }
                result.Data = "ERROR";
                Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
            }
            catch (Exception err)
            {
                result.Result = false;
                result.ErrMsg = err.Message;
                result.Data = "ERROR";
                Log.FunError(err, MethodBase.GetCurrentMethod().Name);
            }

            return JsonConvert.SerializeObject(result);
        }

        /// <summary>
        /// 前端对AGV通用的接口转发
        /// 测试版
        /// </summary>
        /// <param name="url"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static async Task<string> MES_To_AGV_From_WEB_Test(string url, string json)
        {
            var result = new msgResHeader();
            result.Result = false;
            result.ErrMsg = "";
            result.Data = "";

            string errorMessage = "";
            int AID = -1;
            try
            {
                // 显示一下接口日志
                ShowMsg?.Invoke("Receive【" + url + "】" + json);
                AID = SaveWebApiReqLogo(url, json);

                var result2 = new msgResHeader();
                result2.Result = true;
                result2.ErrMsg = "";
                result2.Data = "";

                MES_To_AGV_From_WEB_Req personnelBaseData = JsonConvert.DeserializeObject<MES_To_AGV_From_WEB_Req>(json);
                // 验证必填字段
                if (!ValidationHelper.ValidateRequired(personnelBaseData, out errorMessage))
                {
                    ShowMsg?.Invoke($"****************{errorMessage}"); 
                    result.ErrMsg = errorMessage;
                    return JsonConvert.SerializeObject(result);
                }

                // 手动模拟
                // 接口1 库区列表查询 返回固定JSON数据
                if(personnelBaseData.url == "getPartitionList")
                {
                    var partitionList = new List<object>
                    {
                        new { PartitionCode = "1", PartitionName = "隔离开关操作试验区" },
                        new { PartitionCode = "2", PartitionName = "断路器线边缓存位" },
                        new { PartitionCode = "3", PartitionName = "CT装配区" },
                        new { PartitionCode = "4", PartitionName = "断路器下线" },
                        new { PartitionCode = "5", PartitionName = "OP30产线工位" },
                        new { PartitionCode = "6", PartitionName = "线边缓存库" },
                        new { PartitionCode = "7", PartitionName = "断路器试验区" },
                        new { PartitionCode = "8", PartitionName = "隔离开关安装操作缓存区" },
                        new { PartitionCode = "9", PartitionName = "隔离开关下线" },
                        new { PartitionCode = "10", PartitionName = "断路器缓存区" },
                        new { PartitionCode = "11", PartitionName = "OP20产线工位" },
                        new { PartitionCode = "12", PartitionName = "OP10产线工位" }
                    };
                    result.Result = true;
                    result2.Data = partitionList;
                    result.Data = JsonConvert.SerializeObject(result2);
                }

                // 接口2 库位列表查询 返回固定JSON数据
                if(personnelBaseData.url == "getStockList")
                {
                    var stockList = new List<object>
                    {
                        // StockCode 库位编号
                        // StockName 库位名称
                        // StockStatus 满料状态 bool
                        // PalletCode 托盘编号
                        // EngineNo 产品编号
                        // SortNo 产品型号
                        // TaskId 任务号
                        
                        new { StockCode = "6", StockName = "工位线边缓存位1", StockStatus = true, PalletCode = "pallTestCode1", EngineNo = "GCBTest01", SortNo = "P7223814G003", TaskId = "12312" },
                        new { StockCode = "16", StockName = "工位线边缓存位2", StockStatus = true, PalletCode = "pallTestCode2", EngineNo = "CTTest01-1", SortNo = "P7223363G001", TaskId = (string)null },
                        new { StockCode = "30", StockName = "工位线边缓存位3", StockStatus = false, PalletCode = "pallTestCode3", EngineNo = (string)null, SortNo = (string)null, TaskId = (string)null },
                        new { StockCode = "2", StockName = "工位线边缓存位4", StockStatus = false, PalletCode = (string)null, EngineNo = (string)null, SortNo = (string)null, TaskId = (string)null },
                    };
                    result.Result = true;
                    result2.Data = stockList;
                    result.Data = JsonConvert.SerializeObject(result2);

                }

                // 接口3 更新库位信息
                if (personnelBaseData.url == "updateStockInfo")
                {
                    result.Result = true;
                    result.Data = JsonConvert.SerializeObject(result2);
                }

                // 接口4 创建送料任务
                if (personnelBaseData.url == "createTask")
                {
                    result.Result = true;
                    result.Data = JsonConvert.SerializeObject(result2);
                }

                AID = SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result));
            }
            catch (TaskCanceledException ex)
            {
                if (!ex.CancellationToken.IsCancellationRequested)
                {
                    ShowMsg?.Invoke("请求超时，请检查目标服务是否可达或响应过慢！");
                    result.ErrMsg = "请求超时，请检查目标服务是否可达或响应过慢！";
                }
                else
                {
                    ShowMsg?.Invoke("请求被主动取消！");
                    result.ErrMsg = "请求被主动取消！";
                }
                result.Data = "ERROR";
                Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
            }
            catch (Exception err)
            {
                result.Result = false;
                result.ErrMsg = err.Message;
                result.Data = "ERROR";
                Log.FunError(err, MethodBase.GetCurrentMethod().Name);
            }

            return JsonConvert.SerializeObject(result);
        }

        /// <summary>
        /// AGV到位,离开
        /// </summary>
        /// <param name="url"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static async Task<string> AGV_To_MES_AgvPass(string url, string json)
        {
            var result = new msgResHeader();
            result.Result = false;
            result.ErrMsg = "";
            result.Data = "";

            string errorMessage = "";
            int AID = -1;
            try
            {
                // 显示一下接口日志
                ShowMsg?.Invoke("Receive【" + url + "】" + json);
                AID = SaveWebApiReqLogo(url, json);

                // 解析订单内容，存储数据库，根据实际业务来写
                AGV_To_MES_AgvPass_Req personnelBaseData = JsonConvert.DeserializeObject<AGV_To_MES_AgvPass_Req>(json);

                // 验证必填字段
                if (!ValidationHelper.ValidateRequired(personnelBaseData, out errorMessage))
                {
                    ShowMsg?.Invoke($"****************{errorMessage}");
                    result.ErrMsg = errorMessage;
                    return JsonConvert.SerializeObject(result);
                }


                int workOverType = 0;
                if (personnelBaseData.type == 0)
                {
                    workOverType = 1;
                }
                else if (personnelBaseData.type == 1)
                {
                    workOverType = 3;
                }
                else
                {
                    ShowMsg?.Invoke($"****************未识别的type{workOverType}");
                    result.ErrMsg = $"未识别的Type{workOverType}";
                    return JsonConvert.SerializeObject(result);
                }

                var param = new Dictionary<string, Object>{
                    { "工位号", personnelBaseData.station },
                    { "任务编号", personnelBaseData.taskId },
                    { "工件编号", personnelBaseData.EngineNo },
                    { "type",  workOverType},
                };
                SqlServer.ExecuteProcedure("PTCHV_AGV_进离站", param, out DataTable dt, out errorMessage);
                // 验证必填字段
                if (errorMessage.Length > 0)
                {
                    ShowMsg?.Invoke($"****************{errorMessage}");
                    result.ErrMsg = errorMessage;
                    return JsonConvert.SerializeObject(result);
                }

                await MqttServer.SendMqttMessageToOp(personnelBaseData.station, "AGVStatus", workOverType.ToString());

                result.Result = true;
                AID = SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result));
            }
            catch (Exception err)
            {
                result.Result = false;
                result.ErrMsg = err.Message;
                result.Data = "ERROR";
                Log.FunError(err, MethodBase.GetCurrentMethod().Name);
            }

            return JsonConvert.SerializeObject(result);
        }
    }
}
