using BLL.Interfaces;
using MDL.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using DinkToPdf;
using System;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using CONTROLLER.Utilities;
using CONTROLLER.Extensions;
using Common.Util;

namespace CONTROLLER.Controllers
{
    [Route("api/shipping-handover")]
    [ApiController]
    public class ShippingHandoverFormController : ControllerBase
    {
        private readonly IShippingHandoverFormService _shippingHandoverFormService;
        private readonly IShippingHandoverFormBagTagService _shippingHandoverFormBagTagService;
        private readonly IBagTagService _bagTagService;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly ILogger<ShippingHandoverFormController> _logger;

        public ShippingHandoverFormController(IShippingHandoverFormService shippingHandoverFormService, IShippingHandoverFormBagTagService shippingHandoverFormBagTagService, IBagTagService bagTagService, IWebHostEnvironment hostingEnvironment, ILogger<ShippingHandoverFormController> logger)
        {
            _shippingHandoverFormService = shippingHandoverFormService;
            _shippingHandoverFormBagTagService = shippingHandoverFormBagTagService;
            _bagTagService = bagTagService;
            _hostingEnvironment = hostingEnvironment;
            _logger = logger;
        }

        [HttpGet("create")]
        public async Task<IActionResult> CreateShippingHandoverForm(
            [FromQuery] string HandoverNumber,
            [FromQuery] string Channel,
            [FromQuery] DateTime? DeliveryTime,
            [FromQuery] string? POD,
            [FromQuery] string? Remarks,
            [FromQuery] string Creator,
            [FromQuery] string TimeZone,
            [FromQuery] string callback = null)
        {
            try
            {
                var caller = HttpContext.GetCaller();
                _logger.LogInformation("[Caller: {Caller}] CreateShippingHandoverForm, HandoverNumber: {Number}, Channel: {Channel}", caller, HandoverNumber, Channel);

                var form = new ShippingHandoverFormEntity
                {
                    HandoverNumber = HandoverNumber,
                    Channel = Channel,
                    DeliveryTime = DeliveryTime,
                    POD = POD,
                    Remarks = Remarks,
                    Creator = caller,
                    TimeZone = TimeZone,
                    BigBagCount = 0, // 默认值为0
                    SmallBagCount = 0, // 默认值为0
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };

                if (string.IsNullOrEmpty(form.HandoverNumber))
                {
                    form.HandoverNumber = await _shippingHandoverFormService.GenerateShippingHandoverNumberAsync();
                }
                
                var result = await _shippingHandoverFormService.CreateShippingHandoverFormAsync(form);
                var response = new
                {
                    code = 0,
                    message = "success",
                    data = result
                };

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

                return Ok(response);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        [HttpGet("get/{id}")]
        public async Task<IActionResult> GetShippingHandoverFormById(int id, [FromQuery] string callback = null)
        {
            try
            {
                var form = await _shippingHandoverFormService.GetShippingHandoverFormByIdAsync(id);
                var transformedForm = new
                {
                    form.Id,
                    form.HandoverNumber,
                    form.BigBagCount,
                    form.SmallBagCount,
                    form.Channel,
                    DeliveryTime = form.DeliveryTime.ToTimestamp(),
                    form.POD,
                    form.Remarks,
                    form.Creator,
                    CreatedAt = form.CreatedAt.ToTimestamp(),
                    UpdatedAt = form.UpdatedAt.ToTimestamp(),
                    form.TimeZone,
                    Status = (int)form.Status
                };
                
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = transformedForm
                };

                // 处理 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)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        [HttpGet("get-by-number/{handoverNumber}")]
        public async Task<IActionResult> GetShippingHandoverFormByNumber(string handoverNumber, [FromQuery] string callback = null)
        {
            try
            {
                var form = await _shippingHandoverFormService.GetShippingHandoverFormByNumberAsync(handoverNumber);
                var transformedForm = new
                {
                    form.Id,
                    form.HandoverNumber,
                    form.BigBagCount,
                    form.SmallBagCount,
                    form.Channel,
                    DeliveryTime = form.DeliveryTime.ToTimestamp(),
                    form.POD,
                    form.Remarks,
                    form.Creator,
                    CreatedAt = form.CreatedAt.ToTimestamp(),
                    UpdatedAt = form.UpdatedAt.ToTimestamp(),
                    form.TimeZone,
                    Status = (int)form.Status
                };
                
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = transformedForm
                };

                // 处理 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)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        [HttpGet("list")]
        public async Task<IActionResult> GetShippingHandoverForms(
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string sortBy = "CreatedAt",
            [FromQuery] string sortOrder = "desc",
            [FromQuery] string handoverNumber = "",
            [FromQuery] string channel = "",
            [FromQuery] string creator = "",
            [FromQuery] DateTime? startDeliveryTime = null,
            [FromQuery] DateTime? endDeliveryTime = null,
            [FromQuery] string callback = null)
        {
            try
            {
                var (forms, totalCount) = await _shippingHandoverFormService.GetShippingHandoverFormsBatchAsync(
                    page, pageSize, sortBy, sortOrder, handoverNumber, channel, creator, 
                    startDeliveryTime, endDeliveryTime);
                
                var transformedForms = forms.ConvertAll(form => new
                {
                    form.Id,
                    form.HandoverNumber,
                    form.BigBagCount,
                    form.SmallBagCount,
                    form.Channel,
                    DeliveryTime = form.DeliveryTime.ToTimestamp(),
                    form.POD,
                    form.Remarks,
                    form.Creator,
                    CreatedAt = form.CreatedAt.ToTimestamp(),
                    UpdatedAt = form.UpdatedAt.ToTimestamp(),
                    form.TimeZone,
                    Status = (int)form.Status
                });
                
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = new
                    {
                        forms = transformedForms,
                        totalCount
                    }
                };

                // 处理 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)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        [HttpGet("update/{id}")]
        public async Task<IActionResult> UpdateShippingHandoverForm(
            int id,
            [FromQuery] DateTime? DeliveryTime,
            [FromQuery] string? Remarks,
            [FromQuery] string TimeZone,
            [FromQuery] string callback = null)
        {
            try
            {
                var form = await _shippingHandoverFormService.GetShippingHandoverFormByIdAsync(id);
                if (form == null)
                {
                    throw new Exception("出货交接单不存在");
                }
                
                form.DeliveryTime = DeliveryTime;
                form.Remarks = Remarks;
                form.TimeZone = TimeZone;
                form.UpdatedAt = DateTime.UtcNow;
                
                var result = await _shippingHandoverFormService.UpdateShippingHandoverFormAsync(form);
                var response = new
                {
                    code = 0,
                    message = "success",
                    data = result
                };

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

                return Ok(response);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        [HttpGet("delete/{id}")]
        public async Task<IActionResult> DeleteShippingHandoverForm(int id, [FromQuery] string callback = null)
        {
            try
            {
                var result = await _shippingHandoverFormService.DeleteShippingHandoverFormAsync(id);
                var response = new
                {
                    code = 0,
                    message = "success",
                    data = result
                };

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

                return Ok(response);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        [HttpGet("generate-number")]
        public async Task<IActionResult> GenerateShippingHandoverNumber([FromQuery] string channel = "GOFO", [FromQuery] string callback = null)
        {
            try
            {
                var caller = HttpContext.GetCaller();
                _logger.LogInformation("[Caller: {Caller}] GenerateShippingHandoverNumber, Channel: {Channel}", caller, channel);

                var number = await _shippingHandoverFormService.GenerateShippingHandoverNumberAsync(channel);
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = number
                };

                // 处理 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)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        [HttpGet("update-pod")]
        public async Task<IActionResult> UpdateShippingHandoverFormPOD(
            [FromQuery] string handoverNumber,
            [FromQuery] string podLinks,
            [FromQuery] string callback = null)
        {
            try
            {
                var result = await _shippingHandoverFormService.UpdateShippingHandoverFormPODAsync(handoverNumber, podLinks);
                var response = new
                {
                    code = 0,
                    message = "success",
                    data = result
                };

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

                return Ok(response);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        [HttpGet("details/{handoverNumber}")]
        public async Task<IActionResult> GetShippingHandoverFormDetails(string handoverNumber, [FromQuery] string callback = null)
        {
            try
            {
                var (handoverNumberResult, channel, bagTagCount, totalPackageCount, status) = await _shippingHandoverFormService.GetShippingHandoverFormDetailsAsync(handoverNumber);
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = new
                    {
                        handoverNumber = handoverNumberResult,
                        channel,
                        bagTagCount,
                        totalPackageCount,
                        status
                    }
                };

                // 处理 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)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = 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);
            }
        }

        public class ConfirmShippingHandoverFormRequest
        {
            [System.Text.Json.Serialization.JsonPropertyName("handoverNumber")]
            public string HandoverNumber { get; set; }
            
            [System.Text.Json.Serialization.JsonPropertyName("deliveryTime")]
            public long? DeliveryTime { get; set; }
            
            [System.Text.Json.Serialization.JsonPropertyName("pod")]
            public string Pod { get; set; }
            
            [System.Text.Json.Serialization.JsonPropertyName("callback")]
            public string? Callback { get; set; }
        }

        [HttpPost("confirm")]
        public async Task<IActionResult> ConfirmShippingHandoverForm([FromBody] ConfirmShippingHandoverFormRequest request)
        {
            try
            {
                var result = await _shippingHandoverFormService.ConfirmShippingHandoverFormAsync(request.HandoverNumber, request.DeliveryTime.ToDateTime(), request.Pod);
                var response = new
                {
                    code = 0,
                    message = "success",
                    data = result
                };

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

                return Ok(response);
            }
            catch (Exception ex)
            {
                var errorResult = new
                {
                    code = 9999,
                    message = ex.Message
                };

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

                return Ok(errorResult);
            }
        }

        [HttpGet("{bolNumber}/print")]
        public async Task<IActionResult> PrintBillOfLading(string bolNumber)
        {
            try
            {
                var caller = HttpContext.GetCaller();
                _logger.LogInformation("[Caller: {Caller}] PrintBillOfLading, BolNumber: {BolNumber}", caller, bolNumber);

                // 记录请求开始
                Console.WriteLine($"[{DateTime.Now}] PrintBillOfLading request received for BOL number: {bolNumber}");

                // 获取BOL信息
                Console.WriteLine($"[{DateTime.Now}] Getting BOL information...");
                var form = await _shippingHandoverFormService.GetShippingHandoverFormByNumberAsync(bolNumber);
                Console.WriteLine($"[{DateTime.Now}] BOL information retrieved: {(form != null ? "Found" : "Not found")}");

                string bolNumberValue = bolNumber;
                string channelValue = "GOFO";
                int bagTagCountValue = 0;

                // 如果找到BOL信息，使用实际数据
                if (form != null)
                {
                    bolNumberValue = form.HandoverNumber;
                    channelValue = form.Channel;
                    
                    // 获取BOL详情（包含袋牌数量和总包裹数）
                    var (handoverNumber, channel, bagTagCount, totalPackageCount, status) = await _shippingHandoverFormService.GetShippingHandoverFormDetailsAsync(bolNumber);
                    bagTagCountValue = bagTagCount;
                }

                // 生成条形码
                Console.WriteLine($"[{DateTime.Now}] Generating barcode...");
                var barcodeContent = GenerateBarcode(bolNumberValue);
                Console.WriteLine($"[{DateTime.Now}] Barcode generated: {barcodeContent}");

                // 生成袋牌信息表格
                var bagTagTableRows = string.Empty;
                if (form != null)
                {
                    // 获取BOL关联的袋牌列表
                    var bagTags = await _shippingHandoverFormBagTagService.GetAssociatedBagTagsAsync(form.Id);
                    
                    // 按每3个袋牌一行生成表格
                    for (int i = 0; i < bagTags.Count; i += 3)
                    {
                        var row = $"<tr>\n                        <td>{i/3 + 1}</td>";
                        
                        // 处理第一个袋牌
                        if (i < bagTags.Count)
                        {
                            var bagTag = bagTags[i];
                            var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(bagTag.TagNumber);
                            row += $"\n                        <td>{bagTag.TagNumber}</td>\n                        <td>{waybillCount}</td>";
                        } else {
                            row += $"\n                        <td></td>\n                        <td></td>";
                        }
                        
                        // 处理第二个袋牌
                        if (i + 1 < bagTags.Count)
                        {
                            var bagTag = bagTags[i + 1];
                            var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(bagTag.TagNumber);
                            row += $"\n                        <td>{bagTag.TagNumber}</td>\n                        <td>{waybillCount}</td>";
                        } else {
                            row += $"\n                        <td></td>\n                        <td></td>";
                        }
                        
                        // 处理第三个袋牌
                        if (i + 2 < bagTags.Count)
                        {
                            var bagTag = bagTags[i + 2];
                            var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(bagTag.TagNumber);
                            row += $"\n                        <td>{bagTag.TagNumber}</td>\n                        <td>{waybillCount}</td>";
                        } else {
                            row += $"\n                        <td></td>\n                        <td></td>";
                        }
                        
                        row += $"\n                    </tr>\n";
                        bagTagTableRows += row;
                    }
                }
                
                // 如果没有袋牌，生成一个空行
                if (bagTagTableRows == string.Empty)
                {
                    bagTagTableRows = "<tr>\n                        <td>1</td>\n                        <td></td>\n                        <td></td>\n                        <td></td>\n                        <td></td>\n                        <td></td>\n                        <td></td>\n                    </tr>\n";
                }

                // 使用BillOfLadingTemplate.html作为模板
                Console.WriteLine($"[{DateTime.Now}] Using BillOfLadingTemplate.html template...");
                string htmlContent = string.Empty;
                try
                {
                    // 读取HTML模板文件
                    string templatePath = Path.Combine(_hostingEnvironment.ContentRootPath, "..","BillOfLadingTemplate.html");
                    string htmlTemplate = System.IO.File.ReadAllText(templatePath);

                    // 替换模板中的变量
                    htmlTemplate = htmlTemplate.Replace("{{bolNumber}}", bolNumberValue);
                    htmlTemplate = htmlTemplate.Replace("{{channel}}", channelValue);
                    htmlTemplate = htmlTemplate.Replace("{{bagTagCount}}", bagTagCountValue.ToString());
                    htmlTemplate = htmlTemplate.Replace("{{bagTagTableRows}}", bagTagTableRows);
                    htmlTemplate = htmlTemplate.Replace("{{barcodeBase64}}", barcodeContent);

                    htmlContent = htmlTemplate;
                    Console.WriteLine($"[{DateTime.Now}] Template loaded and variables replaced successfully");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[{DateTime.Now}] Error loading template file: {ex.Message}");
                    Console.WriteLine($"[{DateTime.Now}] Exception stack trace: {ex.StackTrace}");
                    // 如果加载模板文件出错，使用默认HTML
                    htmlContent = $@"<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <title>Bill of Lading - Error</title>
    <style>
        body {{ font-family: Arial, sans-serif; padding: 20px; }}
        h1 {{ color: #333; }}
        .container {{ max-width: 800px; margin: 0 auto; }}
        .info {{ margin: 20px 0; padding: 15px; border: 1px solid #ddd; }}
        .barcode {{ margin: 20px 0; padding: 10px; background-color: #f5f5f5; }}
        table {{ border-collapse: collapse; width: 100%; margin: 20px 0; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        th {{ background-color: #f2f2f2; }}
    </style>
</head>
<body>
    <div class='container'>
        <h1>Bill of Lading - Error</h1>
        <div class='info'>
            <table>
                <tr>
                    <th>Item</th>
                    <th>Value</th>
                </tr>
                <tr>
                    <td>BOL Number</td>
                    <td>{bolNumberValue}</td>
                </tr>
                <tr>
                    <td>Channel</td>
                    <td>{channelValue}</td>
                </tr>
                <tr>
                    <td>Bag Tag Count</td>
                    <td>{bagTagCountValue}</td>
                </tr>
            </table>
        </div>
        <div class='barcode'>
            <h3>Barcode</h3>
            <p>{barcodeContent}</p>
        </div>
    </div>
</body>
</html>";
                }

                // 创建PDF文档
                Console.WriteLine($"[{DateTime.Now}] Creating PDF document...");
                var doc = new HtmlToPdfDocument()
                {
                    GlobalSettings = {
                        ColorMode = ColorMode.Color,
                        Orientation = Orientation.Portrait,
                        PaperSize = PaperKind.A4,
                        Margins = new MarginSettings { Top = 0, Bottom = 0, Left = 0, Right = 0 } // 设为0边距，让内容填充整个页面
                    },
                    Objects = {
                        new ObjectSettings() {
                            PagesCount = true,
                            HtmlContent = htmlContent,
                            WebSettings = { DefaultEncoding = "utf-8" },
                            // 禁用页眉页脚，避免占用空间
                            HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = false, Spacing = 0 },
                            FooterSettings = { FontSize = 9, Line = false, Center = "" }
                        }
                    }
                };

                // 转换HTML为PDF
                Console.WriteLine($"[{DateTime.Now}] Converting HTML to PDF...");
                byte[] pdf = null;
                try
                {
                    // 检查libwkhtmltox.dll是否存在
                    string basePath = AppDomain.CurrentDomain.BaseDirectory;
                    string libPath = Path.Combine(basePath, "libwkhtmltox.dll");
                    if (System.IO.File.Exists(libPath))
                    {
                        Console.WriteLine($"[{DateTime.Now}] libwkhtmltox.dll found at: {libPath}");
                    }
                    else
                    {
                        Console.WriteLine($"[{DateTime.Now}] libwkhtmltox.dll NOT found at: {libPath}");
                        // 检查其他可能的位置
                        string[] possiblePaths = {
                            Path.Combine(basePath, "..", "libwkhtmltox.dll"),
                            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "libwkhtmltox.dll")
                        };
                        foreach (var path in possiblePaths)
                        {
                            if (System.IO.File.Exists(path))
                            {
                                Console.WriteLine($"[{DateTime.Now}] libwkhtmltox.dll found at alternative location: {path}");
                                break;
                            }
                        }
                    }

                    var converter = PdfConverterSingleton.Instance;
                    Console.WriteLine($"[{DateTime.Now}] Converter instance created successfully");
                    pdf = converter.Convert(doc);
                    Console.WriteLine($"[{DateTime.Now}] PDF conversion completed, byte length: {pdf.Length}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[{DateTime.Now}] Error during PDF conversion: {ex.Message}");
                    Console.WriteLine($"[{DateTime.Now}] Exception stack trace: {ex.StackTrace}");
                }

                var bolFileName = $"bill_of_lading_{bolNumber}.pdf";
                Console.WriteLine($"[{DateTime.Now}] Returning PDF file: {bolFileName}");

                // 确保 pdf 不为 null
                if (pdf == null || pdf.Length == 0)
                {
                    // 如果 pdf 为 null 或空，生成一个简单的错误HTML
                    string errorHtml = $@"<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <title>Bill of Lading - Error</title>
    <style>
        body {{ font-family: Arial, sans-serif; padding: 20px; }}
        h1 {{ color: #333; }}
        .error {{ color: red; margin: 20px 0; padding: 15px; border: 1px solid red; background-color: #ffe6e6; }}
    </style>
</head>
<body>
    <h1>Bill of Lading Generation Failed</h1>
    <div class='error'>
        <p>Failed to generate PDF file. Please contact administrator for assistance.</p>
        <p>BOL Number: {bolNumber}</p>
        <p>Time: {DateTime.Now.ToString()}</p>
    </div>
</body>
</html>";
                    pdf = System.Text.Encoding.UTF8.GetBytes(errorHtml);
                }

                return File(pdf, "application/pdf", bolFileName);
            }
            catch (Exception ex)
            {
                // 记录异常
                Console.WriteLine($"[{DateTime.Now}] Exception in PrintBillOfLading: {ex.Message}");
                Console.WriteLine($"[{DateTime.Now}] Exception stack trace: {ex.StackTrace}");

                // 异常时也使用BillOfLadingTemplate.html模板
                try
                {
                    string templatePath = Path.Combine(_hostingEnvironment.ContentRootPath, "..", "src", "Views", "BillOfLadingTemplate.html");
                    string htmlTemplate = System.IO.File.ReadAllText(templatePath);

                    // 使用默认值替换模板中的变量
                    string defaultBolNumber = "ERROR_BOL";
                    string defaultChannel = "SYSTEM";
                    int defaultBagTagCount = 0;
                    string defaultBagTagTableRows = "<tr>\n                        <td>1</td>\n                        <td></td>\n                        <td></td>\n                        <td></td>\n                        <td></td>\n                        <td></td>\n                        <td></td>\n                    </tr>\n";

                    // 生成默认条形码并替换
                    var defaultBarcode = GenerateBarcode(defaultBolNumber);

                    // 替换模板中的变量
                    htmlTemplate = htmlTemplate.Replace("{{bolNumber}}", defaultBolNumber);
                    htmlTemplate = htmlTemplate.Replace("{{channel}}", defaultChannel);
                    htmlTemplate = htmlTemplate.Replace("{{bagTagCount}}", defaultBagTagCount.ToString());
                    htmlTemplate = htmlTemplate.Replace("{{bagTagTableRows}}", defaultBagTagTableRows);
                    htmlTemplate = htmlTemplate.Replace("{{barcodeBase64}}", defaultBarcode);

                    // 转换HTML为PDF
                    var doc = new HtmlToPdfDocument()
                    {
                        GlobalSettings = {
                            ColorMode = ColorMode.Color,
                            Orientation = Orientation.Portrait,
                            PaperSize = PaperKind.A4,
                            Margins = new MarginSettings { Top = 0, Bottom = 0, Left = 0, Right = 0 } // 设为0边距，让内容填充整个页面
                        },
                        Objects = {
                            new ObjectSettings() {
                                PagesCount = true,
                                HtmlContent = htmlTemplate,
                                WebSettings = { DefaultEncoding = "utf-8" },
                                // 禁用页眉页脚，避免占用空间
                                HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = false, Spacing = 0 },
                                FooterSettings = { FontSize = 9, Line = false, Center = "" }
                            }
                        }
                    };

                    var converter = PdfConverterSingleton.Instance;
                    byte[] pdf = converter.Convert(doc);

                    var bolFileName = $"bill_of_lading_error_{DateTime.Now:yyyyMMddHHmmss}.pdf";
                    return File(pdf, "application/pdf", bolFileName);
                }
                catch (Exception templateEx)
                {
                    // 如果模板也加载失败，返回空字节
                    Console.WriteLine($"[{DateTime.Now}] Error loading template in exception handler: {templateEx.Message}");
                    return File(new byte[0], "application/pdf");
                }
            }
        }

        // 生成条形码的辅助方法
        private string GenerateBarcode(string content)
        {
            return GenerateBarcodeWithZXing(content);
        }

        // 使用ZXing生成条形码的方法
        private string GenerateBarcodeWithZXing(string content)
        {
            try
            {
                // 配置条形码写入器
                var writer = new ZXing.BarcodeWriterPixelData
                {
                    Format = ZXing.BarcodeFormat.CODE_128,
                    Options = new ZXing.Common.EncodingOptions
                    {
                        Width = 180,
                        Height = 60,
                        Margin = 0
                    }
                };

                // 生成条形码像素数据
                var pixelData = writer.Write(content);

                // 创建位图
                using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
                {
                    var bitmapData = bitmap.LockBits(
                        new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height),
                        System.Drawing.Imaging.ImageLockMode.WriteOnly,
                        System.Drawing.Imaging.PixelFormat.Format32bppRgb);

                    try
                    {
                        // 复制像素数据到位图
                        System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
                    }
                    finally
                    {
                        bitmap.UnlockBits(bitmapData);
                    }

                    // 将位图保存到内存流
                    using (var stream = new System.IO.MemoryStream())
                    {
                        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                        return System.Convert.ToBase64String(stream.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error generating barcode with ZXing: {ex.Message}");
                return string.Empty;
            }
        }
    }
}