using Microsoft.AspNetCore.Mvc;
using BLL.Interfaces;
using MDL.DTOs;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using System.IO;

namespace CONTROLLER.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DashboardController : ControllerBase
    {
        private readonly ILabelReplaceService _labelReplaceService;
        private readonly ILabelScanService _labelScanService;
        private readonly IArrivalHandoverFormService _arrivalHandoverFormService;
        private readonly ILogger<DashboardController> _logger;

        public DashboardController(
            ILabelReplaceService labelReplaceService,
            ILabelScanService labelScanService,
            IArrivalHandoverFormService arrivalHandoverFormService,
            ILogger<DashboardController> logger)
        {
            _labelReplaceService = labelReplaceService;
            _labelScanService = labelScanService;
            _arrivalHandoverFormService = arrivalHandoverFormService;
            _logger = logger;
        }

        /// <summary>
        /// 数据看板查询接口
        /// </summary>
        [HttpGet("query")]
        public async Task<IActionResult> GetDashboardData(
            [FromQuery] string arrivalNumber = null,
            [FromQuery] string startDate = null,
            [FromQuery] string endDate = null,
            [FromQuery] int? customerId = null,
            [FromQuery] string callback = null)
        {
            try
            {
                _logger.LogInformation("Received dashboard query request with arrivalNumber: {arrivalNumber}", arrivalNumber);

                var dashboardData = await _labelReplaceService.GetDashboardDataAsync(
                    arrivalNumber, startDate, endDate, customerId);

                var result = new
                {
                    code = 0,
                    message = "success",
                    data = dashboardData
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error retrieving dashboard data");
                var errorResult = new
                {
                    code = 1,
                    message = "An unexpected error occurred during dashboard data retrieval.",
                    errorDetails = ex.Message
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 当天扫描后未下单数量统计
        /// </summary>
        [HttpGet("today-unordered")]
        public async Task<IActionResult> GetTodayUnorderedCount([FromQuery] string callback = null)
        {
            try
            {
                _logger.LogInformation("Received request for today's unordered count");

                // 调用服务获取当天扫描后未下单数量
                var unorderedData = await _labelScanService.GetTodayUnorderedCountAsync();

                var result = new
                {
                    code = 0,
                    message = "success",
                    data = unorderedData
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error retrieving today's unordered count");
                var errorResult = new
                {
                    code = 1,
                    message = "An unexpected error occurred during unordered count retrieval.",
                    errorDetails = ex.Message
                };

                // 处理 JSONP 错误
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 导出数据看板到Excel
        /// </summary>
        [HttpGet("export")]
        public async Task<IActionResult> ExportDashboardToExcel(
            [FromQuery] string arrivalNumber = null,
            [FromQuery] string startDate = null,
            [FromQuery] string endDate = null,
            [FromQuery] int? customerId = null)
        {
            try
            {
                _logger.LogInformation("Received request to export dashboard data to Excel");

                var dashboardData = await _labelReplaceService.GetDashboardDataAsync(
                    arrivalNumber, startDate, endDate, customerId);

                var excelBytes = await GenerateExcelAsync(dashboardData);

                var fileName = $"dashboard_export_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xlsx";
                return File(excelBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error exporting dashboard data to Excel");
                return Ok(new
                {
                    code = 1,
                    message = "An unexpected error occurred during Excel export.",
                    errorDetails = ex.Message
                });
            }
        }

        /// <summary>
        /// 生成Excel文件
        /// </summary>
        private async Task<byte[]> GenerateExcelAsync(dynamic dashboardData)
        {
            using (var stream = new MemoryStream())
            {
                return stream.ToArray();
            }
        }

        /// <summary>
        /// 获取每日标签统计数据
        /// </summary>
        [HttpGet("daily-stats")]
        public async Task<IActionResult> GetDailyLabelStats(
            [FromQuery] string startDate = null,
            [FromQuery] string endDate = null,
            [FromQuery] int? customerId = null,
            [FromQuery] string callback = null
        )
        {
            try
            {
                _logger.LogInformation("Received daily label stats request. StartDate: {startDate}, EndDate: {endDate}, CustomerId: {customerId}", 
                    startDate, endDate, customerId);

                var stats = await _labelReplaceService.GetDailyLabelStatsAsync(startDate, endDate, customerId);

                var result = new
                {
                    code = 0,
                    message = "success",
                    data = stats
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error retrieving daily label stats");
                var errorResult = new
                {
                    code = 1,
                    message = "An unexpected error occurred during daily label stats retrieval.",
                    errorDetails = ex.Message
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 获取每日标签统计数据（中文版本，使用自定义SQL）
        /// </summary>
        [HttpGet("daily-stats-chinese")]
        public async Task<IActionResult> GetDailyLabelStatsChinese(
            [FromQuery] string callback = null
        )
        {
            try
            {
                _logger.LogInformation("Received daily label stats Chinese request");

                var stats = await _labelReplaceService.GetDailyLabelStatsChineseAsync();

                var result = new
                {
                    code = 0,
                    message = "success",
                    data = stats
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error retrieving daily label stats Chinese");
                var errorResult = new
                {
                    code = 1,
                    message = "An unexpected error occurred during daily label stats Chinese retrieval.",
                    errorDetails = ex.Message
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }

        /// <summary>
        /// 导出每日标签统计数据（中文版本）为Excel
        /// </summary>
        [HttpGet("daily-stats-chinese/export-excel")]
        public async Task<IActionResult> ExportDailyLabelStatsChineseToExcel()
        {
            try
            {
                _logger.LogInformation("Received request to export daily label stats Chinese to Excel");

                var stats = await _labelReplaceService.GetDailyLabelStatsChineseAsync();

                // 设置EPPlus许可证上下文（用于非商业用途）
                OfficeOpenXml.ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
                
                // 创建Excel文件
                using (var package = new OfficeOpenXml.ExcelPackage())
                {
                    var worksheet = package.Workbook.Worksheets.Add("每日标签统计");

                    // 设置表头
                    worksheet.Cells["A1"].Value = "日期";
                    worksheet.Cells["B1"].Value = "当日新增换单数";
                    worksheet.Cells["C1"].Value = "累计要换的总单数";
                    worksheet.Cells["D1"].Value = "换单失败未完结订单";
                    worksheet.Cells["E1"].Value = "当日换单失败";
                    worksheet.Cells["F1"].Value = "当日换单成功数";
                    worksheet.Cells["G1"].Value = "当日STOP数";
                    worksheet.Cells["H1"].Value = "24H换单率";
                    worksheet.Cells["I1"].Value = "当天换单完成率";
                    worksheet.Cells["J1"].Value = "当日标签推送数";
                    worksheet.Cells["K1"].Value = "当日扫描数";
                    worksheet.Cells["L1"].Value = "数据拉取时间（UTC-5）";

                    // 填充数据
                    for (int i = 0; i < stats.Count; i++)
                    {
                        var stat = stats[i];
                        int row = i + 2;

                        worksheet.Cells[$"A{row}"].Value = stat.Date;
                        worksheet.Cells[$"B{row}"].Value = stat.DailyNewReplaceCount;
                        worksheet.Cells[$"C{row}"].Value = stat.CumulativeTotalReplaceCount;
                        worksheet.Cells[$"D{row}"].Value = stat.UnfinishedFailureCount;
                        worksheet.Cells[$"E{row}"].Value = stat.DailyFailureCount;
                        worksheet.Cells[$"F{row}"].Value = stat.DailySuccessCount;
                        worksheet.Cells[$"G{row}"].Value = stat.DailyStopCount;
                        worksheet.Cells[$"H{row}"].Value = stat.Rate24Hour;
                        worksheet.Cells[$"I{row}"].Value = stat.DailyCompletionRate;
                        worksheet.Cells[$"J{row}"].Value = stat.DailyLabelPushCount;
                        worksheet.Cells[$"K{row}"].Value = stat.DailyScanCount;
                        worksheet.Cells[$"L{row}"].Value = stat.DataFetchTime.ToString("yyyy-MM-dd HH:mm:ss");
                    }

                    // 自动调整列宽
                    worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();

                    // 导出文件
                    var stream = new System.IO.MemoryStream();
                    package.SaveAs(stream);
                    stream.Position = 0;

                    var fileName = $"运维监控_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xlsx";
                    return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error exporting daily label stats Chinese to Excel");
                return Ok(new
                {
                    status = "error",
                    message = "An unexpected error occurred during export.",
                    errorDetails = ex.Message
                });
            }
        }

        [HttpGet("ops-monitor")]
        public async Task<IActionResult> GetOpsMonitorData(
            [FromQuery] string callback = null
        )
        {
            try
            {
                _logger.LogInformation("Received ops monitor data request");

                var stats = await _labelReplaceService.GetOpsMonitorDataAsync();

                var result = new
                {
                    code = 0,
                    message = "success",
                    data = stats
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(result);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error retrieving ops monitor data");
                var errorResult = new
                {
                    code = 1,
                    message = "An unexpected error occurred during ops monitor data retrieval.",
                    errorDetails = ex.Message
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonResult = System.Text.Json.JsonSerializer.Serialize(errorResult);
                    var jsonpResult = $"{callback}({jsonResult})";
                    return Content(jsonpResult, "application/javascript");
                }

                return Ok(errorResult);
            }
        }
    }
}