using Aspose.Words;
using Microsoft.Office.Interop.Excel;
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace BLL
{
    /// <summary>
    /// word文档操作辅助类
    /// </summary>
    public class AsposeWordHelper
    {
        /// <summary>
        /// Word
        /// </summary>
        private Document wordDoc;

        /// <summary>
        /// 基于模版新建Word文件
        /// </summary>
        /// <param name="path">模板路径</param>
        public void OpenTempelte(string path)
        {
            wordDoc = new Document(path);
        }

        /// <summary>
        /// 书签赋值用法
        /// </summary>
        /// <param name="LabelId">书签名</param>
        /// <param name="Content">内容</param>
        public void WriteBookMark(string LabelId, string Content)
        {
            if (wordDoc.Range.Bookmarks[LabelId] != null)
            {
                wordDoc.Range.Bookmarks[LabelId].Text = Content;
            }
        }

        /// <summary>
        /// 列表赋值用法
        /// </summary>
        /// <param name="dt"></param>
        public void WriteTable(System.Data.DataTable dt)
        {
            wordDoc.MailMerge.ExecuteWithRegions(dt);
        }

        /// <summary>
        /// 文本域赋值用法
        /// </summary>
        /// <param name="fieldNames">key</param>
        /// <param name="fieldValues">value</param>
        public void Executefield(string[] fieldNames, object[] fieldValues)
        {
            wordDoc.MailMerge.Execute(fieldNames, fieldValues);
        }

        /// <summary>
        /// Pdf文件保存
        /// </summary>
        /// <param name="filename">文件路径+文件名</param>
        public void SavePdf(string filename)
        {
            wordDoc.Save(filename, SaveFormat.Pdf);
        }

        /// <summary>
        /// Doc文件保存
        /// </summary>
        /// <param name="filename">文件路径+文件名</param>
        public void SaveDoc(string filename)
        {
            wordDoc.Save(filename, SaveFormat.Doc);
        }

        /// <summary>
        /// 不可编辑受保护,需输入密码
        /// </summary>
        /// <param name="pwd">密码</param>
        public void NoEdit(string pwd)
        {
            wordDoc.Protect(ProtectionType.ReadOnly, pwd);
        }

        /// <summary>
        /// 只读
        /// </summary>
        public void ReadOnly()
        {
            wordDoc.Protect(ProtectionType.ReadOnly);
        }

        /// <summary>
        /// 通过流导出word文件
        /// </summary>
        /// <param name="stream">流</param>
        /// <param name="fileName">文件名</param>
        public static HttpResponseMessage ExportWord(Stream stream, string fileName)
        {
            var file = stream;
            fileName += DateTime.Now.ToString("yyyyMMddHHmmss");
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(file);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = fileName + ".doc";
            return result;
        }

        /// <summary>
        /// 通过流导出pdf文件
        /// </summary>
        /// <param name="stream">流</param>
        /// <param name="fileName">文件名</param>
        public static HttpResponseMessage ExportPdf(Stream stream, string fileName)
        {
            var file = stream;
            fileName += DateTime.Now.ToString("yyyyMMddHHmmss");
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(file);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = fileName + ".pdf";
            return result;
        }

        public static  void InsertImg(Document doc, string rootPath, string BookmarksName, string ManId, string Idea)
        {
             Bookmark bookmarkCreateMan = doc.Range.Bookmarks[BookmarksName];

            if (bookmarkCreateMan != null)
            {
                var user = UserService.GetUserByUserId(ManId);
                if (user != null)
                {
                    if (!string.IsNullOrEmpty(user.SignatureUrl))
                    {
                        var file = user.SignatureUrl;
                        if (!string.IsNullOrWhiteSpace(file))
                        {
                            string url = rootPath + file;
                            DocumentBuilder builders = new DocumentBuilder(doc);
                            builders.MoveToBookmark(BookmarksName);
                            if (!string.IsNullOrEmpty(url))
                            {
                                System.Drawing.Size JpgSize;
                                float Wpx;
                                float Hpx;
                                UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                double i = 1;
                                i = JpgSize.Width / 50.0;
                                if (File.Exists(url))
                                {
                                    bookmarkCreateMan.Text = Idea;
                                    builders.InsertImage(url, JpgSize.Width *1.6/ i, JpgSize.Height * 1.2 / i);
                                    
                                }
                                else
                                {
                                    bookmarkCreateMan.Text = Idea;

                                    bookmarkCreateMan.Text = user.UserName;
                                }

                            }
                        }
                    }
                    else
                    {
                        bookmarkCreateMan.Text = user.UserName;
                    }
                }
            }
        }
        public static  void InsertImg(Document doc, string rootPath, string BookmarksName, string ManId, string Idea,bool IdeaIsCover)
        {
             Bookmark bookmarkCreateMan = doc.Range.Bookmarks[BookmarksName];

            if (bookmarkCreateMan != null)
            {
                var user = UserService.GetUserByUserId(ManId);
                if (user != null)
                {
                    if (!string.IsNullOrEmpty(user.SignatureUrl))
                    {
                        var file = user.SignatureUrl;
                        if (!string.IsNullOrWhiteSpace(file))
                        {
                            string url = rootPath + file;
                            DocumentBuilder builders = new DocumentBuilder(doc);
                            builders.MoveToBookmark(BookmarksName);
                            if (!string.IsNullOrEmpty(url))
                            {
                                System.Drawing.Size JpgSize;
                                float Wpx;
                                float Hpx;
                                UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                double i = 1;
                                i = JpgSize.Width / 50.0;
                                if (File.Exists(url))
                                {
                                    if (IdeaIsCover)
                                    {
                                        bookmarkCreateMan.Text += Idea;

                                    }
                                    else
                                    {
                                        bookmarkCreateMan.Text = Idea;

                                    }
                                    builders.InsertImage(url, JpgSize.Width *1.6/ i, JpgSize.Height * 1.2 / i);
                                    
                                }
                                else
                                {
                                    if (IdeaIsCover)
                                    {
                                        bookmarkCreateMan.Text += Idea;

                                    }
                                    else
                                    {
                                        bookmarkCreateMan.Text = Idea;

                                    }
                                    bookmarkCreateMan.Text = user.UserName;
                                }

                            }
                        }
                    }
                    else
                    {
                        bookmarkCreateMan.Text = user.UserName;
                    }
                }
            }
        }
        public static void WordIntoPdf(string wordPath, string pdfPath)
        {
            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document document = null;
            try
            {
                application.Visible = false;
                document = application.Documents.Open(wordPath);
                document.ExportAsFixedFormat(pdfPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                document.Close();
            }
        }

        /// <summary>
        /// html代码转word
        /// </summary>
        /// <param name="Html">html代码</param>
        /// <param name="path">保存路径</param>
        public static void HtmlIntoWord(string Html,string path)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append(
                "<html xmlns:v=\"urn:schemas-microsoft-com:vml\"  xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"xmlns = \"http://www.w3.org/TR/REC-html40\">");
            sb.Append(Html);
            sb.Append("</html>");
            var html = sb.ToString();//读取html内容
             StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("utf-8"));
            sw.WriteLine(html);
            sw.Flush();
            sw.Close();
        }  
        public static  string WordToHtml(object wordFileName)
        {
            //在此处放置用户代码以初始化页面
            Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
            word.Visible = false;//使文档可见(程序运行时,word文档不会闪屏)
            Type wordType = word.GetType();
            Microsoft.Office.Interop.Word.Documents docs = word.Documents;
            //打开文件
            Type docsType = docs.GetType();
            //Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true }); 
            Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(wordFileName);
            //转换格式,另存为
            Type docType = doc.GetType();
            string wordSaveFileName = wordFileName.ToString();
            string strSaveFileName = wordSaveFileName.Substring(0, wordSaveFileName.LastIndexOf(".")) + ".html";
            object saveFileName = (object)strSaveFileName;
            docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });
            docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
            //退出 Word
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
            return saveFileName.ToString();
        }
        #region 预览Excel
        /// <summary>
        /// 预览Excel
        /// </summary>
            public static string  PriviewExcel( string inFilePath)
            {
                Microsoft.Office.Interop.Excel.Application excel = null;
                Microsoft.Office.Interop.Excel.Workbook xls = null;
                excel = new Microsoft.Office.Interop.Excel.Application();
                object missing = Type.Missing;
                object trueObject = true;
                excel.Visible = false;
                excel.DisplayAlerts = false;

                string randomName = DateTime.Now.Ticks.ToString();  //output fileName

                xls = excel.Workbooks.Open(inFilePath, missing, trueObject, missing,
                                            missing, missing, missing, missing, missing, missing, missing, missing,
                                            missing, missing, missing);

                //Save Excel to Html
                object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
            string htmlName = Path.GetFileNameWithoutExtension(inFilePath) + ".html";
            String outputFile = Path.GetDirectoryName(inFilePath) + "\\" + htmlName;
            Workbook wsCurrent = xls;//(Workbook)wsEnumerator.Current;
                 wsCurrent.SaveAs(outputFile, format, missing, missing, missing,
                                  missing, XlSaveAsAccessMode.xlNoChange, missing,
                                  missing, missing, missing, missing);
                excel.Quit();
            return outputFile;
                //Open generated Html
                //Process process = new Process();
                //process.StartInfo.UseShellExecute = true;
                //process.StartInfo.FileName = outputFile;
                //process.Start();
            }

        #endregion
        public static string GetPathByDocToHTML(string strFile)
        {
            if (string.IsNullOrEmpty(strFile))
            {
                return "0";//没有文件
            }
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application()
            {
                Visible = false,
                AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable
            };
            //Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
            //  word.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
            Type wordType = word.GetType();
            Microsoft.Office.Interop.Word.Documents docs = word.Documents;

            // 打开文件
            Type docsType = docs.GetType();

            object fileName = strFile;

            Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open",
            System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true });

            // 转换格式,另存为html
            Type docType = doc.GetType();
            //给文件重新起名
            string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
            System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString();

            string strFileFolder = "/html/";
            DateTime dt = DateTime.Now;
            //以yyyymmdd形式生成子文件夹名
            string strFileSubFolder = dt.Year.ToString();
            strFileSubFolder += (dt.Month < 10) ? ("0" + dt.Month.ToString()) : dt.Month.ToString();
            strFileSubFolder += (dt.Day < 10) ? ("0" + dt.Day.ToString()) : dt.Day.ToString();
            string strFilePath = strFileFolder + strFileSubFolder + "/";
            // 判断指定目录下是否存在文件夹,如果不存在,则创建
            if (!Directory.Exists(strFilePath))
            {
                // 创建up文件夹
                Directory.CreateDirectory(strFilePath);
            }

            //被转换的html文档保存的位置
            // HttpContext.Current.Server.MapPath("html" + strFileSubFolder + filename + ".html")
            string ConfigPath = strFilePath + filename + ".html";
            object saveFileName = ConfigPath;

            /*下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成:
              * docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
              * null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML});
              * 其它格式:
              * wdFormatHTML
              * wdFormatDocument
              * wdFormatDOSText
              * wdFormatDOSTextLineBreaks
              * wdFormatEncodedText
              * wdFormatRTF
              * wdFormatTemplate
              * wdFormatText
              * wdFormatTextLineBreaks
              * wdFormatUnicodeText
            */
            docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
            null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });

            //docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
            //  null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });

            //关闭文档
            docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
            null, doc, new object[] { null, null, null });

            // 退出 Word
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
            //转到新生成的页面
            //return ("/" + filename + ".html");

            //转化HTML页面统一编码格式
            TransHTMLEncoding(ConfigPath);

            return (strFilePath + filename + ".html");
        }
        public static void TransHTMLEncoding(string strFilePath)
        {
            try
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(strFilePath, Encoding.GetEncoding(0));
                string html = sr.ReadToEnd();
                sr.Close();
                html = System.Text.RegularExpressions.Regex.Replace(html, @"<meta[^>]*>", "<meta http-equiv=Content-Type content='text/html; charset=gb2312'>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, false, Encoding.Default);

                sw.Write(html);
                sw.Close();
            }
            catch (Exception ex)
            {
              
            }
        }

    }
}