using System.Threading.Tasks;
using BLL.Interfaces;
using MDL.DTOs;
using ZXing;
using ZXing.Common;

namespace BLL.Services
{
    public class TagGenerationService : ITagGenerationService
    {
        private readonly ITagInstanceService _tagInstanceService;
        private readonly ITagTemplateService _tagTemplateService;

        public TagGenerationService(ITagInstanceService tagInstanceService, ITagTemplateService tagTemplateService)
        {
            _tagInstanceService = tagInstanceService;
            _tagTemplateService = tagTemplateService;
        }

        public async Task<TagInstanceDTO> GenerateTagAsync(GenerateTagDTO dto)
        {
            // 创建标签实例
            var createDTO = new CreateTagInstanceDTO
            {
                TagType = dto.TagType,
                NeutralWaybillNumber = dto.NeutralWaybillNumber,
                CustomerId = dto.CustomerId
            };

            var instance = await _tagInstanceService.CreateInstanceAsync(createDTO);
            return instance;
        }

        public async Task<string> RenderTagAsync(RenderTagDTO dto)
        {
            // 获取标签实例
            var instance = await _tagInstanceService.GetInstanceAsync(dto.TagInstanceId);
            
            // 获取标签模板
            var template = await _tagTemplateService.GetTemplateByTypeAsync(instance.TagType);
            
            // 根据渲染格式生成不同的输出
            if (dto.RenderFormat.ToUpper() == "HTML")
            {
                return RenderHtmlTag(instance, template);
            }
            else if (dto.RenderFormat.ToUpper() == "ZPL")
            {
                return RenderZplTag(instance, template);
            }
            else if (dto.RenderFormat.ToUpper() == "PDF")
            {
                return RenderPdfTag(instance, template);
            }
            else
            {
                throw new System.Exception("Unsupported render format");
            }
        }

        public async Task<string> GenerateBarcodeAsync(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 string RenderHtmlTag(TagInstanceDTO instance, MDL.DTOs.TagTemplateDTO template)
        {
            // 生成HTML格式的标签
            return $@"
            <div style=""border: 1px solid black; padding: 10px; width: 200px;"">
                <h3>STOP标签</h3>
                <p>中性单号: {instance.NeutralWaybillNumber}</p>
                <p>客户ID: {instance.CustomerId}</p>
                <p>触发时间: {instance.TriggerTime}</p>
                <p>标签状态: {instance.Status}</p>
                <div>条形码: {GenerateBarcodeAsync(instance.NeutralWaybillNumber).Result}</div>
            </div>
            ";
        }

        private string RenderZplTag(TagInstanceDTO instance, MDL.DTOs.TagTemplateDTO template)
        {
            // 生成ZPL格式的标签
            // 实际实现需要根据ZPL语法生成正确的命令
            return $@"
            ^XA
            ^FO50,50^A0N,36,24^FDSTOP标签^FS
            ^FO50,100^A0N,24,18^FD中性单号: {instance.NeutralWaybillNumber}^FS
            ^FO50,140^A0N,24,18^FD客户ID: {instance.CustomerId}^FS
            ^FO50,180^A0N,24,18^FD触发时间: {instance.TriggerTime}^FS
            ^FO50,220^A0N,24,18^FD标签状态: {instance.Status}^FS
            ^FO50,260^BY2,3,100^BCN,100,Y,N,N^FD{instance.NeutralWaybillNumber}^FS
            ^XZ
            ";
        }

        private string RenderPdfTag(TagInstanceDTO instance, MDL.DTOs.TagTemplateDTO template)
        {
            // 生成PDF格式的标签
            // 实际实现需要使用PDF生成库，这里返回base64编码的占位符
            // 注意：实际项目中需要使用如iTextSharp等库生成真实的PDF
            
            // 模拟PDF生成，返回base64编码的占位符
            // 实际实现时，这里应该生成真实的PDF字节流并转换为base64
            var pdfContent = $"STOP标签|中性单号: {instance.NeutralWaybillNumber}|客户ID: {instance.CustomerId}|触发时间: {instance.TriggerTime}|标签状态: {instance.Status}";
            var base64Content = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(pdfContent));
            
            return base64Content;
        }
    }
}
