using DevExpress.Spreadsheet;
using DevExpress.XtraPdfViewer;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraSpreadsheet;
using DeviceRepair.Models;
using DeviceRepair.Utils;
using Newtonsoft.Json;
using PdfSharp.Drawing;
using PdfSharp.Pdf.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using TsSFCDevice.Client.Biz.Impl;
using TsSFCDevice.Client.Launch.PreserveTemplate;

namespace TsSFCDevice.Client.Launch.Preserve
{
    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)
                {
                    MaintenanceRecordSubmit model = PreserveRepository.Instance.Get_PreserveDetail_All(id);

                    if (model == null)
                    {
                        XtraMessageBoxHelper.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 = CommonRepository.Instance.DownLoadCheckForm(model.Record.FormPrimaryID);

                    ConvertExcelToPdf(templatePath, FullPath, model.Record);

                    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;

                                if (item.Datas.IsNull())
                                    item.Datas = CommonRepository.Instance.GetAttachmentImageByte(item.AutoID);

                                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))
                                {
                                    if (item.Datas.IsNull())
                                        item.Datas = CommonRepository.Instance.GetAttachmentImageByte(item.AutoID);
                                    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)
            {
                XtraMessageBoxHelper.Error(ex.Message);
                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["正文"];
                    else if (spreadsheetControl.Document.Worksheets.Contains("Table2"))
                        spreadsheetControl.Document.Worksheets.ActiveWorksheet = spreadsheetControl.Document.Worksheets["Table2"];
                    else
                    {
                        XtraMessageBoxHelper.Error("非标准设备保养表单！");
                        this.DialogResult = DialogResult.Cancel;
                    }
                    Worksheet worksheet = spreadsheetControl.Document.Worksheets.ActiveWorksheet;

                    MaintenanceFormVersionInfo CurrentFormModel = CheckFormRepository.Instance.Get_CheckForm_Single(Record.FormPrimaryID);

                    BaseTemplate template = null;
                    switch (CurrentFormModel.VersionCode)
                    {
                        case TemplateConstValue.CompositeTemplateV2:
                            template = JsonConvert.DeserializeObject<TemplateIndexV2>(CurrentFormModel.ContentData);
                            break;
                        case TemplateConstValue.CompositeTemplateV1:
                            template = JsonConvert.DeserializeObject<TemplateIndexV1>(CurrentFormModel.ContentData);
                            break;
                        case TemplateConstValue.DailyTemplateV2:
                            template = JsonConvert.DeserializeObject<Template_AM_01>(CurrentFormModel.ContentData);
                            break;
                        case TemplateConstValue.DailyTemplateV1:
                            template = JsonConvert.DeserializeObject<Template_AM_15>(CurrentFormModel.ContentData);
                            break;
                        case TemplateConstValue.MonthTemplateV1:
                            template = JsonConvert.DeserializeObject<Template_AM_17>(CurrentFormModel.ContentData);
                            break;
                        default:
                            break;
                    }

                    template.ReplaceData(JsonConvert.DeserializeObject<BaseTemplate>(Record.ContentData));

                    foreach (SheetDataItem item in template.EquipmentID)
                    {
                        Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                        cell.Value = item.Value + "";
                    }

                    SpreadsheetFont font = null;
                    foreach (SheetDataItem item in template.Content)
                    {
                        Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                        cell.Value = item.Value + "";

                        if (font == null)
                            font = cell.Font;
                        else
                        {
                        }
                        cell.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
                        cell.Alignment.Vertical = SpreadsheetVerticalAlignment.Center;
                    }

                    foreach (var item in template.Operation)
                    {
                        Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                        cell.Value = item.Value + "";
                        if (CurrentFormModel.VersionCode == TemplateConstValue.DailyTemplateV1 || CurrentFormModel.VersionCode == TemplateConstValue.DailyTemplateV2)
                            cell.Alignment.WrapText = true;
                    }

                    foreach (var item in template.OperationDate)
                    {
                        worksheet.Cells[item.RowIndex, item.ColumnIndex].AutoFitColumns();
                    }

                    var gData = template.ExceptionDescription.Where(x => x.Value != null).GroupBy(
                        x => new { x.RowIndex, x.ColumnIndex });

                    foreach (var group in gData)
                    {
                        Cell cell = worksheet.Cells[group.Key.RowIndex, group.Key.ColumnIndex];
                        cell.Value = template.ExceptionFreezeString + string.Join("", group.Select(x => x.Value).ToArray());
                        cell.Alignment.WrapText = true;
                        cell.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Left;
                        cell.Alignment.Vertical = SpreadsheetVerticalAlignment.Top;
                        double CurrentHeight = worksheet.Rows[group.Key.RowIndex].Height;
                        worksheet.Rows[group.Key.RowIndex].AutoFitRows();
                        double AlertHeight = worksheet.Rows[group.Key.RowIndex].Height;
                        if (CurrentHeight > AlertHeight)
                            worksheet.Rows[group.Key.RowIndex].Height = CurrentHeight;
                    }

                    foreach (SheetDataItem item in template.EquipmentName)
                    {
                        Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                        cell.Value = Record.EquipmentName;
                    }

                    foreach (SheetDataItem item in template.DeviceSpecification)
                    {
                        Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                        cell.Value = Record.Specification;
                    }

                    foreach (SheetDataItem item in template.InstallationSite)
                    {
                        Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                        cell.Value = Record.InstallationSite;
                    }

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


                    if (CurrentFormModel.VersionCode == TemplateConstValue.DailyTemplateV1 || CurrentFormModel.VersionCode == TemplateConstValue.DailyTemplateV2)
                    {
                        DriveMaintencePlanInfo plans = PlanRepository.Instance.Get_PLAN_Single(Record.PlanPrimaryID);

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

                    worksheet.ActiveView.PaperKind = System.Drawing.Printing.PaperKind.A4;

                    worksheet.PrintOptions.FitToPage = true;
                    if (CurrentFormModel.VersionCode == TemplateConstValue.DailyTemplateV1 || CurrentFormModel.VersionCode == TemplateConstValue.DailyTemplateV2)
                    {
                        worksheet.PrintOptions.FitToHeight = 1;
                    }
                    else
                        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;
        }
    }
}
