using BLL.Interfaces;
using DinkToPdf;
using MDL.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Drawing;
using ZXing;
using ZXing.Common;
using ZXing.QrCode.Internal;
using CONTROLLER.Utilities;
using CONTROLLER.Extensions;
using System.IO;
using System;
using Serilog;
using Common.Util;

public class RemoveWaybillRequest
{
    public string TagNumber { get; set; }
    public string FinalMileTrackingNumber { get; set; }
}

namespace CONTROLLER.Controllers
{
    [Route("api/bagtag")]
    [ApiController]
    public class BagTagController : ControllerBase
    {
        private readonly IBagTagService _bagTagService;
        private readonly ITagTemplateService _tagTemplateService;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly ILogger<BagTagController> _logger;

        public BagTagController(IBagTagService bagTagService, ITagTemplateService tagTemplateService, IWebHostEnvironment hostingEnvironment, ILogger<BagTagController> logger)
        {
            _bagTagService = bagTagService;
            _tagTemplateService = tagTemplateService;
            _hostingEnvironment = hostingEnvironment;
            _logger = logger;
        }

        [HttpPost("generate")]
        public async Task<IActionResult> GenerateBagTags([FromBody] GenerateBagTagsRequest request)
        {
            try
            {
                var caller = HttpContext.GetCaller();
                _logger.LogInformation("[Caller: {Caller}] GenerateBagTags, Channel: {Channel}, Count: {Count}", caller, request.ChannelName, request.Count);
                var generatedTags = await _bagTagService.GenerateBagTagsAsync(request.ChannelName, request.Count, caller);
                return Ok(new
                {
                    code = 0,
                    message = "success",
                    data = generatedTags
                });
            }
            catch (System.Exception ex)
            {
                return Ok(new
                {
                    code = 9999,
                    message = ex.Message
                });
            }
        }

        [HttpPost("open")]
        public async Task<IActionResult> OpenBagTag([FromBody] OpenBagTagRequest request)
        {
            try
            {
                var result = await _bagTagService.OpenBagTagAsync(request.TagNumber);
                if (result)
                {
                    // 获取袋牌内小包数量
                    var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(request.TagNumber);
                    return Ok(new
                    {
                        code = 0,
                        message = "Bag tag opened successfully",
                        data = new
                        {
                            waybillCount = waybillCount
                        }
                    });
                }
                else
                {
                    return Ok(new
                    {
                        code = 1001,
                        message = "Failed to open bag tag. It may not exist, already opened, or closed.",
                        data = new {}
                    });
                }
            }
            catch (System.Exception ex)
            {
                return Ok(new
                {
                    code = 9999,
                    message = ex.Message,
                    data = new {}
                });
            }
        }

        [HttpPost("close")]
        public async Task<IActionResult> CloseBagTag([FromBody] CloseBagTagRequest request)
        {
            try
            {
                var result = await _bagTagService.CloseBagTagAsync(request.TagNumber);
                if (result)
                {
                    // 获取袋牌内小包数量
                    var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(request.TagNumber);
                    return Ok(new
                    {
                        code = 0,
                        message = "Bag tag closed successfully",
                        data = new
                        {
                            waybillCount = waybillCount
                        }
                    });
                }
                else
                {
                    return Ok(new
                    {
                        code = 1002,
                        message = "Failed to close bag tag. It may not exist or already closed.",
                        data = new {}
                    });
                }
            }
            catch (System.Exception ex)
            {
                return Ok(new
                {
                    code = 9999,
                    message = ex.Message,
                    data = new {}
                });
            }
        }

        [HttpPost("associate-waybill")]
        public async Task<IActionResult> AssociateWaybill([FromBody] AssociateWaybillRequest request)
        {
            try
            {
                // 如果Creator为空，自动设置为"system"
                var creator = /*string.IsNullOrEmpty(request.Creator) ? "system" : request.Creator*/"system";
                var (success, errorCode, errorMessage) = await _bagTagService.AssociateWaybillAsync(request.TagNumber, request.FinalMileTrackingNumber, creator);
                if (success)
                {
                    // 获取袋牌内小包数量
                    var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(request.TagNumber);
                    return Ok(new
                    {
                        code = 0,
                        message = "Final mile tracking number associated successfully",
                        data = new
                        {
                            waybillCount = waybillCount
                        }
                    });
                }
                else
                {
                    return Ok(new
                    {
                        code = errorCode,
                        message = errorMessage,
                        data = new {}
                    });
                }
            }
            catch (System.Exception ex)
            {
                return Ok(new
                {
                    code = 9999,
                    message = ex.Message,
                    data = new {}
                });
            }
        }

        [HttpGet("{tagNumber}")]
        public async Task<IActionResult> GetBagTag(string tagNumber, [FromQuery] string callback = null)
        {
            try
            {
                var tag = await _bagTagService.GetBagTagAsync(tagNumber);
                if (tag != null)
                {
                    // 获取关联的小包数量
                    var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(tagNumber);
                    
                    // 将waybillCount添加到tag对象中
                    var tagWithCount = new
                    {
                        tag.Id,
                        tag.TagNumber,
                        tag.ChannelName,
                        tag.Status,
                        tag.Creator,
                        createdAt = tag.CreatedAt.ToTimestamp(),
                        openedAt = tag.OpenedAt.ToTimestamp(),
                        closedAt = tag.ClosedAt.ToTimestamp(),
                        waybillCount
                    };
                    
                    var result = new
                    {
                        code = 0,
                        message = "success",
                        data = tagWithCount
                    };

                    // 处理 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);
                }
                else
                {
                    var errorResult = new
                    {
                        code = 1004,
                        message = "Bag tag not found"
                    };

                    // 处理 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);
                }
            }
            catch (System.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("{tagNumber}/waybill-count")]
        public async Task<IActionResult> GetWaybillCount(string tagNumber, [FromQuery] string callback = null)
        {
            try
            {
                var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(tagNumber);
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = new
                    {
                        tagNumber,
                        waybillCount
                    }
                };

                // 处理 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 (System.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);
            }
        }

        [HttpPost("remove-waybill")]
        public async Task<IActionResult> RemoveWaybill([FromBody] RemoveWaybillRequest request, [FromQuery] string callback = null)
        {
            try
            {
                var (success, errorCode, errorMessage) = await _bagTagService.RemoveWaybillAssociationAsync(request.TagNumber, request.FinalMileTrackingNumber);
                if (success)
                {
                    var result = new
                    {
                        code = 0,
                        message = "Waybill removed from bag tag successfully"
                    };

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

                    // 处理 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);
                }
            }
            catch (System.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("{tagNumber}/waybills")]
        public async Task<IActionResult> GetWaybills(string tagNumber, [FromQuery] string callback = null)
        {
            try
            {
                Log.Information("Getting waybills for tag number: {tagNumber}", tagNumber);
                var startTime = DateTime.UtcNow;
                
                var waybills = await _bagTagService.GetWaybillsByTagNumberAsync(tagNumber);
                
                var endTime = DateTime.UtcNow;
                Log.Information("Got {count} waybills in {duration}ms for tag number: {tagNumber}", waybills.Count, (endTime - startTime).TotalMilliseconds, tagNumber);
                
                var result = new
                {
                    code = 0,
                    message = "success",
                    data = waybills
                };

                // 处理 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 (System.Exception ex)
            {
                Log.Error(ex, "Error getting waybills for tag number: {tagNumber}", tagNumber);
                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("{tagNumber}/print")]
        public async Task<IActionResult> PrintBagTag(string tagNumber, [FromQuery] string? bagTagTemplate = null)
        {
            try
            {
                var caller = HttpContext.GetCaller();
                _logger.LogInformation("[Caller: {Caller}] PrintBagTag, TagNumber: {TagNumber}", caller, tagNumber);

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

                // 获取袋牌信息
                Console.WriteLine($"[{DateTime.Now}] Getting bag tag information...");
                var bagTag = await _bagTagService.GetBagTagAsync(tagNumber);
                Console.WriteLine($"[{DateTime.Now}] Bag tag information retrieved: {(bagTag != null ? "Found" : "Not found")}");

                string tagNumberValue = tagNumber;
                string channelValue = "UPS";
                string statusValue = "Generated";
                string packageCountValue = "0";
                string createdAtValue = System.DateTime.Now.ToString();

                // 如果找到袋牌信息，使用实际数据
                if (bagTag != null)
                {
                    tagNumberValue = bagTag.TagNumber;
                    channelValue = bagTag.ChannelName;
                    statusValue = bagTag.Status;
                    createdAtValue = bagTag.CreatedAt.ToString();

                    // 获取关联的包裹数量
                    Console.WriteLine($"[{DateTime.Now}] Getting waybills for tag number: {tagNumber}");
                    var waybills = await _bagTagService.GetWaybillsByTagNumberAsync(tagNumber);
                    Console.WriteLine($"[{DateTime.Now}] Waybills retrieved: {waybills.Count}");
                    packageCountValue = waybills.Count.ToString();
                }

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

                // 从数据库中获取BAG类型的标签模板
                //Console.WriteLine($"[{DateTime.Now}] Getting BAG template from database...");
                //var template = await _tagTemplateService.GetTemplateByTypeAsync("BAG");
                //Console.WriteLine($"[{DateTime.Now}] Template retrieved: {(template != null ? "Found" : "Not found")}");

                string htmlContent = string.Empty;

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

                    // 替换模板中的硬编码值为实际的袋牌数据
                    htmlTemplate = htmlTemplate.Replace("TEST202602021626280001", tagNumberValue);
                    htmlTemplate = htmlTemplate.Replace("TEST", channelValue);
                    htmlTemplate = htmlTemplate.Replace("Opened", statusValue);
                    htmlTemplate = htmlTemplate.Replace("5", packageCountValue.ToString());
                    htmlTemplate = htmlTemplate.Replace("2026-02-02 16:26:28", createdAtValue.ToString());
                    
                    // 替换模板中的条形码为base64编码的图片
                    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>袋牌标签</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>袋牌标签</h1>
        <div class='info'>
            <table>
                <tr>
                    <th>项目</th>
                    <th>值</th>
                </tr>
                <tr>
                    <td>标签号</td>
                    <td>{tagNumberValue}</td>
                </tr>
                <tr>
                    <td>渠道</td>
                    <td>{channelValue}</td>
                </tr>
                <tr>
                    <td>状态</td>
                    <td>{statusValue}</td>
                </tr>
                <tr>
                    <td>包裹数量</td>
                    <td>{packageCountValue}</td>
                </tr>
                <tr>
                    <td>创建时间</td>
                    <td>{createdAtValue}</td>
                </tr>
            </table>
        </div>
        <div class='barcode'>
            <h3>条形码</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.JapanesePostcard,
                PaperSize =new PechkinPaperSize("100","150"),
                Margins = new MarginSettings { Top = 20 } // 设置边距等选项
            },
                    Objects = {
                new ObjectSettings() {
                    PagesCount = true,
                    HtmlContent = htmlContent,
                    WebSettings = { DefaultEncoding = "utf-8" }
                }
            }
                };
                //var doc = new HtmlToPdfDocument()
                //{
                //    GlobalSettings = {
                //        ColorMode = DinkToPdf.ColorMode.Color,
                //        Orientation = DinkToPdf.Orientation.Landscape,
                //        PaperSize = DinkToPdf.PaperKind.A4Plus,
                //        Margins = {
                //            Top = 10,
                //            Bottom = 10,
                //            Left = 10,
                //            Right = 10
                //        }
                //    },
                //    Objects = {
                //        new ObjectSettings() {
                //            PagesCount = true,
                //            HtmlContent = htmlContent,
                //            WebSettings = { 
                //                DefaultEncoding = "utf-8",
                //                EnableJavascript = true,
                //                // 允许加载外部资源
                //                LoadImages = true,
                //                PrintMediaType = true
                //            },
                //            // 禁用头部，避免占用空间导致内容偏移
                //            HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = false, Spacing = 0 }
                //        }
                //    }
                //};

                // 转换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}");
                    Log.Information(ex.Message);
                    Log.Information(ex.StackTrace);
                }

                var bagTagFileName = $"bag_tag_{tagNumber}.pdf";
                Console.WriteLine($"[{DateTime.Now}] Returning PDF file: {bagTagFileName}");

                // 确保 pdf 不为 null
                if (pdf == null || pdf.Length == 0)
                {
                    // 如果 pdf 为 null 或空，生成一个简单的错误HTML
                    string errorHtml = $@"<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <title>袋牌标签 - 错误</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>袋牌标签生成失败</h1>
    <div class='error'>
        <p>无法生成PDF文件。请联系管理员获取帮助。</p>
        <p>标签号: {tagNumber}</p>
        <p>时间: {DateTime.Now.ToString()}</p>
    </div>
</body>
</html>";
                    pdf = System.Text.Encoding.UTF8.GetBytes(errorHtml);
                }

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

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

                    // 使用默认值替换模板中的变量
                    string defaultTagNumber = "ERROR_TAG";
                    string defaultChannel = "SYSTEM";
                    string defaultStatus = "ERROR";
                    string defaultPackageCount = "0";
                    string defaultCreatedAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    // 替换模板中的硬编码值为默认值
                    htmlTemplate = htmlTemplate.Replace("TEST202602021626280001", defaultTagNumber);
                    htmlTemplate = htmlTemplate.Replace("TEST", defaultChannel);
                    htmlTemplate = htmlTemplate.Replace("Opened", defaultStatus);
                    htmlTemplate = htmlTemplate.Replace("5", defaultPackageCount);
                    htmlTemplate = htmlTemplate.Replace("2026-02-02 16:26:28", defaultCreatedAt);
                    
                    // 生成默认条形码并替换
                    var defaultBarcode = GenerateBarcode(defaultTagNumber);
                    htmlTemplate = htmlTemplate.Replace("{{barcodeBase64}}", defaultBarcode);

                    // 转换HTML为PDF
                    var doc = new HtmlToPdfDocument()
                    {
                        GlobalSettings = {
                            ColorMode = DinkToPdf.ColorMode.Color,
                            Orientation = DinkToPdf.Orientation.Landscape,
                            PaperSize = DinkToPdf.PaperKind.A4Plus,
                        },
                        Objects = {
                            new ObjectSettings() {
                                PagesCount = true,
                                HtmlContent = htmlTemplate,
                                WebSettings = { DefaultEncoding = "utf-8" },
                                HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
                            }
                        }
                    };

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

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

        private string RenderBagTagPdf(MDL.Models.BagTagEntity bagTag, int packageCount)
        {
            // 生成一个简单的PDF文件，使用基本字体
            var barcodeContent = GenerateBarcode(bagTag.TagNumber);

            // 创建PDF文件内容，使用更简单的结构
            var pdfContent = $@"%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>
endobj
4 0 obj
<< /Length 200 >>
stream
BT /F1 12 Tf 50 700 Td (Bag Tag) Tj ET
BT /F1 10 Tf 50 680 Td (Tag Number: {bagTag.TagNumber}) Tj ET
BT /F1 10 Tf 50 660 Td (Barcode: {barcodeContent}) Tj ET
BT /F1 10 Tf 50 640 Td (Channel: {bagTag.ChannelName}) Tj ET
BT /F1 10 Tf 50 620 Td (Status: {bagTag.Status}) Tj ET
BT /F1 10 Tf 50 600 Td (Package Count: {packageCount}) Tj ET
BT /F1 10 Tf 50 580 Td (Created At: {bagTag.CreatedAt}) Tj ET
endstream
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /Name /F1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>
endobj
xref
0 6
0000000000 65535 f 
0000000010 00000 n 
0000000062 00000 n 
0000000122 00000 n 
0000000251 00000 n 
0000000550 00000 n 
trailer
<< /Size 6 /Root 1 0 R >>
%%EOF";

            // 转换为base64编码
            var base64Content = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(pdfContent));
            return base64Content;
        }

        private string GenerateBarcode(string content)
        {
            try
            {
                // 配置条形码设置
                Spire.Barcode.BarcodeSettings settings = new Spire.Barcode.BarcodeSettings
                {
                    Data = content,
                    Type = Spire.Barcode.BarCodeType.Code128,
                    ShowText = false,
                    ImageHeight = 60,  // 增加高度以获得更清晰的条形码
                    ImageWidth = 200,
                    ForeColor = System.Drawing.Color.Black,
                    BackColor = System.Drawing.Color.White
                };

                // 创建条形码生成器
                Spire.Barcode.BarCodeGenerator generator = new Spire.Barcode.BarCodeGenerator(settings);
                
                // 生成条形码图像
                using (System.Drawing.Image barcodeImage = generator.GenerateImage())
                {
                    // 将图像保存到内存流
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        barcodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        // 转换为 Base64 编码
                        return System.Convert.ToBase64String(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误并返回原始内容作为 fallback
                Console.WriteLine($"Error generating barcode: {ex.Message}");
                return content;
            }
        }

        private string GenerateBarcodeWithZXing(string content)
        {
            try
            {
                // 配置条形码写入器
                var writer = new BarcodeWriterPixelData
                {
                    Format = BarcodeFormat.CODE_128,
                    Options = new EncodingOptions
                    {
                        Width = 180,
                        Height = 60,
                        Margin = 2
                    }
                };

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

                // 创建位图并保存到内存流
                using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
                using (var ms = new System.IO.MemoryStream())
                {
                    var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height),
                        System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                    System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
                    bitmap.UnlockBits(bitmapData);

                    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    return System.Convert.ToBase64String(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error generating barcode with ZXing: {ex.Message}");
                return content;
            }
        }

        private byte[] ImageToByte(Image img)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                return ms.ToArray();
            }
        }

        [HttpGet("test-pdf")]
        public IActionResult TestPdf()
        {
            try
            {
                // 创建HTML内容
                var htmlContent = @"<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <title>测试PDF</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: 10px; border: 1px solid #ddd; }
    </style>
</head>
<body>
    <div class='container'>
        <h1>测试PDF文档</h1>
        <div class='info'>
            <h2>袋牌信息</h2>
            <p><strong>标签号:</strong> TEST123456</p>
            <p><strong>渠道:</strong> UPS</p>
            <p><strong>状态:</strong> 已生成</p>
            <p><strong>包裹数量:</strong> 5</p>
            <p><strong>创建时间:</strong> " + DateTime.Now.ToString() + @"</p>
        </div>
        <div class='info'>
            <h2>测试说明</h2>
            <p>这是一个使用HtmlToPdfDocument生成的测试PDF文档。</p>
            <p>包含了基本的HTML结构和样式。</p>
        </div>
    </div>
</body>
</html>";

                // 创建PDF文档
                var doc = new HtmlToPdfDocument()
                {
                    GlobalSettings = {
                        ColorMode = DinkToPdf.ColorMode.Color,
                        Orientation = DinkToPdf.Orientation.Landscape,
                        PaperSize = DinkToPdf.PaperKind.A4Plus,
                    },
                    Objects = {
                        new ObjectSettings() {
                            PagesCount = true,
                            HtmlContent = htmlContent,
                            WebSettings = { DefaultEncoding = "utf-8" },
                            HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
                        }
                    }
                };

                // 转换HTML为PDF
                var converter = PdfConverterSingleton.Instance;
                byte[] pdf = converter.Convert(doc);

                // 返回PDF字节流
                return base.File(pdf, "application/pdf", "test_pdf_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[{DateTime.Now}] Exception in TestPdf: {ex.Message}");
                Console.WriteLine($"[{DateTime.Now}] Exception stack trace: {ex.StackTrace}");
                return base.File(new byte[0], "application/pdf");
            }
        }

        [HttpGet("batch")]
        public async Task<IActionResult> GetBagTagsBatch(
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 500,
            [FromQuery] string sortBy = "CreatedAt",
            [FromQuery] string sortOrder = "desc",
            [FromQuery] string tagNumber = "",
            [FromQuery] string channel = "",
            [FromQuery] string status = "",
            [FromQuery] string creator = "",
            [FromQuery] string callback = null)
        {
            try
            {
                // 限制pageSize，防止一次性加载过多数据
                //if (pageSize > 100)
                //{
                //    pageSize = 100;
                //}

                // 调用服务层的批量查询方法
                var (bagTags, totalCount) = await _bagTagService.GetBagTagsBatchAsync(
                    page, pageSize, sortBy, sortOrder, tagNumber, channel, status, creator);

                // 计算总页数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

                // 构建响应数据
                var responseData = new List<object>();
                foreach (var tag in bagTags)
                {
                    // 获取关联的运单数量
                    var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(tag.TagNumber);
                    
                    responseData.Add(new
                    {
                        id = tag.Id,
                        tagNumber = tag.TagNumber,
                        channelName = tag.ChannelName,
                        status = tag.Status,
                        creator = tag.Creator,
                        createdAt = tag.CreatedAt,
                        openedAt = tag.OpenedAt,
                        closedAt = tag.ClosedAt,
                        waybillCount = waybillCount
                    });
                }

                var result = new
                {
                    status = "ok",
                    data = responseData,
                    page = page,
                    pageSize = pageSize,
                    totalPages = totalPages,
                    totalCount = 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)
            {
                Log.Error(ex, "Error in GetBagTagsBatch");
                var errorResult = new
                {
                    status = "error",
                    message = "An error occurred while processing your request"
                };

                // 处理 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("waybill/{finalMileTrackingNumber}")]
        public async Task<IActionResult> GetBagTagByWaybill(string finalMileTrackingNumber, [FromQuery] string callback = null)
        {
            try
            {
                var association = await _bagTagService.GetBagTagByWaybillAsync(finalMileTrackingNumber);
                if (association != null)
                {
                    // 获取袋牌信息
                    var bagTag = await _bagTagService.GetBagTagAsync(association.TagNumber);
                    
                    var result = new
                    {
                        code = 0,
                        message = "success",
                        data = new
                        {
                            association.Id,
                            association.TagNumber,
                            association.FinalMileTrackingNumber,
                            association.Creator,
                            association.CreatedAt,
                            association.Remark,
                            bagTag = bagTag != null ? new
                            {
                                bagTag.ChannelName,
                                bagTag.Status,
                                bagTag.OpenedAt,
                                bagTag.ClosedAt
                            } : null
                        }
                    };

                    // 处理 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);
                }
                else
                {
                    var errorResult = new
                    {
                        code = 10036,
                        message = "Waybill not associated with any bag tag"
                    };

                    // 处理 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);
                }
            }
            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("available")]
        public async Task<IActionResult> GetAvailableBagTags([FromQuery] string channel, [FromQuery] string callback = null)
        {
            try
            {
                var caller = HttpContext.GetCaller();
                _logger.LogInformation("[Caller: {Caller}] GetAvailableBagTags, Channel: {Channel}", caller, channel);

                if (string.IsNullOrEmpty(channel))
                {
                    var errorResult = new
                    {
                        code = 400,
                        message = "Channel parameter is required"
                    };

                    // 处理 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);
                }

                var bagTags = await _bagTagService.GetAvailableBagTagsByChannelAsync(channel);
                
                // 构建响应数据，包含关联的运单数量
                var responseData = new List<object>();
                foreach (var tag in bagTags)
                {
                    var waybillCount = await _bagTagService.GetWaybillCountByTagNumberAsync(tag.TagNumber);
                    
                    responseData.Add(new
                    {
                        id = tag.Id,
                        tagNumber = tag.TagNumber,
                        channelName = tag.ChannelName,
                        status = tag.Status,
                        creator = tag.Creator,
                        createdAt = tag.CreatedAt,
                        openedAt = tag.OpenedAt,
                        closedAt = tag.ClosedAt,
                        waybillCount = waybillCount
                    });
                }

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

                // 处理 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);
            }
        }

        [HttpPost("auto-pack/start")]
        public async Task<IActionResult> StartAutoPack([FromBody] StartAutoPackRequest request)
        {
            try
            {
                var caller = HttpContext.GetCaller();
                _logger.LogInformation("[Caller: {Caller}] StartAutoPack, TagNumber: {TagNumber}", caller, request.TagNumber);
                request.Creator = caller;
                var result = await _bagTagService.StartAutoPackAsync(request.TagNumber, request.Creator);
                return Ok(new { code = 0, message = "success", data = result });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 1001, message = ex.Message });
            }
        }

        [HttpGet("auto-pack/progress/{taskId}")]
        public async Task<IActionResult> GetAutoPackProgress(string taskId)
        {
            try
            {
                var result = await _bagTagService.GetAutoPackProgressAsync(taskId);
                if (result == null)
                {
                    return Ok(new { code = 1002, message = "Task not found" });
                }
                return Ok(new { code = 0, message = "success", data = result });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 9999, message = ex.Message });
            }
        }

        [HttpPost("auto-pack/cancel/{taskId}")]
        public async Task<IActionResult> CancelAutoPack(string taskId)
        {
            try
            {
                var success = await _bagTagService.CancelAutoPackAsync(taskId);
                if (!success)
                {
                    return Ok(new { code = 1002, message = "Task not found or already completed" });
                }
                return Ok(new { code = 0, message = "Task cancelled successfully" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 9999, message = ex.Message });
            }
        }

        [HttpGet("auto-pack/result/{taskId}")]
        public async Task<IActionResult> GetAutoPackResult(string taskId)
        {
            try
            {
                var result = await _bagTagService.GetAutoPackResultAsync(taskId);
                if (result == null)
                {
                    return Ok(new { code = 1002, message = "Task not found" });
                }
                return Ok(new { code = 0, message = "success", data = result });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 9999, message = ex.Message });
            }
        }
    }
}