using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Models;


namespace WebApiCall
{
    /// <summary>
    /// WMS WebApi调用类
    /// </summary>
    public class AGVWebApiCall
    {
        private static readonly HttpClient httpClient;

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

        /// <summary>
        /// MES叫料接口 - 同步版本，返回bool结果
        /// </summary>
        /// <param name="storageCode">叫料位置（库位号）</param>
        /// <param name="goodsCode">物料号（型号）</param>
        /// <returns>是否成功</returns>
        public static bool MES_To_AGV_CallGoods(string storageCode, string goodsCode)
        {
            try
            {
                var task = MES_To_AGV_CallGoods_Async(storageCode, goodsCode);
                task.Wait(); // 同步等待异步任务完成
                return task.Result;
            }
            catch (Exception err)
            {
                string errorMsg = $"叫料同步调用异常 - 库位: {storageCode}, 物料号: {goodsCode}, 异常: {err.Message}";
                LogHelper.ShowMsg(errorMsg);
                Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {errorMsg}");
                return false;
            }
        }

        /// <summary>
        /// MES叫料接口 - 内部异步实现
        /// </summary>
        private static async Task<bool> MES_To_AGV_CallGoods_Async(string storageCode, string goodsCode)
        {
            int AID = -1;
            try
            {
                string WMSIPPort = ConfigurationManager.AppSettings["AGVIPPort"];
                string url = $"http://{WMSIPPort}/wms/apiForThirdPartySys/callGoods";

                var requestData = new MES_To_AGV_CallGoods_Req
                {
                    storageCode = storageCode,
                    goodsCode = goodsCode
                };

                string json = JsonConvert.SerializeObject(requestData);
                LogHelper.ShowMsg($"发起叫料请求 - 库位: {storageCode}, 物料号: {goodsCode} -> Send【{url}】{json}");
                AID = LogHelper.SaveWebApiReqLogo(url, json);

                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                LogHelper.ShowMsg($"叫料响应 - 库位: {storageCode}, 物料号: {goodsCode} -> Response【{url}】{responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    // 解析WMS响应
                    var wmsResponse = JsonConvert.DeserializeObject<WmsApiResponse>(responseContent);
                    
                    if (wmsResponse != null && wmsResponse.code == 200)
                    {
                        LogHelper.ShowMsg($"叫料成功 - 库位: {storageCode}, 物料号: {goodsCode}, 响应消息: {wmsResponse.msg}");
                        LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(wmsResponse));
                        return true;
                    }
                    else
                    {
                        LogHelper.ShowMsg($"叫料失败 - 库位: {storageCode}, 物料号: {goodsCode}, 错误信息: {wmsResponse?.msg ?? "未知错误"}");
                        LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(wmsResponse));
                        return false;
                    }
                }
                else
                {
                    string msg = $"叫料HTTP请求失败 - 库位: {storageCode}, 物料号: {goodsCode}, 状态码: {response.StatusCode}, 响应: {responseContent}";
                    LogHelper.ShowMsg(msg);
                    LogHelper.SaveWebApiResLogo(AID, msg);
                    return false;
                }
            }
            catch (Exception err)
            {
                string errorMsg = $"叫料异常 - 库位: {storageCode}, 物料号: {goodsCode}, 异常详情: {err.Message}";
                LogHelper.ShowMsg(errorMsg);
                Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {errorMsg}");
                if (AID > 0)
                {
                    LogHelper.SaveWebApiResLogo(AID, errorMsg);
                }
                return false;
            }
        }

        /// <summary>
        /// MES退料接口 - 同步版本，返回bool结果
        /// </summary>
        /// <param name="storageCode">退料位置（库位号）</param>
        /// <param name="goodsCode">物料号（型号）</param>
        /// <param name="isEmpty">是否为空 0.空托 1.余料</param>
        /// <returns>是否成功</returns>
        public static bool MES_To_AGV_ReturnGoods(string storageCode, string goodsCode, int isEmpty)
        {
            try
            {
                var task = MES_To_AGV_ReturnGoods_Async(storageCode, goodsCode, isEmpty);
                task.Wait(); // 同步等待异步任务完成
                return task.Result;
            }
            catch (Exception err)
            {
                string emptyTypeDesc = isEmpty == 0 ? "空托" : "余料";
                string errorMsg = $"退料同步调用异常 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 异常: {err.Message}";
                LogHelper.ShowMsg(errorMsg);
                Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {errorMsg}");
                return false;
            }
        }

        /// <summary>
        /// MES退料接口 - 内部异步实现
        /// </summary>
        private static async Task<bool> MES_To_AGV_ReturnGoods_Async(string storageCode, string goodsCode, int isEmpty)
        {
            int AID = -1;
            try
            {
                string emptyTypeDesc = isEmpty == 0 ? "空托" : "余料";
                string WMSIPPort = ConfigurationManager.AppSettings["AGVIPPort"];
                string url = $"http://{WMSIPPort}/wms/apiForThirdPartySys/returnGoods";

                var requestData = new MES_To_AGV_ReturnGoods_Req
                {
                    storageCode = storageCode,
                    goodsCode = goodsCode,
                    isEmpty = isEmpty
                };

                string json = JsonConvert.SerializeObject(requestData);
                LogHelper.ShowMsg($"发起退料请求 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}) -> Send【{url}】{json}");
                AID = LogHelper.SaveWebApiReqLogo(url, json);

                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                LogHelper.ShowMsg($"退料响应 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}) -> Response【{url}】{responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    // 解析WMS响应
                    var wmsResponse = JsonConvert.DeserializeObject<WmsApiResponse>(responseContent);
                    
                    if (wmsResponse != null && wmsResponse.code == 200)
                    {
                        LogHelper.ShowMsg($"退料成功 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 响应消息: {wmsResponse.msg}");
                        LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(wmsResponse));
                        return true;
                    }
                    else
                    {
                        LogHelper.ShowMsg($"退料失败 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 错误信息: {wmsResponse?.msg ?? "未知错误"}");
                        LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(wmsResponse));
                        return false;
                    }
                }
                else
                {
                    string msg = $"退料HTTP请求失败 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 状态码: {response.StatusCode}, 响应: {responseContent}";
                    LogHelper.ShowMsg(msg);
                    LogHelper.SaveWebApiResLogo(AID, msg);
                    return false;
                }
            } 
            catch (Exception err)
            {
                string emptyTypeDesc = isEmpty == 0 ? "空托" : "余料";
                string errorMsg = $"退料异常 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 异常详情: {err.Message}";
                LogHelper.ShowMsg(errorMsg);
                Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {errorMsg}");
                if (AID > 0)
                {
                    LogHelper.SaveWebApiResLogo(AID, errorMsg);
                }
                return false;
            }
        }
    }
} 