using Siger.ApiCommon.Utilities;
using Siger.ApiDashboard.Tasks.Model;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.FieldEnum;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace Siger.ApiDashboard.Tasks.Reports
{
    internal class ConvertHelper
    {
        public static ConvertPdfResult ConvertToPdf(string htmlContent, siger_project_monthreport_config config)
        {
            //生成html再转pdf
            var newHtmlFolder = GetNewHtmlFolder();
            var newHtmlPath = Path.Combine(newHtmlFolder, GetNewHtmlFileName(config.template_id) + ".html");
            FileHelper.WriteFile(htmlContent, newHtmlPath);
            if (!File.Exists(newHtmlPath))
            {
                return new ConvertPdfResult(ReportSendResult.WriteHtmlTemplateFailed);
            }

            //convert
            var pdfFilePath = ConvertPdf(newHtmlPath, config.template_id);
            if (!File.Exists(pdfFilePath))
            {
                return new ConvertPdfResult(ReportSendResult.ConvertPdfFailed);
            }

            //重命名
            var pdfFile = new FileInfo(pdfFilePath);
            var destPath = Path.Combine(pdfFile.DirectoryName, config.name + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf");
            //判断是否重名
            if (!File.Exists(destPath))
            {
                pdfFile.CopyTo(destPath);
            }

            return new ConvertPdfResult(ReportSendResult.Successful, destPath);
        }
        public static ConvertPdfResult ConvertToPdf(string htmlContent, int sendType = 0)
        {
            //生成html再转pdf
            var reportTemplate = ReportTemplate.MainReport;
            var newHtmlFolder = GetNewHtmlFolder();
            var newHtmlPath = Path.Combine(newHtmlFolder, GetNewHtmlFileName(reportTemplate) + ".html");
            FileHelper.WriteFile(htmlContent, newHtmlPath);
            if (!File.Exists(newHtmlPath))
                return new ConvertPdfResult(ReportSendResult.WriteHtmlTemplateFailed);

            if (sendType == 0)
                return new ConvertPdfResult(ReportSendResult.Successful, "", newHtmlPath);

            //convert
            var pdfFilePath = ConvertPdf(newHtmlPath, reportTemplate);
            if (!File.Exists(pdfFilePath))
                return new ConvertPdfResult(ReportSendResult.ConvertPdfFailed);

            //重命名
            var pdfFile = new FileInfo(pdfFilePath);
            var destPath = Path.Combine(pdfFile.DirectoryName, reportTemplate.ToString() + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf");
            //判断是否重名
            if (!File.Exists(destPath))
                pdfFile.CopyTo(destPath);

            return new ConvertPdfResult(ReportSendResult.Successful, destPath, newHtmlPath);
        }
        private static string GetNewHtmlFolder()
        {
            var fileSetting = Config<FileSettings>.Get();
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, "NewHtml",
                DateTime.Now.ToString("yyyy-MM-dd"));
           

            return rootDir;
        }

        private static string GetNewHtmlFileName(ReportTemplate template)
        {
            var description = template.ToString();
            return description + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
        }

        private static string ConvertPdf(string fileName, ReportTemplate template)
        {
            var fileSetting = Config<FileSettings>.Get();

            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, "PdfReport",
                DateTime.Now.ToString("yyyy-MM-dd"));
           

            var path = Path.Combine(rootDir, GetNewHtmlFileName(template) + ".pdf");

            var arguments = " " + fileName + " " + path;

            string toolPath;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows).Equals(true))
            {
                toolPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Utilities", "wkhtmltopdf.exe");
                if (!File.Exists(toolPath))
                {
                    throw new FileNotFoundException("Can not find pdf convert tool.");
                }
            }
            else
            {
                toolPath = "wkhtmltopdf";
            }

            try
            {
                var p = new Process
                {
                    StartInfo =
                    {
                        FileName = toolPath,
                        Arguments = arguments,
                        UseShellExecute = false,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = false
                    }
                };
                p.Start();
                p.WaitForExit();
                System.Threading.Thread.Sleep(1000);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ConvertPdf Error," + e);
                throw;
            }

            return path;
        }
    }
}
