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

namespace CONTROLLER.Controllers
{
    [ApiController]
    [Route("api/order-log")]
    public class OrderLogController : ControllerBase
    {
        private readonly ILogger<OrderLogController> _logger;
        private readonly IOrderLogService _orderLogService;

        public OrderLogController(ILogger<OrderLogController> logger, IOrderLogService orderLogService)
        {
            _logger = logger;
            _orderLogService = orderLogService;
        }

        [HttpGet("query")]
        public IActionResult QueryOrderLog(
            string neutralWaybillNumber = null,
            string finalMileTrackingNumber = null,
            string sortBy = "CreatedAt",
            string sortOrder = "desc",
            string callback = null)
        {
            try
            {
                // 模拟订单日志数据
                var orderLogs = new List<OrderLog>
                {
                    new OrderLog
                    {
                        Id = 1,
                        NeutralWaybillNumber = "TEST202603261511",
                        FinalMileTrackingNumber = "1Z999AA10123456789",
                        OperationType = "Create",
                        OperationDetails = "创建订单",
                        Operator = "System",
                        CreatedAt = DateTime.Now.AddHours(-1)
                    },
                    new OrderLog
                    {
                        Id = 2,
                        NeutralWaybillNumber = "TEST202603261511",
                        FinalMileTrackingNumber = "1Z999AA10123456789",
                        OperationType = "Update",
                        OperationDetails = "更新订单状态",
                        Operator = "Admin",
                        CreatedAt = DateTime.Now.AddMinutes(-30)
                    }
                };

                // 过滤数据
                if (!string.IsNullOrEmpty(neutralWaybillNumber))
                {
                    orderLogs = orderLogs.Where(log => log.NeutralWaybillNumber == neutralWaybillNumber).ToList();
                }

                if (!string.IsNullOrEmpty(finalMileTrackingNumber))
                {
                    orderLogs = orderLogs.Where(log => log.FinalMileTrackingNumber == finalMileTrackingNumber).ToList();
                }

                // 排序
                if (sortBy == "CreatedAt")
                {
                    orderLogs = sortOrder == "desc"
                        ? orderLogs.OrderByDescending(log => log.CreatedAt).ToList()
                        : orderLogs.OrderBy(log => log.CreatedAt).ToList();
                }
                else if (sortBy == "Id")
                {
                    orderLogs = sortOrder == "desc"
                        ? orderLogs.OrderByDescending(log => log.Id).ToList()
                        : orderLogs.OrderBy(log => log.Id).ToList();
                }

                var response = new
                {
                    code = 0,
                    message = "success",
                    data = orderLogs
                };

                // 处理 JSONP 请求
                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonpResponse = $"{callback}({Newtonsoft.Json.JsonConvert.SerializeObject(response)})";
                    return Content(jsonpResponse, "application/javascript");
                }

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error querying order log");
                
                var errorResponse = new
                {
                    code = 1,
                    message = "Failed to query order log",
                    data = (object)null
                };

                if (!string.IsNullOrEmpty(callback))
                {
                    var jsonpErrorResponse = $"{callback}({Newtonsoft.Json.JsonConvert.SerializeObject(errorResponse)})";
                    return Content(jsonpErrorResponse, "application/javascript");
                }

                return BadRequest(errorResponse);
            }
        }

        [HttpGet("export")]
        public IActionResult ExportOrderLog(
            string neutralWaybillNumber = null,
            string finalMileTrackingNumber = null,
            string sortBy = "CreatedAt",
            string sortOrder = "desc")
        {
            try
            {
                // 模拟导出逻辑
                var csvContent = "Id,NeutralWaybillNumber,FinalMileTrackingNumber,OperationType,OperationDetails,Operator,CreatedAt\n";
                csvContent += "1,TEST202603261511,1Z999AA10123456789,Create,创建订单,System," + DateTime.Now.AddHours(-1).ToString() + "\n";
                csvContent += "2,TEST202603261511,1Z999AA10123456789,Update,更新订单状态,Admin," + DateTime.Now.AddMinutes(-30).ToString() + "\n";

                return File(System.Text.Encoding.UTF8.GetBytes(csvContent), "text/csv", "order-log-export.csv");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error exporting order log");
                return BadRequest(new { code = 1, message = "Failed to export order log" });
            }
        }

        /// <summary>
        /// 获取订单日志表的规格信息
        /// </summary>
        /// <returns>订单日志表的规格信息</returns>
        /// <response code="200">成功获取规格信息</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("spec")]
        public IActionResult GetOrderLogSpec()
        {
            try
            {
                _logger.LogInformation("获取订单日志表规格信息");

                // 构建订单日志表的规格信息
                var spec = new
                {
                    tableName = "order_logs",
                    description = "订单操作日志表，记录订单的各种操作历史",
                    fields = new List<object>
                    {
                        new
                        {
                            name = "Id",
                            type = "long",
                            description = "主键ID，自增",
                            isRequired = true,
                            isPrimaryKey = true
                        },
                        new
                        {
                            name = "NeutralWaybillNumber",
                            type = "string",
                            description = "中性面单单号",
                            isRequired = false,
                            maxLength = 255
                        },
                        new
                        {
                            name = "FinalMileTrackingNumber",
                            type = "string",
                            description = "尾程跟踪单号",
                            isRequired = false,
                            maxLength = 255
                        },
                        new
                        {
                            name = "OperationType",
                            type = "string",
                            description = "操作类型（换单、集包、数据更新、下单、取消订单等）",
                            isRequired = true,
                            maxLength = 100
                        },
                        new
                        {
                            name = "OperationResult",
                            type = "string",
                            description = "操作结果（成功、失败）",
                            isRequired = true,
                            maxLength = 50
                        },
                        new
                        {
                            name = "OperationDescription",
                            type = "string",
                            description = "操作说明（详细描述操作内容）",
                            isRequired = true,
                            maxLength = 500
                        },
                        new
                        {
                            name = "Operator",
                            type = "string",
                            description = "操作人",
                            isRequired = false,
                            maxLength = 100
                        },
                        new
                        {
                            name = "CreatedAt",
                            type = "DateTime",
                            description = "操作时间",
                            isRequired = true
                        }
                    },
                    indexes = new List<object>
                    {
                        new
                        {
                            name = "IX_OrderLogs_NeutralWaybillNumber",
                            columns = new List<string> { "NeutralWaybillNumber" },
                            isUnique = false,
                            description = "中性面单单号索引，用于快速查询"
                        },
                        new
                        {
                            name = "IX_OrderLogs_FinalMileTrackingNumber",
                            columns = new List<string> { "FinalMileTrackingNumber" },
                            isUnique = false,
                            description = "尾程跟踪单号索引，用于快速查询"
                        },
                        new
                        {
                            name = "IX_OrderLogs_CreatedAt",
                            columns = new List<string> { "CreatedAt" },
                            isUnique = false,
                            description = "创建时间索引，用于时间排序"
                        }
                    },
                    sampleData = new List<object>
                    {
                        new
                        {
                            Id = 1,
                            NeutralWaybillNumber = "TEST202603261511",
                            FinalMileTrackingNumber = "1Z999AA10123456789",
                            OperationType = "Create",
                            OperationResult = "成功",
                            OperationDescription = "创建订单",
                            Operator = "System",
                            CreatedAt = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss")
                        },
                        new
                        {
                            Id = 2,
                            NeutralWaybillNumber = "TEST202603261511",
                            FinalMileTrackingNumber = "1Z999AA10123456789",
                            OperationType = "Update",
                            OperationResult = "成功",
                            OperationDescription = "更新订单状态",
                            Operator = "Admin",
                            CreatedAt = DateTime.Now.AddMinutes(-30).ToString("yyyy-MM-dd HH:mm:ss")
                        }
                    },
                    apiEndpoints = new List<object>
                    {
                        new
                        {
                            path = "/api/order-log/query",
                            method = "GET",
                            description = "查询订单日志",
                            parameters = new List<object>
                            {
                                new
                                {
                                    name = "neutralWaybillNumber",
                                    type = "string",
                                    required = false,
                                    description = "中性面单单号"
                                },
                                new
                                {
                                    name = "finalMileTrackingNumber",
                                    type = "string",
                                    required = false,
                                    description = "尾程跟踪单号"
                                },
                                new
                                {
                                    name = "sortBy",
                                    type = "string",
                                    required = false,
                                    defaultValue = "CreatedAt",
                                    description = "排序字段"
                                },
                                new
                                {
                                    name = "sortOrder",
                                    type = "string",
                                    required = false,
                                    defaultValue = "desc",
                                    description = "排序顺序"
                                },
                                new
                                {
                                    name = "callback",
                                    type = "string",
                                    required = false,
                                    description = "JSONP回调函数名"
                                }
                            }
                        },
                        new
                        {
                            path = "/api/order-log/export",
                            method = "GET",
                            description = "导出订单日志为CSV",
                            parameters = new List<object>
                            {
                                new
                                {
                                    name = "neutralWaybillNumber",
                                    type = "string",
                                    required = false,
                                    description = "中性面单单号"
                                },
                                new
                                {
                                    name = "finalMileTrackingNumber",
                                    type = "string",
                                    required = false,
                                    description = "尾程跟踪单号"
                                },
                                new
                                {
                                    name = "sortBy",
                                    type = "string",
                                    required = false,
                                    defaultValue = "CreatedAt",
                                    description = "排序字段"
                                },
                                new
                                {
                                    name = "sortOrder",
                                    type = "string",
                                    required = false,
                                    defaultValue = "desc",
                                    description = "排序顺序"
                                }
                            }
                        },
                        new
                        {
                            path = "/api/order-log/spec",
                            method = "GET",
                            description = "获取订单日志表规格信息",
                            parameters = new List<object>()
                        }
                    }
                };

                return Ok(new
                {
                    code = 0,
                    message = "success",
                    data = spec
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting order log spec");
                return StatusCode(500, new
                {
                    code = 1,
                    message = "Failed to get order log spec",
                    data = (object)null
                });
            }
        }
    }

    public class OrderLog
    {
        public int Id { get; set; }
        public string? NeutralWaybillNumber { get; set; }
        public string? FinalMileTrackingNumber { get; set; }
        public string? OperationType { get; set; }
        public string? OperationDetails { get; set; }
        public string? Operator { get; set; }
        public DateTime CreatedAt { get; set; }
    }
}
