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 MisDataSaveDate;
using System.Web.Http;
using static MisDataSaveDate.Helper.ApiLogHelper;
using MisDataSaveDate.Helper;

namespace MisDataSaveDate
{
    /// <summary>
    /// 西开 AGV 业务处理类
    /// 处理 AGV -> MES 的接收请求
    /// </summary>
    public class ZZAGV_BusinessLogic
    {
        /// <summary>
        /// 处理状态更新请求（到达/离开）
        /// </summary>
        /// <param name="url">接口URL</param>
        /// <param name="jobj">请求数据</param>
        /// <returns>处理结果 JSON 字符串</returns>
        public static string ProcessStatusUpdate(string url, [FromBody] JObject jobj)
        {
            var result = ZZAGV_Response.Success();
            string str = jobj?.ToString() ?? "";

            // 存储请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                if (jobj == null)
                {
                    throw new Exception("请求参数不能为空");
                }

                ZZAGV_StatusUpdateRequest request = JsonConvert.DeserializeObject<ZZAGV_StatusUpdateRequest>(str);

                // 参数校验
                if (string.IsNullOrWhiteSpace(request.position))
                {
                    throw new Exception("工位编号(position)不能为空");
                }

                string typeDesc = request.type == 1 ? "到达" : (request.type == 2 ? "离开" : "未知");
                SaveMesLog("ZZAGV_StatusUpdate", $"AGV状态更新：工位={request.position}, 类型={typeDesc}, AGV={request.agvid}, 物料={request.materialCode}", MesLogType.INFO);

                // TODO: 后续业务逻辑在此添加

            }
            catch (Exception ex)
            {
                result = ZZAGV_Response.Fail(1, ex.Message);
                SaveMesLog("ZZAGV_StatusUpdate", $"处理异常：{ex.Message}", MesLogType.ERROR);
            }

            string retString = JsonConvert.SerializeObject(result);
            SaveLog_Interface_Response(retString, AID);
            return retString;
        }

        /// <summary>
        /// 处理动作完成请求（举升/下降）
        /// </summary>
        /// <param name="url">接口URL</param>
        /// <param name="jobj">请求数据</param>
        /// <returns>处理结果 JSON 字符串</returns>
        public static string ProcessActionComplete(string url, [FromBody] JObject jobj)
        {
            var result = ZZAGV_Response.Success();
            string str = jobj?.ToString() ?? "";

            // 存储请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                if (jobj == null)
                {
                    throw new Exception("请求参数不能为空");
                }

                ZZAGV_ActionCompleteRequest request = JsonConvert.DeserializeObject<ZZAGV_ActionCompleteRequest>(str);

                // 参数校验
                if (string.IsNullOrWhiteSpace(request.position))
                {
                    throw new Exception("工位编号(position)不能为空");
                }

                string typeDesc = request.type == 1 ? "举升完成" : (request.type == 2 ? "下降完成" : "未知");
                SaveMesLog("ZZAGV_ActionComplete", $"AGV动作完成：工位={request.position}, 类型={typeDesc}", MesLogType.INFO);

                // TODO: 后续业务逻辑在此添加

            }
            catch (Exception ex)
            {
                result = ZZAGV_Response.Fail(1, ex.Message);
                SaveMesLog("ZZAGV_ActionComplete", $"处理异常：{ex.Message}", MesLogType.ERROR);
            }

            string retString = JsonConvert.SerializeObject(result);
            SaveLog_Interface_Response(retString, AID);
            return retString;
        }

        /// <summary>
        /// 处理故障/报警推送请求
        /// </summary>
        /// <param name="url">接口URL</param>
        /// <param name="jobj">请求数据</param>
        /// <returns>处理结果 JSON 字符串</returns>
        public static string ProcessAlarmPush(string url, [FromBody] JObject jobj)
        {
            var result = ZZAGV_Response.Success();
            string str = jobj?.ToString() ?? "";

            // 存储请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                if (jobj == null)
                {
                    throw new Exception("请求参数不能为空");
                }

                ZZAGV_AlarmPushRequest request = JsonConvert.DeserializeObject<ZZAGV_AlarmPushRequest>(str);

                string typeDesc = request.type == 1 ? "AGV故障" : (request.type == 2 ? "区域故障" : "未知");
                SaveMesLog("ZZAGV_AlarmPush", $"AGV故障推送：类型={typeDesc}, AGV={request.agvNo}, 故障码={request.errorCode}, 信息={request.errorMsg}", MesLogType.WARNING);

                // TODO: 后续业务逻辑在此添加

            }
            catch (Exception ex)
            {
                result = ZZAGV_Response.Fail(1, ex.Message);
                SaveMesLog("ZZAGV_AlarmPush", $"处理异常：{ex.Message}", MesLogType.ERROR);
            }

            string retString = JsonConvert.SerializeObject(result);
            SaveLog_Interface_Response(retString, AID);
            return retString;
        }

        /// <summary>
        /// 处理任务执行结果请求
        /// </summary>
        /// <param name="url">接口URL</param>
        /// <param name="jobj">请求数据</param>
        /// <returns>处理结果 JSON 字符串</returns>
        public static string ProcessTaskResult(string url, [FromBody] JObject jobj)
        {
            var result = ZZAGV_Response.Success();
            string str = jobj?.ToString() ?? "";

            // 存储请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                if (jobj == null)
                {
                    throw new Exception("请求参数不能为空");
                }

                ZZAGV_TaskResultRequest request = JsonConvert.DeserializeObject<ZZAGV_TaskResultRequest>(str);

                // 参数校验
                if (string.IsNullOrWhiteSpace(request.requestTaskId))
                {
                    throw new Exception("任务ID(requestTaskId)不能为空");
                }

                string statusDesc = request.status == "success" ? "成功" : "失败";
                SaveMesLog("ZZAGV_TaskResult", $"AGV任务结果：任务ID={request.requestTaskId}, 状态={statusDesc}, AGV={request.agvNo}, 消息={request.message}", MesLogType.INFO);

                // TODO: 后续业务逻辑在此添加

            }
            catch (Exception ex)
            {
                result = ZZAGV_Response.Fail(1, ex.Message);
                SaveMesLog("ZZAGV_TaskResult", $"处理异常：{ex.Message}", MesLogType.ERROR);
            }

            string retString = JsonConvert.SerializeObject(result);
            SaveLog_Interface_Response(retString, AID);
            return retString;
        }
    }
}
