using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ExternalDataSync;
using MesServerWork;
using MisDataSaveDate;
using System.Net.Http;
using System.Web.Http;
using MisDataSaveDate.MOM;
using System.Data.SqlClient;
using static MisDataSaveDate.Helper.ApiLogHelper;
using WebApi;
using System.Security.Policy;
using System.Data;
using MisDataFunDll;
using System.Net;

namespace MisDataSaveDate
{
    /// <summary>
    /// WEB业务处理类
    /// </summary>
    public class WEB_BusinessLogic
    {
        /// <summary>
        /// WEB端发来的请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="jobj">请求的JSON对象</param>
        /// <returns>处理结果</returns>
        public static string WEB_Request(string url, [FromBody] JObject jobj)
        {
            var result = new MsgResHeader<string>();
            result.code = 200;
            result.message = "";

            if (jobj == null)
            {
                result.code = 500;
                result.message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                SaveMesLog("WEB进入请求", "参数格式不正确！", Helper.MesLogType.ERROR);
                MyLog4Net.MyLogHelper.Info("WEB请求进入接口res:", retString1);
                return retString1;
            }

            string str = jobj.ToString();
            //存储请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                // 解析WEB请求内容
                WEB_Request webRequest = JsonConvert.DeserializeObject<WEB_Request>(str);

                // 必填字段校验
                if (string.IsNullOrWhiteSpace(webRequest.type))
                {
                    throw new Exception("请求类型(type)不能为空");
                }
                switch (webRequest.type)
                {
                    case "OperAtion_JobStart":
                        // 手动重新开始工作
                        // 使用JObject的索引器或Value<T>方法来获取值
                        string workStation1 = webRequest.paramObj?["工位号"]?.ToString() ?? "";
                        string orderNo1 = webRequest.paramObj?["订单号"]?.ToString() ?? "";
                        string workpieceNo1 = webRequest.paramObj?["工件编号"]?.ToString() ?? "";

                        // 验证必要参数
                        if (string.IsNullOrWhiteSpace(workStation1) ||
                            string.IsNullOrWhiteSpace(orderNo1) ||
                            string.IsNullOrWhiteSpace(workpieceNo1))
                        {
                            throw new Exception("OperAtion_JobStart 缺少必要参数：工位号、订单号或工件编号");
                        }

                        CALL_Inerface_DataHandle.CALL_Inerface_JobStart(workStation1, workpieceNo1, orderNo1);
                        break;

                    case "OperAtion_JobFinished":
                        // 手动完成工作
                        // 使用JObject的索引器或Value<T>方法来获取值
                        string workStation2 = webRequest.paramObj?["工位号"]?.ToString() ?? "";
                        string orderNo2 = webRequest.paramObj?["订单号"]?.ToString() ?? "";
                        string workpieceNo2 = webRequest.paramObj?["工件编号"]?.ToString() ?? "";

                        // 验证必要参数
                        if (string.IsNullOrWhiteSpace(workStation2) ||
                            string.IsNullOrWhiteSpace(orderNo2) ||
                            string.IsNullOrWhiteSpace(workpieceNo2))
                        {
                            throw new Exception("OperAtion_JobFinished 缺少必要参数：工位号、订单号或工件编号");
                        }

                        CALL_Inerface_DataHandle.CALL_Inerface_JobFinished(workStation2, workpieceNo2, orderNo2);
                        break;

                    default:
                        result.code = 500;
                        result.message = "无此类型~";
                        break;
                }
            }
            catch (Exception err)
            {
                // 记录错误日志
                SaveMesLog("WEB端调用接口", err.Message, Helper.MesLogType.ERROR);

                result.code = 500;
                result.message = err.Message;
            }

            string retString = JsonConvert.SerializeObject(result);
            // 存储响应日志
            SaveLog_Interface_Response(retString, AID);
            return retString;
        }

        /// <summary>
        /// 批量读取PLC点位值
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="jobj">请求的JSON对象，包含OpName和TagTypeCodeIDs数组</param>
        /// <returns>处理结果</returns>
        public static string WEB_ReadPLCValues(string url, [FromBody] JObject jobj)
        {
            var result = new MsgResHeader<List<PLCTagValueResult>>
            {
                code = 200,
                message = "",
                Data = new List<PLCTagValueResult>()
            };

            if (jobj == null)
            {
                result.code = 500;
                result.message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                SaveMesLog("WEB批量读取PLC点位值", "参数格式不正确！", Helper.MesLogType.ERROR);
                MyLog4Net.MyLogHelper.Info("WEB_ReadPLCValues res:", retString1);
                return retString1;
            }

            string str = jobj.ToString();
            // 存储请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                string opName = jobj["OpName"]?.ToString() ?? "";
                JArray tagTypeCodeIDsArray = jobj["TagTypeCodeIDs"] as JArray;

                // 参数校验
                if (string.IsNullOrEmpty(opName))
                {
                    throw new Exception("工位号(OpName)不能为空");
                }

                if (tagTypeCodeIDsArray == null || tagTypeCodeIDsArray.Count == 0)
                {
                    throw new Exception("TagTypeCodeID数组不能为空");
                }

                int[] tagTypeCodeIDs = tagTypeCodeIDsArray.Select(x => (int)x).ToArray();

                // 读取工位全部数据
                var rtList = MIS_BASE.ReadPLC_OpName(opName);
                if (rtList == null)
                {
                    throw new Exception($"读取工位[{opName}]数据失败");
                }

                var pp = JsonConvert.SerializeObject(rtList);
                // 使用 dynamic 类型避免程序集引用问题
                var tagValues = JsonConvert.DeserializeObject<System.Collections.Concurrent.ConcurrentDictionary<string, dynamic>>(pp);

                // 根据传入的TagTypeCodeID数组过滤并返回对应的值
                foreach (var tagTypeCodeID in tagTypeCodeIDs)
                {
                    var tagResult = new PLCTagValueResult
                    {
                        TagTypeCodeID = tagTypeCodeID,
                        Success = false,
                        TagValue = null,
                        Message = ""
                    };

                    try
                    {
                        var matchedTag = tagValues.Where(x => (int)x.Value.TagTypeCodeID == tagTypeCodeID).FirstOrDefault();
                        if (matchedTag.Value != null)
                        {
                            tagResult.Success = true;
                            tagResult.TagValue = (int)matchedTag.Value.TagValue;
                            tagResult.TagName = (string)matchedTag.Value.TagName;
                            tagResult.OpName = (string)matchedTag.Value.OpName;
                            tagResult.TimeStamp = (string)matchedTag.Value.TimeStamp;
                        }
                        else
                        {
                            tagResult.Message = $"未找到TagTypeCodeID={tagTypeCodeID}的点位";
                        }
                    }
                    catch (Exception ex)
                    {
                        tagResult.Message = $"读取TagTypeCodeID={tagTypeCodeID}失败: {ex.Message}";
                    }

                    result.Data.Add(tagResult);
                }

                result.message = "读取成功";
            }
            catch (Exception err)
            {
                // 记录错误日志
                SaveMesLog("WEB批量读取PLC点位值", err.Message, Helper.MesLogType.ERROR);

                result.code = 500;
                result.message = err.Message;
                result.Data = null;
            }

            string retString = JsonConvert.SerializeObject(result);
            // 存储响应日志
            SaveLog_Interface_Response(retString, AID);
            return retString;
        }

        /// <summary>
        /// 写入PLC点位值
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="jobj">请求的JSON对象，包含TagTypeCodeID、OpName和TagValue</param>
        /// <returns>处理结果</returns>
        public static string WEB_WritePLC(string url, [FromBody] JObject jobj)
        {
            var result = new MsgResHeader<object>
            {
                code = 200,
                message = "",
                Data = null
            };

            if (jobj == null)
            {
                result.code = 500;
                result.message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                SaveMesLog("WEB写入PLC", "参数格式不正确！", Helper.MesLogType.ERROR);
                MyLog4Net.MyLogHelper.Info("WEB_WritePLC res:", retString1);
                return retString1;
            }

            string str = jobj.ToString();
            // 存储请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                int tagTypeCodeID = jobj["TagTypeCodeID"]?.Value<int>() ?? 0;
                string opName = jobj["OpName"]?.ToString() ?? "";
                object tagValue = jobj["TagValue"]?.ToObject<object>();

                // 参数校验
                if (string.IsNullOrEmpty(opName))
                {
                    throw new Exception("工位号(OpName)不能为空");
                }

                if (tagTypeCodeID == 0)
                {
                    throw new Exception("TagTypeCodeID不能为0");
                }

                // 调用MIS_BASE.WritePLC方法写入PLC
                bool writeResult = MIS_BASE.WritePLC(tagTypeCodeID, opName, tagValue);

                if (writeResult)
                {
                    result.code = 200;
                    result.message = "写入成功";
                    result.Data = new { Success = true };
                }
                else
                {
                    result.code = 500;
                    result.message = "写入失败";
                    result.Data = new { Success = false };
                }
            }
            catch (Exception err)
            {
                // 记录错误日志
                SaveMesLog("WEB写入PLC", err.Message, Helper.MesLogType.ERROR);

                result.code = 500;
                result.message = err.Message;
                result.Data = new { Success = false };
            }

            string retString = JsonConvert.SerializeObject(result);
            // 存储响应日志
            SaveLog_Interface_Response(retString, AID);
            return retString;
        }

        /// <summary>
        /// 磨合转序
        /// 调用AGV转序接口，成功后执行转序存储过程
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="jobj">请求的JSON对象，包含转序相关参数</param>
        /// <returns>处理结果</returns>
        public static string WEB_RunningInTransfer(string url, [FromBody] JObject jobj)
        {
            var result = new MsgResHeader<object>
            {
                code = 200,
                message = "",
                Data = null
            };

            if (jobj == null)
            {
                result.code = 500;
                result.message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                SaveMesLog("WEB磨合转序", "参数格式不正确！", Helper.MesLogType.ERROR);
                MyLog4Net.MyLogHelper.Info("WEB_RunningInTransfer res:", retString1);
                return retString1;
            }

            string str = jobj.ToString();
            // 存储请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                // 获取参数
                string startPositionCode = jobj["startPositionCode"]?.ToString() ?? "";
                string endPositionCode = jobj["endPositionCode"]?.ToString() ?? "";
                string productCode = jobj["productCode"]?.ToString() ?? "";
                string productModel = jobj["productModel"]?.ToString() ?? "";
                string targetProcess = jobj["targetProcess"]?.ToString() ?? "";
                string targetProcessNo = jobj["targetProcessNo"]?.ToString() ?? "";

                // 参数校验
                if (string.IsNullOrEmpty(startPositionCode) || string.IsNullOrEmpty(endPositionCode))
                {
                    throw new Exception("起始库位号和目标库位号不能为空");
                }

                // 1. 调用AGV转序接口
                var agvResult = CALL_Inerface_DataHandle.CALL_Inerface_MaterialTransfer(startPositionCode, endPositionCode);
                int agvCode = 500;
                int.TryParse(agvResult["code"]?.ToString() ?? "500", out agvCode);

                if (agvCode != 200)
                {
                    result.code = agvCode;
                    result.message = $"AGV调度失败：{agvResult["message"]?.ToString() ?? "未知错误"}";
                }
                else
                {
                    // 2. AGV调度成功，执行转序存储过程
                    var param = new SqlParameter[] {
                        new SqlParameter("@库位号", startPositionCode),
                        new SqlParameter("@产品编号", productCode),
                        new SqlParameter("@产品型号", productModel),
                        new SqlParameter("@目标库位号", endPositionCode),
                        new SqlParameter("@目标工序", targetProcess),
                        new SqlParameter("@目标工序号", targetProcessNo)
                    };

                    DataLinkMesWork2.DataAccess2.ExecuteStoredProcedure("XD_磨合_开始下一序", ref param, out string errMessage);

                    if (!string.IsNullOrEmpty(errMessage))
                    {
                        result.code = 500;
                        result.message = $"AGV调度成功，但存储过程执行失败：{errMessage}";
                    }
                    else
                    {
                        result.code = 200;
                        result.message = "转序操作成功";
                    }
                }
            }
            catch (Exception err)
            {
                // 记录错误日志
                SaveMesLog("WEB磨合转序", err.Message, Helper.MesLogType.ERROR);

                result.code = 500;
                result.message = err.Message;
            }

            string retString = JsonConvert.SerializeObject(result);
            // 存储响应日志
            SaveLog_Interface_Response(retString, AID);
            return retString;
        }
    }
}
