using iTextSharp.awt.geom;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.util;

namespace XYY.Core.Standard.PDF
{
    public static class PDFHelper
    {


        public static byte[] SetPdfSize(byte[] data, double x, double y, float width, float height, double angle = 0, int qty = 0, double scale = 1.0)
        {
            var ms = new MemoryStream();
            PdfReader reader = new PdfReader(data);
            Document doc = new Document();
            doc.SetPageSize(new iTextSharp.text.Rectangle(width, height));


            PdfWriter writer = PdfWriter.GetInstance(doc, ms);
            doc.Open();

            PdfContentByte cb = writer.DirectContent;

            AffineTransform transform = new AffineTransform();
            transform.Translate(x, y);
            transform.Scale(scale, scale);
            if (angle > 0)
                transform.SetToRotation(angle);
            if (qty == 0)
                qty = reader.NumberOfPages;
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                doc.NewPage();
                PdfImportedPage page = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page, transform);
            }
            doc.Close();
            return ms.ToArray();
        }

        public static byte[] CutOutPackage(byte[] data, int index)
        {
            var ms = new MemoryStream();
            PdfReader reader = new PdfReader(data);
            Document doc = new Document(reader.GetPageSizeWithRotation(index));
            doc.NewPage();
            PdfWriter writer = PdfWriter.GetInstance(doc, ms);
            doc.Open();
            PdfContentByte cb = writer.DirectContent;
            AffineTransform transform = new AffineTransform();
            for (int i = index; i <= index; i++)
            {
                PdfImportedPage page = writer.GetImportedPage(reader, i);
                var rotation = reader.GetPageRotation(index);
                if (rotation == 90)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(index).Height);
                }
                else if (rotation == 180)
                {
                    cb.AddTemplate(page, -1f, 0, 0, -1f, reader.GetPageSizeWithRotation(index).Width, reader.GetPageSizeWithRotation(index).Height);
                }
                else if (rotation == 270)
                {
                    cb.AddTemplate(page, 0, 1f, -1f, 0, reader.GetPageSizeWithRotation(index).Width, 0);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
            }
            doc.Close();
            return ms.ToArray();
        }


        /// <summary>
        /// PDF合并方法
        /// </summary>
        /// <param name="outMergeFile">输出文件路径</param>
        /// <param name="lstFile">需要合并的PDF文件</param>
        /// <param name="isStretch">是否缩放文件尺寸到第一页</param>
        public static byte[] SetPageSize(byte[] data, int width, int height, int rotation)
        {
            Document document = new Document();
            using (var ms = new System.IO.MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(document, ms);
                document.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage newPage;

                var reader = new PdfReader(data);
                int iPageNum = reader.NumberOfPages;
                int startPage = 1;
                while (startPage <= iPageNum)
                {

                    Rectangle rectrangle = null;

                    rectrangle = new Rectangle(width, height);
                    if (rotation == 90)
                    {
                        rectrangle = new Rectangle(height, width);
                    }
                    document.SetPageSize(rectrangle);
                    document.NewPage();
                    newPage = writer.GetImportedPage(reader, startPage);
                    if (rotation == 90)
                    {
                        cb.AddTemplate(newPage, 0, -1f, 1f, 0, 0, width);
                    }
                    else if (rotation == 180)
                    {
                        cb.AddTemplate(newPage, -1f, 0, 0, -1f, reader.GetPageSizeWithRotation(startPage).Width, reader.GetPageSizeWithRotation(startPage).Height);
                    }
                    else if (rotation == 270)
                    {
                        cb.AddTemplate(newPage, 0, 1f, -1f, 0, reader.GetPageSizeWithRotation(startPage).Width, 0);
                    }
                    else
                    {
                        cb.AddTemplate(newPage, 1f, 0, 0, 1f, 0, 0);
                    }
                    startPage++;
                }
                document.Close();
                return ms.ToArray();
            }
        }


        public static void PDFFileRepeat(string outMergeFile, byte[] file)
        {
            if (!string.IsNullOrEmpty(outMergeFile))
            {
                try
                {
                    if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(outMergeFile)))
                    {
                        System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(outMergeFile));
                    }

                    var document = new Document(new PdfReader(new MemoryStream(file)).GetPageSizeWithRotation(1));
                    PdfCopy copy = new PdfCopy(document, new System.IO.FileStream(outMergeFile, FileMode.Create));
                    document.Open();

                    PdfReader reader = new PdfReader(file);
                    int n = reader.NumberOfPages;// 获得总页码
                    for (int j = 1; j <= 2; j++)
                    {
                        document.NewPage();
                        PdfImportedPage page = copy.GetImportedPage(reader, 1);// 从当前Pdf,获取第j页
                        copy.AddPage(page);
                    }
                    document.Close();
                }
                catch (Exception ex)
                {
                }
            }
        }

        public static void MergePDFFiles(string outMergeFile, List<byte[]> files, bool isStretch = true, int qty = 0)
        {
            if (!string.IsNullOrEmpty(outMergeFile))
            {
                try
                {
                    if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(outMergeFile)))
                    {
                        System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(outMergeFile));
                    }

                    var document = new Document(new PdfReader(new MemoryStream(files[0])).GetPageSizeWithRotation(1));
                    PdfCopy copy = new PdfCopy(document, new System.IO.FileStream(outMergeFile, FileMode.Create));
                    document.Open();
                    for (int i = 0; i < files.Count; i++)
                    {
                        PdfReader reader = new PdfReader(files[i]);
                        int n = qty == 0 ? reader.NumberOfPages : qty;// 获得总页码
                        for (int j = 1; j <= n; j++)
                        {
                            document.NewPage();
                            PdfImportedPage page = copy.GetImportedPage(reader, j);// 从当前Pdf,获取第j页
                            copy.AddPage(page);
                        }
                    }
                    document.Close();
                }
                catch (Exception ex)
                {
                }
            }
        }


        public class InvoiceOrder
        {
            public string senderPhone
            {
                get; set;
            }
            public string senderCountry
            {
                get; set;
            }
            public string senderState
            {
                get; set;
            }
            public string senderCity
            {
                get; set;
            }
            public string senderPostCode
            {
                get; set;
            }
            public string senderName
            {
                get; set;
            }
            public string senderCompany
            {
                get; set;
            }
            public string senderStree
            {
                get; set;
            }
            public string HSCode
            {
                get; set;
            }
            public string TackingNumber
            {
                get; set;
            }

            public string Phone
            {
                get; set;
            }

            public string Name
            {
                get; set;
            }

            public string Stree
            {
                get; set;
            }

            public string Weight
            {
                get; set;
            }

            public string Number
            {
                get; set;
            }

            public string EnName
            {
                get; set;
            }

            public string Country
            {
                get; set;
            }

            public string Qty
            {
                get; set;
            }

            public string UV
            {
                get; set;
            }

            public string SV
            {
                get; set;
            }

            public string SUV
            {
                get; set;
            }

            public string SSV
            {
                get; set;
            }

            public DateTime Time
            {
                get; set;
            }
        }

        public static byte[] Zoom(string pdfPath, int width, int height)
        {
            System.IO.MemoryStream ms = new MemoryStream();
            PdfReader reader = new PdfReader(pdfPath);
            Document document = new Document();
            document.SetPageSize(new Rectangle(new RectangleJ(0, 0, width, height)));
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage page = writer.GetImportedPage(reader, 1); //page #1
            float Scale = Math.Max(width / page.Width, height / page.Height);
            cb.AddTemplate(page, Scale, 0, 0, Scale, 0, 0);
            document.Close();
            //ms.Position = 0;
            return ms.ToArray();
        }

 
        public class FCLabelInfo
        {
            public string TransferNumber
            {
                get; set;
            }

            public string TrackngNumber
            {
                get; set;
            }

            public string TrackngNumber2
            {
                get; set;
            }

            public string Name
            {
                get; set;
            }

            public string Stree
            {
                get; set;
            }

            public string City
            {
                get; set;
            }

            public string State
            {
                get; set;
            }

            public string ReceiverZipCode
            {
                get; set;
            }

            public string Weight
            {
                get; set;
            }
        }


  
        public static byte[] Watermark(byte[] data, string text, int package, int x, int y, int fontSize, BaseColor color)
        {
            try
            {
                using (PdfReader pdfReader = new PdfReader(new System.IO.MemoryStream(data)))
                {
                    using (var outputStream = new System.IO.MemoryStream())
                    {
                        PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
                        PdfContentByte content;
                        BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                        PdfGState gs = new PdfGState();
                        int numberOfPackage = pdfReader.NumberOfPages;
                        numberOfPackage = package;

                        content = pdfStamper.GetOverContent(numberOfPackage);

                        gs.FillOpacity = 1f;
                        content.SetGState(gs);
                        content.BeginText();
                        content.SetColorFill(color);
                        content.SetFontAndSize(font, fontSize);
                        content.SetTextMatrix(0, 0);
                        content.ShowTextAligned(Element.ALIGN_LEFT, text, x, y, 0);
                        content.EndText();
                        pdfStamper.Close();
                        return outputStream.ToArray();
                    }
                }
            }
            catch (FileNotFoundException)
            {
                throw new InvalidOperationException("Label的PDF文件不存在");
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("水印生成错误" + ex.Message);
            }
        }
    }
}
