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

namespace CONTROLLER.Controllers
{
    /// <summary>
    /// Excel导入控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ExcelImportController : ControllerBase
    {
        private readonly IExcelImportService _excelImportService;
        private readonly ICustomerApiRepository _customerApiRepository;
        private readonly ICustomerRepository _customerRepository;
        private readonly ILogger<ExcelImportController> _logger;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="excelImportService">Excel导入服务</param>
        /// <param name="logger">日志记录器</param>
        public ExcelImportController(IExcelImportService excelImportService, ICustomerApiRepository customerApiRepository, ICustomerRepository customerRepository, ILogger<ExcelImportController> logger)
        {
            _excelImportService = excelImportService;
            _customerApiRepository = customerApiRepository;
            _customerRepository = customerRepository;
            _logger = logger;
        }
        
        /// <summary>
        /// 导入货物数据（中性面单、大包号、提单号）
        /// </summary>
        /// <returns>导入结果</returns>
        [HttpPost("upload")]
        public async Task<IActionResult> UploadCargoData()
        {
            try
            {
                // 从Header中获取API验证参数
                string customerCode = HttpContext.Request.Headers.TryGetValue("customer_code", out var customerCodeHeader) 
                    ? customerCodeHeader.FirstOrDefault() 
                    : string.Empty;
                string apiKey = HttpContext.Request.Headers.TryGetValue("api_key", out var apiKeyHeader) 
                    ? apiKeyHeader.FirstOrDefault() 
                    : string.Empty;
                
                // 验证API凭证
                int? customerId = null;
                if (!string.IsNullOrEmpty(customerCode) && !string.IsNullOrEmpty(apiKey))
                {
                    var customerApiInfo = await _customerApiRepository.ValidateAndGetApiCredentialsAsync(customerCode, apiKey);
                    if (customerApiInfo == null)
                    {
                        _logger.LogWarning("Invalid API credentials: CustomerCode={CustomerCode}, ApiKey={ApiKey}", 
                            customerCode, apiKey);
                        return Unauthorized(new
                        {
                            status = "error",
                            message = "Invalid API credentials. Please check your customer_code and api_key."
                        });
                    }
                    
                    // 验证CustomerId是否在customers表中存在
                    var customerExists = await _customerRepository.GetByIdAsync(customerApiInfo.CustomerId) != null;
                    if (!customerExists)
                    {
                        _logger.LogError("Customer not found: CustomerId={CustomerId}, CustomerCode={CustomerCode}", 
                            customerApiInfo.CustomerId, customerCode);
                        return StatusCode(500, new
                        {
                            status = "error",
                            message = "Internal server error: Invalid customer configuration."
                        });
                    }
                    
                    customerId = customerApiInfo.CustomerId;
                    _logger.LogInformation("API credentials validated successfully: CustomerCode={CustomerCode}, CustomerId={CustomerId}", 
                        customerCode, customerId);
                }
                
                // 检查文件是否存在
                if (!Request.HasFormContentType || !Request.Form.Files.Any())
                {
                    return BadRequest(new
                    {
                        status = "error",
                        message = "No file uploaded. Please upload an Excel file."
                    });
                }
                
                // 获取上传的文件
                var file = Request.Form.Files[0];
                if (file.Length == 0)
                {
                    return BadRequest(new
                    {
                        status = "error",
                        message = "Uploaded file is empty."
                    });
                }
                
                // 验证文件类型
                if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
                {
                    return BadRequest(new
                    {
                        status = "error",
                        message = "Invalid file format. Please upload an Excel file (.xlsx)."
                    });
                }
                
                // 读取文件流
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    stream.Position = 0;
                    
                    // 执行导入操作
                    var result = await _excelImportService.ImportCargoDataAsync(stream, customerId, customerCode);
                    
                    return Ok(new
                    {
                        status = result.Success ? "success" : "error",
                        message = result.Success ? "Data imported successfully." : "Data import failed.",
                        data = result
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error uploading cargo data");
                return StatusCode(500, new
                {
                    status = "error",
                    message = "An error occurred during data import. Please contact support."
                });
            }
        }
        
        /// <summary>
        /// 导出Excel导入模板
        /// </summary>
        /// <returns>Excel模板文件</returns>
        [HttpGet("template")]
        public async Task<IActionResult> ExportTemplate()
        {
            try
            {
                // 生成模板文件
                var templateBytes = await _excelImportService.ExportTemplateAsync();
                
                // 返回文件
                return File(templateBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 
                    "货物数据导入模板.xlsx");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error exporting Excel template");
                return StatusCode(500, new
                {
                    status = "error",
                    message = "An error occurred during template generation. Please contact support."
                });
            }
        }
        
        /// <summary>
        /// 查询货物数据
        /// </summary>
        /// <param name="searchKey">搜索关键字（中性面单/提单号/大包号）</param>
        /// <param name="pageIndex">页码（默认1）</param>
        /// <param name="pageSize">每页记录数（默认100）</param>
        /// <returns>货物数据列表</returns>
        [HttpGet("query")]
        public async Task<IActionResult> QueryCargoData(string? searchKey = null, int pageIndex = 1, int pageSize = 500)
        {
            try
            {
                // 验证分页参数
                if (pageIndex < 1) pageIndex = 1;
                if (pageSize < 1 || pageSize > 1000) pageSize = 500;
                
                // 执行查询
                var cargoDataList = await _excelImportService.QueryCargoDataAsync(searchKey, null, pageIndex, pageSize);
                
                return Ok(new
                {
                    status = "success",
                    data = cargoDataList,
                    pageIndex = pageIndex,
                    pageSize = pageSize
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error querying cargo data");
                return StatusCode(500, new
                {
                    status = "error",
                    message = "An error occurred during data query. Please contact support."
                });
            }
        }
        
        /// <summary>
        /// 根据中性面单单号查询货物数据
        /// </summary>
        /// <param name="waybillNumber">中性面单单号</param>
        /// <returns>货物数据</returns>
        [HttpGet("by-waybill/{waybillNumber}")]
        public async Task<IActionResult> GetCargoDataByWaybillNumber(string waybillNumber)
        {
            try
            {
                if (string.IsNullOrEmpty(waybillNumber))
                {
                    return BadRequest(new
                    {
                        status = "error",
                        message = "Waybill number is required."
                    });
                }
                
                // 执行查询
                var cargoData = await _excelImportService.GetCargoDataByWaybillNumberAsync(waybillNumber);
                
                if (cargoData == null)
                {
                    return NotFound(new
                    {
                        status = "error",
                        message = "Cargo data not found."
                    });
                }
                
                return Ok(new
                {
                    status = "success",
                    data = cargoData
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting cargo data by waybill number");
                return StatusCode(500, new
                {
                    status = "error",
                    message = "An error occurred during data retrieval. Please contact support."
                });
            }
        }
    }
}