using Microsoft.AspNetCore.Mvc;
using BLL.Interfaces;
using MDL.Models;
using DAL.Interfaces;
using System.Text.Json;
using System.Collections.Generic;

namespace CONTROLLER.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class TagController : ControllerBase
    {
        private readonly ITagReplacing _tagReplacing;
        private readonly ITagRepository _tagRepository;
        private readonly ILogisticsParser _logisticsParser;
        private readonly ILabelReplaceService _labelReplaceService;
        private readonly DAL.Interfaces.ICustomerApiRepository _customerApiRepository;
        private readonly Microsoft.Extensions.Logging.ILogger<TagController> _logger;

        public TagController(ITagReplacing tagReplacing, ITagRepository tagRepository, ILogisticsParser logisticsParser, ILabelReplaceService labelReplaceService, DAL.Interfaces.ICustomerApiRepository customerApiRepository, Microsoft.Extensions.Logging.ILogger<TagController> logger)
        {
            _tagReplacing = tagReplacing;
            _tagRepository = tagRepository;
            _logisticsParser = logisticsParser;
            _labelReplaceService = labelReplaceService;
            _customerApiRepository = customerApiRepository;
            _logger = logger;
        }

        [HttpPost("replace")]
        public async Task<IActionResult> Replace([FromBody] TagReplaceRequest req)
        {
            try
            {
                var text = req?.Text ?? string.Empty;
                var vars = req?.Variables ?? new Dictionary<string,string>();
                _logger.LogInformation("Received replace request. Text length: {len}", text.Length);
                var result = _tagReplacing.Replace(text, vars);
                await _tagRepository.SaveResultAsync(req?.Id ?? Guid.NewGuid().ToString(), result);

                var resp = new {
                    status = "ok",
                    timestamp = DateTime.UtcNow,
                    input = text,
                    variables = vars,
                    result = result
                };
                _logger.LogInformation("Returning result: {res}", result);
                return Ok(resp);
            }
            catch(Exception ex)
            {
                _logger.LogError(ex, "Error processing replace request");
                var err = new {
                    status = "error",
                    message = ex.Message
                };
                return Ok(err);
            }
        }

        [HttpPost("logistics-parse")]
        public async Task<IActionResult> ParseLogisticsMessage([FromBody] LogisticsRequest request)
        {
            try
            {
                if (request == null || string.IsNullOrEmpty(request.LogisticsInterface))
                {
                    return Ok(new
                    {
                        status = "error",
                        message = "Logistics interface message is required"
                    });
                }

                _logger.LogInformation("Received logistics parse request. RequestType: {type}, Message length: {len}", 
                    request.RequestType, request.LogisticsInterface.Length);

                // 验证物流报文
                bool isValid = _logisticsParser.ValidateLogisticsMessage(request.LogisticsInterface, request.RequestType ?? string.Empty);
                if (!isValid)
                {
                    return Ok(new
                    {
                        status = "error",
                        message = "Invalid logistics message format"
                    });
                }

                // 解析物流报文
                var parsedData = _logisticsParser.ParseLogisticsMessage(request);

                // 保存解析结果（如果需要）
                await _tagRepository.SaveResultAsync(
                    request.Id ?? Guid.NewGuid().ToString(), 
                    JsonSerializer.Serialize(parsedData));

                var response = new
                {
                    status = "ok",
                    timestamp = DateTime.UtcNow,
                    requestId = request.Id ?? Guid.NewGuid().ToString(),
                    requestType = request.RequestType,
                    parsedData = parsedData
                };

                _logger.LogInformation("Logistics message parsed successfully. Extracted {count} fields", parsedData.Count);
                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing logistics parse request");
                return Ok(new
                {
                    status = "error",
                    message = ex.Message
                });
            }
        }

        [HttpPost("label-replace")]
        public async Task<IActionResult> LabelReplace([FromBody] LabelReplaceMessage request)
        {
            try
            {
                // 记录所有接收到的headers，便于排查生产环境问题
                var headersLog = string.Join(", ", HttpContext.Request.Headers.Select(h => $"{h.Key}: {string.Join(';', h.Value.ToArray())}"));
                _logger.LogWarning("Received all headers: {Headers}", headersLog);
                
                // 从Header中获取API验证参数
                string customerCode = HttpContext.Request.Headers.TryGetValue("customerCode", out var customerCodeHeader) 
                    ? customerCodeHeader.FirstOrDefault() 
                    : string.Empty;
                string apiKey = HttpContext.Request.Headers.TryGetValue("apiKey", out var apiKeyHeader) 
                    ? apiKeyHeader.FirstOrDefault() 
                    : string.Empty;

                // 验证API凭证不能为空
                if (string.IsNullOrEmpty(customerCode) || string.IsNullOrEmpty(apiKey))
                {
                    _logger.LogWarning("Missing API credentials. CustomerCode: {customerCode}, ApiKey: {apiKey}", 
                        customerCode, apiKey);
                    return Ok(new
                    {
                        status = "error",
                        message = "API credentials are required."
                    });
                }

                // 记录请求信息
                _logger.LogInformation("Received label replace request. NeutralWaybillNumber: {number}, CustomerCode: {customerCode}", 
                    request?.NeutralWaybillNumber, customerCode);

                // 调用标签替换服务处理请求
                var result = await _labelReplaceService.ProcessLabelReplaceAsync(request, customerCode, apiKey);

                // 无论结果如何，都返回200状态码
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing label replace request");
                return Ok(new
                {
                    status = "error",
                    message = "An unexpected error occurred.",
                    errorDetails = ex.Message
                });
            }
        }

        [HttpGet("order-import")]
        public async Task<IActionResult> OrderImport([FromQuery] string data, [FromQuery] string customerCode, [FromQuery] string apiKey)
        {
            try
            {
                // 记录所有接收到的headers，便于排查生产环境问题
                var headersLog = string.Join(", ", HttpContext.Request.Headers.Select(h => $"{h.Key}: {string.Join(';', h.Value.ToArray())}"));
                _logger.LogWarning("Received all headers: {Headers}", headersLog);
                
                // 验证API凭证不能为空
                if (string.IsNullOrEmpty(customerCode) || string.IsNullOrEmpty(apiKey))
                {
                    _logger.LogWarning("Missing API credentials. CustomerCode: {customerCode}, ApiKey: {apiKey}", 
                        customerCode, apiKey);
                    return CreateJsonpResponse(new
                    {
                        status = "error",
                        message = "API credentials are required."
                    });
                }

                // 验证数据参数
                if (string.IsNullOrEmpty(data))
                {
                    _logger.LogWarning("Missing data parameter in import request");
                    return CreateJsonpResponse(new
                    {
                        status = "error",
                        message = "No data provided for import."
                    });
                }

                // 解析JSON数据
                OrderImportRequest request;
                try
                {
                    request = System.Text.Json.JsonSerializer.Deserialize<OrderImportRequest>(data);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error deserializing order import data");
                    return CreateJsonpResponse(new
                    {
                        status = "error",
                        message = "Invalid data format. Please check your input."
                    });
                }

                // 记录请求信息
                _logger.LogInformation("Received order import request. Order count: {count}, CustomerCode: {customerCode}", 
                    request?.Orders?.Count ?? 0, customerCode);

                // 验证请求参数
                if (request == null || request.Orders == null || request.Orders.Count == 0)
                {
                    _logger.LogWarning("Empty order list in import request");
                    return CreateJsonpResponse(new
                    {
                        status = "error",
                        message = "No orders provided for import."
                    });
                }

                // 处理每个订单
                var results = new List<OrderImportResultItem>();
                int successCount = 0;
                int failedCount = 0;

                foreach (var order in request.Orders)
                {
                    var resultItem = new OrderImportResultItem
                    {
                        BillOfLadingNumber = order.BillOfLadingNumber,
                        MasterPackageNumber = order.MasterPackageNumber,
                        NeutralWaybillNumber = order.NeutralWaybillNumber,
                        FinalMileTrackingNumber = order.FinalMileTrackingNumber,
                        Label = order.Label
                    };

                    try
                    {
                        // 验证订单必填字段
                        if (string.IsNullOrEmpty(order.NeutralWaybillNumber))
                        {
                            resultItem.Status = "error";
                            resultItem.Message = "Neutral waybill number is required";
                            failedCount++;
                        }
                        else
                        {
                            // 构建标签替换请求
                            var labelReplaceRequest = new LabelReplaceMessage
                            {
                                BillOfLadingNumber = order.BillOfLadingNumber,
                                MasterPackageNumber = order.MasterPackageNumber,
                                NeutralWaybillNumber = order.NeutralWaybillNumber,
                                FinalMileTrackingNumber = order.FinalMileTrackingNumber,
                                Label = order.Label,
                                ReplaceStatus = order.ReplaceStatus ?? "Y"
                            };

                            // 调用标签替换服务处理请求
                            var processResult = await _labelReplaceService.ProcessLabelReplaceAsync(labelReplaceRequest, customerCode, apiKey);

                            resultItem.Status = processResult.Status;
                            resultItem.Message = processResult.Message;
                            resultItem.LabelReplaced = processResult.LabelReplaced;

                            if (processResult.Status == "ok")
                            {
                                successCount++;
                            }
                            else
                            {
                                failedCount++;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        resultItem.Status = "error";
                        resultItem.Message = ex.Message;
                        failedCount++;
                        _logger.LogError(ex, "Error processing order import for neutral waybill: {number}", order.NeutralWaybillNumber);
                    }

                    results.Add(resultItem);
                }

                // 构建响应
                var response = new OrderImportResult
                {
                    Status = "ok",
                    Timestamp = DateTime.UtcNow,
                    SuccessCount = successCount,
                    FailedCount = failedCount,
                    TotalCount = request.Orders.Count,
                    Results = results
                };

                return CreateJsonpResponse(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing order import request");
                
                return CreateJsonpResponse(new
                {
                    status = "error",
                    message = "An unexpected error occurred.",
                    errorDetails = ex.Message
                });
            }
        }

        // 创建JSONP响应
        private IActionResult CreateJsonpResponse(object data)
        {
            string callback = HttpContext.Request.Query.TryGetValue("callback", out var callbackValue) ? callbackValue.FirstOrDefault() : null;
            if (!string.IsNullOrEmpty(callback))
            {
                // JSONP响应
                var jsonResponse = System.Text.Json.JsonSerializer.Serialize(data);
                return Content($"{callback}({jsonResponse});", "application/javascript");
            }

            // 正常JSON响应
            return Ok(data);
        }

        [HttpGet("customer-api")]
        public async Task<IActionResult> GetCustomerApi([FromQuery] int customerId)
        {
            try
            {
                // 调用客户API仓库获取API信息
                var customerApiList = await _customerApiRepository.GetByCustomerIdAsync(customerId);
                
                if (customerApiList == null || customerApiList.Count == 0)
                {
                    _logger.LogWarning("Customer API info not found for CustomerId: {customerId}", customerId);
                    return CreateJsonpResponse(new
                    {
                        status = "error",
                        message = "Customer API information not found"
                    });
                }
                
                // 选择第一个有效（启用且未过期）的API密钥
                var now = DateTime.UtcNow;
                var validApiInfo = customerApiList.FirstOrDefault(api => 
                    api.Status == "Y" && (api.ExpireDate == null || api.ExpireDate > now));
                
                if (validApiInfo == null)
                {
                    _logger.LogWarning("No valid API key found for CustomerId: {customerId}", customerId);
                    return CreateJsonpResponse(new
                    {
                        status = "error",
                        message = "No valid API key found"
                    });
                }
                
                return CreateJsonpResponse(new
                {
                    status = "ok",
                    data = new
                    {
                        CustomerId = validApiInfo.CustomerId,
                        ApiKey = validApiInfo.ApiKey
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting customer API info for CustomerId: {customerId}", customerId);
                return CreateJsonpResponse(new
                {
                    status = "error",
                    message = "An unexpected error occurred",
                    errorDetails = ex.Message
                });
            }
        }


    }
}