using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BLL.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CONTROLLER.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class MetricsController : ControllerBase
    {
        private readonly IMetricsCalculationService _metricsService;
        private readonly ILogger<MetricsController> _logger;

        public MetricsController(IMetricsCalculationService metricsService, ILogger<MetricsController> logger)
        {
            _metricsService = metricsService;
            _logger = logger;
        }

        /// <summary>
        /// 获取指定交接单的标签率
        /// </summary>
        /// <param name="handoverNumber">交接单号</param>
        /// <returns>标签率信息</returns>
        [HttpGet("label-rate")]
        public async Task<IActionResult> GetLabelRate([FromQuery] string handoverNumber)
        {
            if (string.IsNullOrWhiteSpace(handoverNumber))
            {
                return BadRequest(new { error = "handoverNumber is required" });
            }

            try
            {
                var labelRate = await _metricsService.GetLabelRateAsync(handoverNumber);
                return Ok(new { data = labelRate, success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting label rate for handover: {handoverNumber}", handoverNumber);
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取指定订单的考核指标
        /// </summary>
        /// <param name="neutralWaybillNumber">中性面单号</param>
        /// <returns>订单指标信息</returns>
        [HttpGet("order-assessment")]
        public async Task<IActionResult> GetOrderAssessmentMetrics([FromQuery] string neutralWaybillNumber)
        {
            if (string.IsNullOrWhiteSpace(neutralWaybillNumber))
            {
                return BadRequest(new { error = "neutralWaybillNumber is required" });
            }

            try
            {
                var metrics = await _metricsService.GetOrderMetricsAsync(neutralWaybillNumber);
                return Ok(new { data = metrics, success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting order metrics for: {waybillNumber}", neutralWaybillNumber);
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取每日统计摘要
        /// </summary>
        /// <param name="date">日期（格式：yyyy-MM-dd），不传则使用当前日期</param>
        /// <returns>每日统计数据</returns>
        [HttpGet("daily-summary")]
        public async Task<IActionResult> GetDailySummary([FromQuery] string date = null)
        {
            try
            {
                DateTime targetDate;
                if (string.IsNullOrWhiteSpace(date))
                {
                    targetDate = _metricsService.GetUtc5Today();
                }
                else
                {
                    if (!DateTime.TryParse(date, out targetDate))
                    {
                        return BadRequest(new { error = "Invalid date format. Use yyyy-MM-dd" });
                    }
                    targetDate = targetDate.Date;
                }

                var summary = await _metricsService.GetDailySummaryAsync(targetDate);
                return Ok(new { data = summary, success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting daily summary for date: {date}", date);
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取指定日期范围的每日统计
        /// </summary>
        /// <param name="startDate">开始日期（格式：yyyy-MM-dd）</param>
        /// <param name="endDate">结束日期（格式：yyyy-MM-dd）</param>
        /// <returns>每日统计数据列表</returns>
        [HttpGet("daily-summaries")]
        public async Task<IActionResult> GetDailySummaries([FromQuery] string startDate, [FromQuery] string endDate)
        {
            if (string.IsNullOrWhiteSpace(startDate) || string.IsNullOrWhiteSpace(endDate))
            {
                return BadRequest(new { error = "startDate and endDate are required" });
            }

            try
            {
                if (!DateTime.TryParse(startDate, out var start) || !DateTime.TryParse(endDate, out var end))
                {
                    return BadRequest(new { error = "Invalid date format. Use yyyy-MM-dd" });
                }

                if (start.Date > end.Date)
                {
                    return BadRequest(new { error = "startDate cannot be after endDate" });
                }

                var summaries = await _metricsService.GetDailySummariesAsync(start.Date, end.Date);
                return Ok(new { data = summaries, success = true, count = summaries.Count });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting daily summaries from {startDate} to {endDate}", startDate, endDate);
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }

        /// <summary>
        /// 批量获取订单指标
        /// </summary>
        /// <param name="request">包含中性面单号列表的请求</param>
        /// <returns>订单指标列表</returns>
        [HttpPost("batch-order-metrics")]
        public async Task<IActionResult> GetBatchOrderMetrics([FromBody] BatchMetricsRequest request)
        {
            if (request?.NeutralWaybillNumbers == null || request.NeutralWaybillNumbers.Count == 0)
            {
                return BadRequest(new { error = "NeutralWaybillNumbers list is required and cannot be empty" });
            }

            try
            {
                var metrics = await _metricsService.GetBatchOrderMetricsAsync(request.NeutralWaybillNumbers);
                return Ok(new { data = metrics, success = true, count = metrics.Count });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting batch order metrics");
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }

        /// <summary>
        /// 重新计算交接单的标签率
        /// </summary>
        /// <param name="request">包含交接单号的请求</param>
        /// <returns>操作结果</returns>
        [HttpPost("recalculate-label-rate")]
        public async Task<IActionResult> RecalculateLabelRate([FromBody] RecalculateLabelRateRequest request)
        {
            if (string.IsNullOrWhiteSpace(request?.HandoverNumber))
            {
                return BadRequest(new { error = "HandoverNumber is required" });
            }

            try
            {
                var result = await _metricsService.RecalculateAndCacheLabelRateAsync(request.HandoverNumber);
                return Ok(new { data = new { success = result }, success = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error recalculating label rate for: {handoverNumber}", request.HandoverNumber);
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取24小时完成率
        /// </summary>
        /// <param name="date">日期（格式：yyyy-MM-dd），不传则使用当前日期</param>
        /// <returns>24小时完成率百分比</returns>
        [HttpGet("24h-completion-rate")]
        public async Task<IActionResult> Get24HCompletionRate([FromQuery] string date = null)
        {
            try
            {
                DateTime targetDate;
                if (string.IsNullOrWhiteSpace(date))
                {
                    targetDate = _metricsService.GetUtc5Today();
                }
                else
                {
                    if (!DateTime.TryParse(date, out targetDate))
                    {
                        return BadRequest(new { error = "Invalid date format. Use yyyy-MM-dd" });
                    }
                    targetDate = targetDate.Date;
                }

                var rate = await _metricsService.Calculate24HCompletionRateAsync(targetDate);
                return Ok(new { data = new { date = targetDate.ToString("yyyy-MM-dd"), rate = $"{rate:F2}%" }, success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting 24H completion rate for date: {date}", date);
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取当天换单完成率
        /// </summary>
        /// <param name="date">日期（格式：yyyy-MM-dd），不传则使用当前日期</param>
        /// <returns>当天换单完成率百分比</returns>
        [HttpGet("daily-completion-rate")]
        public async Task<IActionResult> GetDailyCompletionRate([FromQuery] string date = null)
        {
            try
            {
                DateTime targetDate;
                if (string.IsNullOrWhiteSpace(date))
                {
                    targetDate = _metricsService.GetUtc5Today();
                }
                else
                {
                    if (!DateTime.TryParse(date, out targetDate))
                    {
                        return BadRequest(new { error = "Invalid date format. Use yyyy-MM-dd" });
                    }
                    targetDate = targetDate.Date;
                }

                var rate = await _metricsService.CalculateDailyCompletionRateAsync(targetDate);
                return Ok(new { data = new { date = targetDate.ToString("yyyy-MM-dd"), rate = $"{rate:F2}%" }, success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting daily completion rate for date: {date}", date);
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取日汇总仪表盘完整数据（一键查询所有关键指标）
        /// </summary>
        /// <param name="date">日期（格式：yyyy-MM-dd），不传则使用当前日期</param>
        /// <param name="callback">JSONP回调函数名</param>
        /// <returns>完整的日汇总指标数据</returns>
        [HttpGet("daily-dashboard")]
        public async Task<IActionResult> GetDailyDashboard([FromQuery] string date = null, [FromQuery] string callback = null)
        {
            try
            {
                DateTime targetDate;
                if (string.IsNullOrWhiteSpace(date))
                {
                    targetDate = _metricsService.GetUtc5Today();
                }
                else
                {
                    if (!DateTime.TryParse(date, out targetDate))
                    {
                        return BadRequest(new { error = "Invalid date format. Use yyyy-MM-dd" });
                    }
                    targetDate = targetDate.Date;
                }

                var summary = await _metricsService.GetDailySummaryAsync(targetDate);
                var dailyCompletionRate = await _metricsService.CalculateDailyCompletionRateAsync(targetDate);
                var rate24Hour = await _metricsService.Calculate24HCompletionRateAsync(targetDate);

                var dashboardData = new
                {
                    date = targetDate.ToString("yyyy-MM-dd"),
                    summary = new
                    {
                        dailyNewReplaceCount = summary?.DailyNewReplaceCount ?? 0,
                        dailyShouldReplaceCount = summary?.DailyShouldReplaceCount ?? 0,
                        dailySuccessCount = summary?.DailySuccessCount ?? 0,
                        dailyCompletionRate = $"{dailyCompletionRate:F2}%",
                        rate24Hour = $"{rate24Hour:F2}%"
                    },
                    breakdown = new
                    {
                        beforeNoon = new
                        {
                            arrived = summary?.BeforeNoonArrivedCount ?? 0,
                            passed = summary?.BeforeNoonPassedCount ?? 0,
                            rate = summary?.BeforeNoonArrivedCount > 0 
                                ? $"{((summary.BeforeNoonPassedCount / (double)summary.BeforeNoonArrivedCount) * 100):F2}%"
                                : "0%"
                        },
                        afternoon = new
                        {
                            arrived = summary?.AfternoonArrivedCount ?? 0,
                            passed = summary?.AfternoonPassedCount ?? 0,
                            rate = summary?.AfternoonArrivedCount > 0 
                                ? $"{((summary.AfternoonPassedCount / (double)summary.AfternoonArrivedCount) * 100):F2}%"
                                : "0%"
                        }
                    },
                    details = new
                    {
                        cumulativeTotal = summary?.CumulativeTotalReplaceCount ?? 0,
                        dailyStop = summary?.DailyStopCount ?? 0,
                        dailyLabelPush = summary?.DailyLabelPushCount ?? 0,
                        dailyScanCount = summary?.DailyScanCount ?? 0,
                        dailyFailure = summary?.DailyFailureCount ?? 0
                    }
                };

                // 支持JSONP跨域请求
                if (!string.IsNullOrWhiteSpace(callback))
                {
                    // 验证回调函数名的合法性（只允许字母、数字、下划线、$）
                    if (System.Text.RegularExpressions.Regex.IsMatch(callback, @"^[a-zA-Z_$][a-zA-Z0-9_$]*$"))
                    {
                        var jsonResult = System.Text.Json.JsonSerializer.Serialize(new { data = dashboardData, success = true });
                        return Content($"{callback}({jsonResult});", "application/javascript");
                    }
                    else
                    {
                        return BadRequest(new { error = "Invalid callback function name" });
                    }
                }

                return Ok(new { data = dashboardData, success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting daily dashboard data for date: {date}", date);
                return StatusCode(500, new { error = "Internal server error", message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 批量请求DTO
    /// </summary>
    public class BatchMetricsRequest
    {
        public List<string> NeutralWaybillNumbers { get; set; }
    }

    /// <summary>
    /// 重新计算标签率请求DTO
    /// </summary>
    public class RecalculateLabelRateRequest
    {
        public string HandoverNumber { get; set; }
    }
}
