using DevExpress.Spreadsheet;
using DevExpress.XtraEditors;
using DevExpress.XtraPdfViewer;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraSpreadsheet;
using DeviceRepair.Models;
using DeviceRepair.Utils;
using DeviceRepairAndOptimization.Biz;
using Newtonsoft.Json;
using PdfSharp.Drawing;
using PdfSharp.Pdf.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Linq;

namespace DeviceRepairAndOptimization.Pages.Maintenance
{
    public partial class page_MaintenancePdfView : Form
    {
        private int[] MaintenanceAutoIds;

        private bool PrintModule = false;

        public page_MaintenancePdfView(string Caption, int[] ids, bool isPrint = false)
        {
            InitializeComponent();
            //pdfViewer1.CreateBars();
            ///设置标题
            this.Text = Caption;
            if (ids == null || ids.Length == 0)
                this.Close();

            MaintenanceAutoIds = ids;
            PrintModule = isPrint;
        }

        private void page_MaintenancePdfView_Load(object sender, EventArgs e)
        {
            SplashScreenManager.ShowDefaultWaitForm("数据加载中", "请稍等...");
            try
            {
                List<string> files = new List<string>();
                string CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                foreach (var id in MaintenanceAutoIds)
                {
                    APIResponseData result = PreserveManager.Instance.GetDetailById(id);
                    if (result.Code == -1)
                    {
                        XtraMessageBox.Show(result.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        SplashScreenManager.CloseDefaultWaitForm();
                        this.Close();
                        return;
                    }

                    byte[] btResult = Convert.FromBase64String(result.Data + "");
                    btResult = btResult.Decompress();
                    MaintenanceRecordSubmit model = btResult.ToObject<MaintenanceRecordSubmit>();

                    if (model == null)
                    {
                        XtraMessageBox.Show("获取数据失败", "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        SplashScreenManager.CloseDefaultWaitForm();
                        this.Close();
                    }

                    if (!Directory.Exists(Path.Combine(CurrentDirectory, "Cache")))
                        Directory.CreateDirectory(Path.Combine(CurrentDirectory, "Cache"));

                    string CacheFileName = Guid.NewGuid().ToString() + ".pdf";
                    string FullPath = Path.Combine(CurrentDirectory, "Cache", CacheFileName);


                    //下载模板到本地
                    string templatePath = PreserveManager.Instance.GetFileSingle(model.Record.FormPrimaryID);

                    ConvertExcelToPdf(templatePath, FullPath, model.Record);
                    //ConvertExcelToPdf(model.ContentData, FullPath);

                    if (model.Imgs != null && model.Imgs.Count > 0)
                    {
                        using (PdfSharp.Pdf.PdfDocument document = PdfReader.Open(FullPath, PdfDocumentOpenMode.Modify))
                        {
                            foreach (var item in model.Imgs)
                            {
                                // 添加新的空白页面
                                PdfSharp.Pdf.PdfPage page = document.AddPage();
                                // 设置页面大小（可选）
                                page.Size = PdfSharp.PageSize.A4;
                                using (MemoryStream ms = new MemoryStream(item.Datas))
                                {
                                    // 加载图片文件
                                    using (XImage image = XImage.FromStream(ms))
                                    {
                                        // 获取图形对象
                                        XGraphics gfx = XGraphics.FromPdfPage(page);

                                        // 绘制图片到页面，指定图片的位置和尺寸
                                        gfx.DrawImage(image, 0, 0, page.Width, page.Height); // 这里将图片填满整个页面，你可以调整参数以适应你的需求
                                    }
                                }
                            }
                            document.Save(FullPath);
                        }
                    }

                    files.Add(FullPath);

                    if (model.Files != null && model.Files.Count > 0)
                    {
                        try
                        {
                            foreach (AttachmentSubmitModel item in model.Files)
                            {
                                if (item.Extension.ToLower() != ".pdf")
                                    continue;

                                string attFileFullPath = Path.Combine(CurrentDirectory, "Cache", Guid.NewGuid().ToString() + ".pdf");
                                using (var fileStream = new FileStream(attFileFullPath, FileMode.Create))
                                {
                                    fileStream.Write(item.Datas, 0, item.Datas.Length);
                                }
                                files.Add(attFileFullPath);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }
                    }
                }

                string PdfFilePath = "";
                if (files.Count > 1)
                {
                    string fileName = Guid.NewGuid().ToString() + ".pdf";
                    string outputName = Path.Combine(CurrentDirectory, "Cache", fileName);
                    MergePdfDocuments(files.ToArray(), outputName);
                    PdfFilePath = outputName;
                }
                else
                {
                    PdfFilePath = files[0];
                }

                pdfViewer1.LoadDocument(PdfFilePath);

                if (PrintModule)
                {
                    var printerSettings = new System.Drawing.Printing.PrinterSettings();
                    pdfViewer1.Print();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }

            SplashScreenManager.CloseDefaultWaitForm();
        }

        void MergePdfDocuments(string[] pdfFiles, string outputPdfPath)
        {
            using (PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument())
            {
                foreach (string pdfFile in pdfFiles)
                {
                    using (PdfSharp.Pdf.PdfDocument inputDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import))
                    {
                        int count = inputDocument.PageCount;
                        for (int idx = 0; idx < count; idx++)
                        {
                            PdfSharp.Pdf.PdfPage page = inputDocument.Pages[idx];
                            outputDocument.AddPage(page);
                        }
                    }
                }

                outputDocument.Save(outputPdfPath);
            }
        }

        /// <summary>
        /// 保存到文件
        /// </summary>
        /// <param name="excelBytes"></param>
        /// <param name="FilePath"></param>
        private void ConvertExcelToPdf(byte[] excelBytes, string FilePath)
        {
            using (MemoryStream excelStream = new MemoryStream(excelBytes))
            {
                using (SpreadsheetControl spreadsheetControl = new SpreadsheetControl())
                {
                    using (IWorkbook workbook = spreadsheetControl.Document)
                    {
                        workbook.LoadDocument(excelStream);
                        using (FileStream pdfFileStream = new FileStream(FilePath, FileMode.Create))
                        {
                            workbook.ExportToPdf(pdfFileStream);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 保存到文件
        /// </summary>
        /// <param name="excelBytes"></param>
        /// <param name="FilePath"></param>
        private void ConvertExcelToPdf(string excelFile, string FilePath, MaintenanceRecordInfo Record)
        {
            try
            {
                using (SpreadsheetControl spreadsheetControl = new SpreadsheetControl())
                {
                    spreadsheetControl.LoadDocument(IOExtend.FileToByteArray(excelFile));
                    if (spreadsheetControl.Document.Worksheets.Contains("正文"))
                        spreadsheetControl.Document.Worksheets.ActiveWorksheet = spreadsheetControl.Document.Worksheets["正文"];

                    Worksheet worksheet = spreadsheetControl.Document.Worksheets.ActiveWorksheet;

                    //Biz.PreserveTemplate.TemplateIndexV1 template = Record.FormVersionCode.Equals("FM-P0079.02", StringComparison.CurrentCultureIgnoreCase)?
                    //    JsonConvert.DeserializeObject<Biz.PreserveTemplate.TemplateIndexV1>(Record.ContentData)
                    //    : JsonConvert.DeserializeObject<Biz.PreserveTemplate.TemplateIndexV2>(Record.ContentData);

                    Biz.PreserveTemplate.TemplateIndexV1 template = JsonConvert.DeserializeObject<Biz.PreserveTemplate.TemplateIndexV1>(Record.ContentData);
                    List<SheetDataItem>[] ItemArray = new List<SheetDataItem>[] {
                        template.DeviceSpecification,
                        template.EquipmentID,
                        template.Content,
                        template.ExceptionDescription,
                        template.Operation,
                        template.OperationDate
                    };

                    foreach (List<SheetDataItem> lst in ItemArray)
                    {
                        foreach (SheetDataItem item in lst)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = item.Value + "";
                        }
                    }


                    foreach (SheetDataItem item in template.Year)
                    {
                        Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                        cell.Value = cell.Value.TextValue.Replace("    年", $"{item.Value}年");
                    }

                    //int Count = spreadsheetControl.Document.Worksheets.ActiveWorksheet.VerticalPageBreaks.Count;
                    worksheet.ActiveView.PaperKind = System.Drawing.Printing.PaperKind.A4;
                    //worksheet.ActiveView.Orientation = PageOrientation.Portrait;
                    //worksheet.PrintOptions.Orientation
                    worksheet.PrintOptions.FitToPage = true;
                    worksheet.PrintOptions.FitToHeight = 0;

                    using (IWorkbook workbook = spreadsheetControl.Document)
                    {
                        using (FileStream pdfFileStream = new FileStream(FilePath, FileMode.Create))
                        {
                            workbook.ExportToPdf(pdfFileStream);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }


        }

        /// <summary>
        /// 右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pdfViewer1_PopupMenuShowing(object sender, PdfPopupMenuShowingEventArgs e)
        {
            if (e.PopupMenuKind == PdfPopupMenuKind.PageContent)
                e.ItemLinks.Clear();
            //e.ItemLinks[0].Visible = false;
        }
    }
}
