using OfficeAppHelp.Word;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Text;
using QuestionSwapDoc.SwapWordModel;
using System.Linq;
using System.IO;
using QuestionSwapDoc.Help;
using QuestionSwapDoc.SwapQuestionModel;
using OfficeAppHelp.Help;

namespace QuestionSwapDoc
{
    /// <summary>
    /// 输出为文档
    /// </summary>
    public class SwapWord
    {
        /// <summary>
        /// 创建试卷、答案、解析、答题卡
        /// </summary>
        /// <param name="saveDirectory">保存文件夹的绝对路径</param>
        /// <param name="queConfig">试卷配置（为null则返回空数据）</param>
        /// <param name="daAnConfig">答案解析配置（为null表示没有答案解析）</param>
        /// <param name="daTiKaConfig">答题卡配置（为null表示没有答题卡）</param>
        /// <param name="ques">试题集合（为null则返回空数据）</param>
        public static List<SwapWordCreateQueResult> CreateQue(string saveDirectory, SwapQueConfig queConfig, SwapDaAnConfig daAnConfig, SwapDaTiKaConfig daTiKaConfig, SwapTiXins ques)
        {
            List<SwapWordCreateQueResult> swapWordResults = new List<SwapWordCreateQueResult>();
            if (queConfig == null || ques == null || ques.TiXinList == null || !ques.TiXinList.Any())
                return swapWordResults;

            WordApp wordApp = new WordApp();
            if (queConfig.ZhiZhangDaXiao == PaperQue.A4竖向)
                wordApp.NewDoc();
            else
            {
                wordApp.NewDoc(WdPaperSize.wdPaperA3, WdOrientation.wdOrientLandscape);
                //分栏
                var textColumns = wordApp.Doc.PageSetup.TextColumns;
                textColumns.SetCount(2);
                textColumns.Spacing = 42;
            }

            //储存文档默认样式
            var rangeDocStyte = wordApp.Doc.RangeEnd();
            var docLineUnitAfter = rangeDocStyte.ParagraphFormat.LineUnitAfter;
            var docLineUnitBefore = rangeDocStyte.ParagraphFormat.LineUnitBefore;
            var docFontSize = rangeDocStyte.Font.Size;
            var docFontBold = rangeDocStyte.Font.Bold;
            var docFontColor = rangeDocStyte.Font.Color;

            #region 生成试卷
            //设置试卷头部
            if (queConfig.ZhuBiaoTi != null)
            {
                var range = wordApp.Doc.RangeEnd();
                range.Text = queConfig.ZhuBiaoTi;
                range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                range.ParagraphFormat.LineUnitAfter = 0.25f;
                range.Font.Size = 12;
                range.Font.Bold = -1;
                range.InsertParagraphAfter();
            }
            if (queConfig.FuBiaoTi != null)
            {
                var range = wordApp.Doc.RangeEnd();
                range.Text = queConfig.FuBiaoTi;
                range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                range.ParagraphFormat.LineUnitAfter = 0.25f;
                range.Font.Size = 14;
                range.Font.Bold = -1;
                range.InsertParagraphAfter();
            }
            if (queConfig.ShiTiXinXi != null)
            {
                var range = wordApp.Doc.RangeEnd();
                range.Text = queConfig.ShiTiXinXi;
                range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                range.ParagraphFormat.LineUnitAfter = 0.25f;
                range.Font.Size = 10;
                range.Font.Bold = 0;
                range.InsertParagraphAfter();
            }
            if (queConfig.KaoShengShuRu != null)
            {
                var range = wordApp.Doc.RangeEnd();
                range.Text = queConfig.KaoShengShuRu;
                range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                range.ParagraphFormat.LineUnitAfter = 0.25f;
                range.Font.Size = 10;
                range.Font.Bold = 0;
                range.InsertParagraphAfter();
            }
            if (queConfig.ZhuYiShiXian != null)
            {
                var range = wordApp.Doc.RangeEnd();
                range.Text = queConfig.ZhuYiShiXian;
                range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                range.ParagraphFormat.LineUnitAfter = 0.25f;
                range.Font.Color = WdColor.wdColorGray60;
                range.Font.Size = 10;
                range.Font.Bold = 0;
                range.InsertParagraphAfter();
            }
            if (queConfig.IsFenJuan)
            {
                var range = wordApp.Doc.RangeEnd();
                range.Text = "第Ⅰ卷";
                range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                range.ParagraphFormat.LineUnitBefore = 0.25f;
                range.ParagraphFormat.LineUnitAfter = 0.25f;
                range.ParagraphFormat.Shading.BackgroundPatternColor = WdColor.wdColorGray15;
                range.Font.Color = WdColor.wdColorBlack;
                range.Font.Size = 14;
                range.Font.Bold = 0;
                range.InsertParagraphAfter();
            }

            //还原样式
            var rangeEnd = wordApp.Doc.RangeEnd();
            rangeEnd.ParagraphFormat.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
            rangeEnd.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
            rangeEnd.ParagraphFormat.LineUnitBefore = docLineUnitBefore;
            rangeEnd.ParagraphFormat.LineUnitAfter = docLineUnitAfter;
            rangeEnd.Font.Color = docFontColor;
            rangeEnd.Font.Size = docFontSize;
            rangeEnd.Font.Bold = docFontBold;

            //添加题
            ques.UpdateNumber();
            ques.QueHtmlContentToFile();
            foreach (var tiXin in ques.TiXinList)
            {
                var range = wordApp.Doc.RangeEnd();
                //分卷
                if (queConfig.IsFenJuan && !tiXin.IsPanDuan && !tiXin.IsXuanZhe)
                {
                    range.InsertBreak(WdBreakType.wdPageBreak);
                    range.Text = "第Ⅱ卷";
                    range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    range.ParagraphFormat.LineUnitBefore = 0.25f;
                    range.ParagraphFormat.LineUnitAfter = 0.25f;
                    range.ParagraphFormat.Shading.BackgroundPatternColor = WdColor.wdColorGray15;
                    range.Font.Color = WdColor.wdColorBlack;
                    range.Font.Size = 14;
                    range.Font.Bold = 0;
                    range.InsertParagraphAfter();
                    //还原样式
                    rangeEnd = wordApp.Doc.RangeEnd();
                    rangeEnd.ParagraphFormat.Shading.BackgroundPatternColorIndex = WdColorIndex.wdNoHighlight;
                    rangeEnd.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    rangeEnd.ParagraphFormat.LineUnitBefore = docLineUnitBefore;
                    rangeEnd.ParagraphFormat.LineUnitAfter = docLineUnitAfter;
                    rangeEnd.Font.Color = docFontColor;
                    rangeEnd.Font.Size = docFontSize;
                    rangeEnd.Font.Bold = docFontBold;
                }
                //添加题型文本
                var fentxtxt = tiXin.GetFenStr(queConfig.IsFen);
                range.InsertAfter(tiXin.NumberStr + tiXin.TiXinStr + fentxtxt);
                range.InsertParagraphAfter();
                foreach (var que in tiXin.QueList)
                {
                    var fenttxt = tiXin.GetFenStr(string.IsNullOrEmpty(fentxtxt));
                    range.InsertAfter(que.NumberStr + " " + fenttxt);
                    var upath = que.TiRange.GetUseFile();
                    if (File.Exists(upath))
                    {
                        range = wordApp.Doc.RangeEnd();
                        range.InsertFile(upath);
                    }
                    else
                    {
                        range.InsertParagraphAfter();
                    }
                }
            }
            AddZhuanDinXian(wordApp.Doc, queConfig.ZhuanDinXian);
            #endregion

            #region 生成答案
            if (daAnConfig != null || daAnConfig.IsShowDaAn || daAnConfig.IsShowJieXi)
            {
                SwapWordResultType swapWordResultType;
                //答案是否在新的文档中
                if (!daAnConfig.IsInQue)
                {
                    //保存试卷
                    swapWordResults.Add(new SwapWordCreateQueResult()
                    {
                        resultType = SwapWordResultType.试卷,
                        Path = DocSaveToDirectory(wordApp.Doc, saveDirectory)
                    });
                    wordApp.Close();
                    wordApp.NewDoc();

                    swapWordResultType = SwapWordResultType.答题卡;
                }
                else
                {
                    var rangeBreak = wordApp.Doc.RangeEnd();
                    rangeBreak.InsertBreak(WdBreakType.wdPageBreak);

                    swapWordResultType = SwapWordResultType.试卷和答案解析;
                }

                //添加标题
                if (daAnConfig.Title != null)
                {
                    //标题范围
                    var rangeTou = wordApp.Doc.RangeEnd();
                    //储存值
                    docFontSize = rangeTou.Font.Size;
                    //设置值
                    rangeTou.Text = daAnConfig.Title;
                    rangeTou.Font.Size = 22;
                    rangeTou.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    //换行、还原值
                    rangeTou.InsertParagraphAfter();
                    rangeTou = wordApp.Doc.RangeEnd();
                    rangeTou.Font.Size = docFontSize;
                    rangeTou.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                }

                //添加答案
                AddDaAn(wordApp.Doc, daAnConfig, ques);
                //保存答案解析或试卷
                swapWordResults.Add(new SwapWordCreateQueResult()
                {
                    resultType = swapWordResultType,
                    Path = DocSaveToDirectory(wordApp.Doc, saveDirectory)
                });
                wordApp.Close();
            }

            //还原，清理文件
            ques.QueHtmlFileToContent();
            #endregion

            #region 生成答题卡
            if (daTiKaConfig != null && ques != null && ques.TiXinList != null)
            {
                if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A4竖向)
                {
                    wordApp.NewDoc();
                }
                else if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向)
                {
                    wordApp.NewDoc(WdPaperSize.wdPaperA3, WdOrientation.wdOrientLandscape);
                    //分栏
                    var textColumns = wordApp.Doc.PageSetup.TextColumns;
                    textColumns.SetCount(2);
                }
                else if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向3)
                {
                    wordApp.NewDoc(WdPaperSize.wdPaperA3, WdOrientation.wdOrientLandscape);
                    //分栏
                    var textColumns = wordApp.Doc.PageSetup.TextColumns;
                    textColumns.SetCount(3);
                }

                //添加定位
                AddDtkDinWei(wordApp.Doc);
                //添加头部信息
                AddDtkTou(wordApp.Doc, daTiKaConfig);
                //添加答题区域
                AddDtkNeiRong(wordApp.Doc, daTiKaConfig, ques);

                //保存答题卡
                swapWordResults.Add(new SwapWordCreateQueResult()
                {
                    resultType = SwapWordResultType.答题卡,
                    Path = DocSaveToDirectory(wordApp.Doc, saveDirectory)
                });
                wordApp.Close();
            }
            #endregion

            return swapWordResults;
        }

        /// <summary>
        /// 合并试题
        /// </summary>
        /// <param name="fileName">文件的绝对路径（如"D:\word.docx"）</param>
        /// <returns></returns>
        public static void JoinQue(string fileName, SwapWordJoinQueItem swapWordJoinQueItem)
        {
            JoinQue(fileName, new List<SwapWordJoinQueItem>() { swapWordJoinQueItem } );
        }

        /// <summary>
        /// 合并试题
        /// </summary>
        /// <param name="fileName">文件的绝对路径（如"D:\word.docx"）</param>
        /// <returns></returns>
        public static void JoinQue(string fileName, List<SwapWordJoinQueItem> swapWordJoinQueItems)
        {
            WordApp wordApp = null;
            try
            {
                wordApp = new WordApp();
                wordApp.NewDoc();
                SwapWordJoinQueItem.QueHtmlContentToFile(swapWordJoinQueItems);
                foreach (var item in swapWordJoinQueItems)
                {
                    if (item.TiRange != null && !item.TiRange.IsNull)
                    {
                        if (!string.IsNullOrWhiteSpace(item.Data))
                            wordApp.Doc.Content.InsertAfter($"【题编码信息】{item.Data.ToBase64()}\r\n\r\n");
                        if (!string.IsNullOrWhiteSpace(item.TiXinStr))
                            wordApp.Doc.Content.InsertAfter($"题型：{item.TiXinStr}\r\n\r\n");

                        //添加题
                        wordApp.Doc.Content.InsertParagraphAfter();
                        wordApp.Doc.RangeEnd().InsertFile(item.TiRange.GetUseFile());
                        if (item.DaAnRange != null && !item.DaAnRange.IsNull)
                        {
                            if (item.IsXuanZhe)
                            {
                                wordApp.Doc.ParagraphEndCount(1);
                                wordApp.Doc.Content.InsertAfter($"答案：{item.DaAnRange.HtmlText}");
                                wordApp.Doc.Content.InsertParagraphAfter();
                            }
                            else if (item.IsPanDuan)
                            {
                                if (bool.TryParse(item.DaAnRange.HtmlText, out bool jgbool))
                                {
                                    wordApp.Doc.ParagraphEndCount(1);
                                    wordApp.Doc.Content.InsertAfter($"答案：" + (jgbool ? "正确" : "错误"));
                                    wordApp.Doc.Content.InsertParagraphAfter();
                                }
                            }
                            else
                            {
                                wordApp.Doc.Content.InsertAfter($"答案：");
                                wordApp.Doc.RangeEnd().InsertFile(item.DaAnRange.GetUseFile());
                            }
                        }
                        if (item.JieXiRange != null && !item.JieXiRange.IsNull)
                        {
                            wordApp.Doc.Content.InsertAfter("解析：");
                            wordApp.Doc.RangeEnd().InsertFile(item.JieXiRange.GetUseFile());
                        }
                        wordApp.Doc.Content.InsertParagraphAfter();
                    }
                }
                wordApp.Save(fileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                SwapWordJoinQueItem.QueHtmlFileToContent(swapWordJoinQueItems);
                wordApp?.Close();
            }
        }

        /// <summary>
        /// html文本转为word文件
        /// </summary>
        /// <param name="fileName">文件的绝对路径（如"D:\word.docx"）</param>
        /// <param name="htmlText">html文本</param>
        /// <param name="imgLinkLeftPath">网页中的图片的左边的路径（和图片路径拼接成绝对路径）</param>
        /// <returns></returns>
        public static void HtmlToWord(string fileName, string htmlText, string imgLinkLeftPath = "")
        {
            var htmlpath = Path.GetFullPath(Path.GetRandomFileName().Replace(".", "") + ".html");
            File.WriteAllText(htmlpath, HttpHelp.AddLeftLinkPath(htmlText, imgLinkLeftPath), Encoding.UTF8);
                WordApp wordApp = new WordApp();
            try
            {
                wordApp.NewDoc();
                wordApp.Doc.Content.InsertFile(htmlpath);
                wordApp.Save(fileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                wordApp?.Close();
                if (File.Exists(htmlpath))
                    File.Delete(htmlpath);
            }
        }

        /// <summary>
        /// word文件转为html文本
        /// </summary>
        /// <param name="fileName">文件的绝对路径（如"D:\word.docx"）</param>
        /// <param name="linkDirectory">html关联文件文件夹（文件名称md5方式）【为空为文档名加parse，如："D:\wordparse"】</param>
        /// <param name="imgLinkLeftPath">html中img中src的前缀【为空：[img src='md5.png']；假如为‘imgfiles’：[img src='imgfiles\md5.png']】</param>
        /// <returns>Html内容</returns>
        public static string WordToHtml(string fileName, string linkDirectory = "", string imgLinkLeftPath = "")
        {
            var p1 = Path.GetDirectoryName(fileName);//D:\
            var p2 = Path.GetFileNameWithoutExtension(fileName) + "parse";//wordparse
            var p3 = Path.Combine(p1, p2);//D:\wordparse
            if (string.IsNullOrWhiteSpace(linkDirectory))
                linkDirectory = p3;

            WordApp wordApp = null;
            string html = string.Empty;
            try
            {
                Directory.CreateDirectory(linkDirectory);

                wordApp = new WordApp(fileName, true, "123");
                wordApp.Doc.Content.SetColor(WdColor.wdColorBlack);
                wordApp.Doc.Content.Replace(WordApp.Find_BlankRow, WordApp.Find_Paragraph);
                wordApp.Doc.Content.Replace(WordApp.Find_Tab, "    ");//为了兼容性
                html = QueItemRange.FillHtml(wordApp.Doc.Content, linkDirectory, imgLinkLeftPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                wordApp?.Close();
            }
            return html;
        }

        /// <summary>
        /// 填充装订线(支持A3，A4)
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="zhuanDinXian"></param>
        private static void AddZhuanDinXian(Document doc, ZhuanDinXian zhuanDinXian)
        {
            if (zhuanDinXian == null || !zhuanDinXian.IsShow)
                return;

            bool isA4 = doc.PageSetup.PaperSize == WdPaperSize.wdPaperA4;
            float widthGutter = 15;//装订线的多余宽度

            //装订线的多余宽度
            doc.PageSetup.Gutter = widthGutter;
            if (zhuanDinXian.IsDuplexPrinting)
                doc.PageSetup.MirrorMargins = -1;

            float widthGutterTop = 10;//装订线的上下间距
            float widthGutterLeft = 10;//装订线的纸张边外侧间距
            float widthGutterRight = 17;//装订线的纸张边内侧间距
            float width = doc.PageSetup.PageWidth;//页面宽度
            float widthLeft = doc.PageSetup.LeftMargin;//纸张内侧宽度
            float height = doc.PageSetup.PageHeight;//页面高度

            //当前页码
            int pageNum = 1;
            foreach (var pRange in doc.GetPageRanges())
            {

                //是否为偶数页
                var IsOdd = !((pageNum % 2) == 1);
                if (zhuanDinXian.IsDuplexPrinting && IsOdd)
                {
                    var shape = doc.Shapes.AddTextbox(
                         MsoTextOrientation.msoTextOrientationVerticalFarEast,
                         width - widthLeft - widthGutter + widthGutterRight,
                         widthGutterTop,
                         (widthGutter + widthLeft) - (widthGutterLeft + widthGutterRight),
                         height - (widthGutterTop * 2),
                         pRange);

                    //字体居中竖向显示
                    shape.TextFrame.Orientation = MsoTextOrientation.msoTextOrientationDownward;
                    shape.TextFrame.TextRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    shape.TextFrame.TextRange.ParagraphFormat.LineUnitAfter = 0f;
                    if (!zhuanDinXian.IsShowLine)
                        shape.Line.Visible = MsoTriState.msoFalse;

                    //文本区域
                    var textRange = shape.TextFrame.TextRange;
                    //添加文本
                    if (isA4)
                        textRange.InsertParagraphAfter();
                    textRange.InsertParagraphAfter();
                    textRange.InsertParagraphAfter();
                    textRange.InsertAfter(zhuanDinXian.GetAlurSplitText());
                }
                else
                {
                    var shape = doc.Shapes.AddTextbox(
                        MsoTextOrientation.msoTextOrientationVerticalFarEast,
                        widthGutterLeft,
                        widthGutterTop,
                        (widthGutter + widthLeft) - (widthGutterLeft + widthGutterRight),
                        height - (widthGutterTop * 2),
                        pRange);

                    //字体居中竖向显示
                    shape.TextFrame.Orientation = MsoTextOrientation.msoTextOrientationUpward;
                    shape.TextFrame.TextRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    shape.TextFrame.TextRange.ParagraphFormat.LineUnitAfter = 0f;
                    if (!zhuanDinXian.IsShowLine)
                        shape.Line.Visible = MsoTriState.msoFalse;

                    //文本区域
                    var textRange = shape.TextFrame.TextRange;
                    if (isA4)
                        textRange.InsertParagraphAfter();
                    if (pageNum == 1 || zhuanDinXian.IsNewPageShowWriteText)
                    {
                        //添加文本
                        textRange.InsertAfter(zhuanDinXian.WriteText);
                        textRange.InsertParagraphAfter();
                        textRange.InsertParagraphAfter();
                        textRange.InsertAfter(zhuanDinXian.GetAlurSplitText());
                    }
                    else
                    {
                        //添加文本
                        textRange.InsertParagraphAfter();
                        textRange.InsertParagraphAfter();
                        textRange.InsertAfter(zhuanDinXian.GetAlurSplitText());
                    }

                }
                pageNum++;
            }

        }
        /// <summary>
        /// 添加答案
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="daAnConfig"></param>
        /// <param name="ques"></param>
        private static void AddDaAn(Document doc, SwapDaAnConfig daAnConfig, SwapTiXins ques)
        {
            //题型
            foreach (var tiXin in ques.TiXinList)
            {
                var range = doc.RangeEnd();
                range.InsertAfter(tiXin.NumberStr + tiXin.TiXinStr);
                range.InsertParagraphAfter();
                //题
                foreach (var que in tiXin.QueList)
                {
                    range.InsertAfter(que.NumberStr + " ");
                    //添加答案
                    if (daAnConfig.IsShowDaAn)
                    {
                        range.InsertAfter("答案：");
                        if (string.IsNullOrWhiteSpace(que.DaAnRange.GetUseFile()))
                        {
                            range.InsertAfter(daAnConfig.DaAnNullStr);
                            range.InsertParagraphAfter();
                        }
                        else if (tiXin.IsXuanZhe)
                        {
                            range.InsertAfter(que.DaAnRange.HtmlText);
                            range.InsertParagraphAfter();
                        }
                        else if (tiXin.IsPanDuan)
                        {
                            var t = bool.TryParse(que.DaAnRange.HtmlText, out bool t2);
                            if (t)
                            {
                                var t3 = t2 ? daAnConfig.PanDuanTrueShowStr : daAnConfig.PanDuanFalseShowStr;
                                range.InsertAfter(t3);
                                range.InsertParagraphAfter();
                            }
                        }
                        else
                        {
                            var upath = que.DaAnRange.GetUseFile();
                            if (File.Exists(upath))
                            {
                                range = doc.RangeEnd();
                                range.InsertFile(upath);
                            }
                            else
                            {
                                range.InsertParagraphAfter();
                            }
                        }
                    }
                    //添加解析
                    if (daAnConfig.IsShowJieXi)
                    {
                        range.InsertAfter("解析：");

                        var upath = que.JieXiRange.GetUseFile();
                        if (File.Exists(upath))
                        {
                            range = doc.RangeEnd();
                            range.InsertFile(upath);
                        }
                        else
                        {
                            range.InsertAfter(daAnConfig.JieXiNullStr);
                            range.InsertParagraphAfter();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 给答题卡添加定位
        /// </summary>
        /// <param name="Doc"></param>
        private static void AddDtkDinWei(Document Doc)
        {
            var range = Doc.RangeEnd();
            foreach (Section section in Doc.Sections)
            {
                #region 页眉
                //页眉
                range = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                var headerTable = range.Tables.Add(range, 2, 3);
                headerTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
                headerTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleNone;
                //字体大小
                headerTable.Range.Font.Size = 11;
                //range.set_Style("正文");//ms office存在样式问题，使用set_Style解决
                //样式对齐
                foreach (Row row in headerTable.Rows)
                {
                    row.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;
                    foreach (Cell cell in row.Cells)
                    {
                        if (cell.ColumnIndex == 1)
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                        else if (cell.ColumnIndex == 2)
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                        else if (cell.ColumnIndex == 3)
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                    }
                }
                //添加定位块
                headerTable.Cell(1, 1).Range.Text = "       ■";
                headerTable.Cell(2, 1).Range.Text = "▅";
                headerTable.Cell(2, 2).Range.Text = "▅";
                headerTable.Cell(2, 3).Range.Text = "▅     ▅";
                //表格悬浮
                headerTable.Rows.WrapAroundText = 1;
                headerTable.Rows.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
                headerTable.Rows.VerticalPosition = Doc.PageSetup.TopMargin - 30;
                //headerTable.Rows.HorizontalPosition = 90;
                #endregion

                #region 页脚
                //页脚
                range = section.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                var footerTable = range.Tables.Add(range, 2, 3);
                footerTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
                footerTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleNone;
                //字体大小
                footerTable.Range.Font.Size = 11;
                //样式对齐
                foreach (Row row in footerTable.Rows)
                {
                    row.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;
                    foreach (Cell cell in row.Cells)
                    {
                        if (cell.ColumnIndex == 1)
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                        else if (cell.ColumnIndex == 2)
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                        else if (cell.ColumnIndex == 3)
                            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                    }
                }
                //添加定位块
                footerTable.Cell(1, 1).Range.Text = "■";
                footerTable.Cell(1, 2).Range.Text = "▅";
                footerTable.Cell(1, 3).Range.Text = "▅     ▅";
                footerTable.Cell(2, 1).Range.Text = "       ■";
                //表格悬浮
                footerTable.Rows.WrapAroundText = 1;
                footerTable.Rows.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
                footerTable.Rows.VerticalPosition = Doc.PageSetup.PageHeight - Doc.PageSetup.BottomMargin;
                //footerTable.Rows.HorizontalPosition = 90;
                #endregion

            }
        }
        /// <summary>
        /// 给答题卡添加头部信息
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="daTiKaConfig"></param>
        private static void AddDtkTou(Document doc, SwapDaTiKaConfig daTiKaConfig)
        {
            var range = doc.RangeEnd();
            range.Font.Size = daTiKaConfig.WordFontSize;
            var rangeFontSize = range.Font.Size;

            //二维码区域
            if (daTiKaConfig.IsErWeiMa)
            {
                int shu = 2;
                int hen = (daTiKaConfig.ZhuBiaoTi == null || daTiKaConfig.FuBiaoTi == null) ? 1 : 2;
                var table = doc.Tables.Add(range, hen, shu, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
                table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleNone;
                //调整宽度
                var tWidth = table.GetWidth();
                table.Columns[1].Width = 0.3f * tWidth;
                table.Columns[2].Width = 0.7f * tWidth;
                if (hen == 1)
                    table.Rows.Height = 50;
                else
                    table.Columns[1].Cells.Merge();
                //虚线框
                table.Columns[1].Borders.OutsideLineStyle = WdLineStyle.wdLineStyleDot;
                table.Columns[1].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                table.Columns[2].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                //二维码粘贴区
                var ewmRange = table.Cell(1, 1).Range;
                ewmRange.Text = "二维码\r\n粘贴区";
                ewmRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                ewmRange.Font.Size = 12;
                ewmRange.Font.Color = WdColor.wdColorGray50;

                //主副标题
                if ((daTiKaConfig.ZhuBiaoTi == null && daTiKaConfig.FuBiaoTi == null) || daTiKaConfig.ZhuBiaoTi != null)
                {
                    range = table.Cell(1, 2).Range;
                    range.Text = daTiKaConfig.ZhuBiaoTi ?? "答题卡";
                    range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    range.Font.Size = 13;
                    range.Font.Bold = -1;
                }
                if (hen == 2 && daTiKaConfig.FuBiaoTi != null)
                {
                    range = table.Cell(2, 2).Range;
                    range.Text = daTiKaConfig.FuBiaoTi;
                    range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    range.Font.Size = 12;
                    range.Font.Bold = 0;
                }
                range = doc.RangeEnd();
                range.InsertParagraphAfter();
            }
            else
            {
                //主副标题
                if (daTiKaConfig.ZhuBiaoTi != null)
                {
                    range = doc.RangeEnd();
                    range.Text = daTiKaConfig.ZhuBiaoTi;
                    range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    range.Font.Size = 14;
                    range.Font.Bold = -1;
                    range.InsertParagraphAfter();
                }
                if (daTiKaConfig.FuBiaoTi != null)
                {
                    range = doc.RangeEnd();
                    range.Text = daTiKaConfig.FuBiaoTi;
                    range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    range.Font.Size = 13;
                    range.Font.Bold = 0;
                    range.InsertParagraphAfter();
                }
            }

            //还原
            range = doc.RangeEnd();
            range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
            range.Font.Size = rangeFontSize;
            range.Font.Bold = 0;

            if (daTiKaConfig.DaTiKaType == DaTiKaStyle.机读卡)
            {
                //答题卡头
                var table = doc.Tables.Add(range, 7, 3, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                table.Rows.Height = 20;
                table.Rows[1].Height = 25;
                table.Rows[2].Height = 25;
                //文本对齐方式
                table.Columns[1].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                table.Columns[2].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                table.Columns[3].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                //表格宽度
                var tWidth = table.GetWidth();
                //调整列宽（按%）
                if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向3)
                {
                    table.Columns[1].Width = 0.15f * tWidth;
                    table.Columns[2].Width = 0.26f * tWidth;
                    table.Columns[3].Width = 0.59f * tWidth;
                }
                else if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向)
                {
                    table.Columns[1].Width = 0.15f * tWidth;
                    table.Columns[2].Width = 0.2f * tWidth;
                    table.Columns[3].Width = 0.65f * tWidth;
                }
                else
                {
                    table.Columns[1].Width = 0.15f * tWidth;
                    table.Columns[2].Width = 0.25f * tWidth;
                    table.Columns[3].Width = 0.6f * tWidth;
                }
                //第三列合并
                table.Columns[3].Cells.Merge();
                //第七排合并
                table.Cell(7, 1).Merge(table.Cell(7, 2));
                //填充内容
                table.Cell(1, 1).Range.Text = "姓    名：";
                table.Cell(2, 1).Range.Text = "班    级：";
                table.Cell(3, 1).Range.Text = "正确填涂：";
                table.Cell(4, 1).Range.Text = "错误填涂：";
                table.Cell(5, 1).Range.Text = "缺考标记：";
                table.Cell(6, 1).Range.Text = "违纪标记：";
                table.Cell(7, 1).Range.Text = "注意事项：\r\n" + daTiKaConfig.ZhuYiShiXian;
                table.Cell(3, 2).Range.Text = daTiKaConfig.TianTuTrue;
                table.Cell(3, 2).Range.Font.Size = 12;
                table.Cell(4, 2).Range.Text = daTiKaConfig.TianTuFlase;
                table.Cell(4, 2).Range.Font.Size = daTiKaConfig.TianTuFontSize;
                table.Cell(5, 2).Range.Text = "[  ]";
                table.Cell(5, 2).Range.Font.Size = daTiKaConfig.TianTuFontSize;
                table.Cell(6, 2).Range.Text = "[  ]";
                table.Cell(6, 2).Range.Font.Size = daTiKaConfig.TianTuFontSize;

                //准考证号
                var zkzhRange = table.Cell(1, 3).Range;
                zkzhRange.Text = "准考证号";
                zkzhRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                zkzhRange.InsertParagraphAfter();
                //新的范围
                zkzhRange.SetRange(zkzhRange.End - 1, zkzhRange.End);
                zkzhRange.Text = "1";//改变Range，预防在office中报错

                //表格大小（A4）
                int mixcount = 6;
                if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向)
                    mixcount = 8;
                else if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向3)
                    mixcount = 6;

                var sjsl = daTiKaConfig.ZhunKaoZhenHaoShu < mixcount ? mixcount : daTiKaConfig.ZhunKaoZhenHaoShu;//实际数量
                //表中表
                table = doc.Tables.Add(zkzhRange, 2, sjsl, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                table.Rows[1].Height = 20;
                table.Rows[1].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                sjsl -= daTiKaConfig.ZhunKaoZhenHaoShu;
                foreach (Cell cell in table.Rows[2].Cells)
                {
                    cell.Range.Font.Size = daTiKaConfig.TianTuFontSize;
                    if (sjsl > 0)
                    {
                        table.Cell(1, cell.ColumnIndex).Range.Text = "/";
                        cell.Range.Text = "[  ]\r\n[  ]\r\n[  ]\r\n[  ]\r\n[  ]\r\n[  ]\r\n[  ]\r\n[  ]\r\n[  ]\r\n[  ]";
                        sjsl--;
                    }
                    else
                        cell.Range.Text = "[ 0 ]\r\n[ 1 ]\r\n[ 2 ]\r\n[ 3 ]\r\n[ 4 ]\r\n[ 5 ]\r\n[ 6 ]\r\n[ 7 ]\r\n[ 8 ]\r\n[ 9 ]";
                }
            }
            else
            {
                range = doc.RangeEnd();
                range.Text = "姓名：___________ 班级：___________ 学号：___________";
                range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                range.Font.Size = 10;
                range.Font.Bold = 0;
                range.InsertParagraphAfter();
                //还原
                range = doc.RangeEnd();
                range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                range.Font.Size = rangeFontSize;
                range.Font.Bold = 0;
            }
        }
        /// <summary>
        /// 添加答题区域的内容
        /// </summary>
        private static void AddDtkNeiRong(Document Doc, SwapDaTiKaConfig daTiKaConfig, SwapTiXins ques)
        {
            var rangeDtkEnd = Doc.RangeEnd();
            foreach (var queTX in ques.TiXinList)
            {
                var fentxtxt = queTX.GetFenStr(daTiKaConfig.IsFen);
                rangeDtkEnd = Doc.RangeEnd();
                rangeDtkEnd.InsertParagraphAfter();
                rangeDtkEnd.InsertAfter(queTX.NumberStr + queTX.TiXinStr + fentxtxt);
                rangeDtkEnd.InsertParagraphAfter();
                rangeDtkEnd = Doc.RangeEnd();

                if (queTX.DaTiKaType == SwapTiXinDaTiKaType.不显示)
                    continue;

                //选择题,判断题
                if (queTX.IsXuanZhe || queTX.IsPanDuan)
                {
                    rangeDtkEnd.Font.Size = daTiKaConfig.TianTuFontSize;
                    if (daTiKaConfig.DaTiKaType == DaTiKaStyle.机读卡)
                    {
                        if (queTX.DaTiKaType == SwapTiXinDaTiKaType.竖向)
                        {
                            var lie = 15;
                            if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向)
                                lie = 20;

                            var hen = (int)Math.Ceiling((decimal)queTX.QueList.Count / (decimal)lie);

                            var table = Doc.Tables.Add(rangeDtkEnd, hen, lie, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                            foreach (Row item in table.Rows)
                            {
                                item.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                                foreach (Cell item2 in item.Cells)
                                {
                                    item2.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                                }
                            }
                            table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
                            table.AddText(queTX.GetDaTiKaJiDuKeGuanStr(true).ToArray());
                        }
                        else
                        {
                            var lie = 5;
                            //if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A4竖向 && !queTX.IsPanDuan)
                            //    lie = 5;
                            if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向3 && !queTX.IsPanDuan)
                                lie = 4;

                            var hen = (int)Math.Ceiling((decimal)queTX.QueList.Count / (decimal)lie);

                            var table = Doc.Tables.Add(rangeDtkEnd, hen, lie, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                            table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
                            table.AddText(queTX.GetDaTiKaJiDuKeGuanStr(false).ToArray());
                        }
                    }
                    //人阅卡
                    else
                    {
                        var lie = 5;
                        var hen = (int)Math.Ceiling((decimal)queTX.QueList.Count / (decimal)lie);

                        var table = Doc.Tables.Add(rangeDtkEnd, hen, lie, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                        table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
                        table.AddText(queTX.GetDaTiKaRenYueKeGuanStr().ToArray());
                    }
                    rangeDtkEnd.SetRange(rangeDtkEnd.End - 1, rangeDtkEnd.End);
                    rangeDtkEnd.Font.Size = daTiKaConfig.WordFontSize;
                }
                else
                {
                    if (queTX.DaTiKaType == SwapTiXinDaTiKaType.单排横线)
                    {
                        var table = Doc.Tables.Add(rangeDtkEnd, 1, 1, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                        table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;

                        var tableRange = table.Cell(1, 1).Range;
                        tableRange.Underline = WdUnderline.wdUnderlineSingle;
                        var kong1 = new string(' ', 60);
                        foreach (var item in queTX.QueList)
                        {
                            var fenttxt = item.GetFenStr(string.IsNullOrEmpty(fentxtxt));
                            tableRange.InsertAfter(item.NumberStr + fenttxt + kong1);
                            if (item != queTX.QueList.Last())
                            {
                                tableRange.InsertParagraphAfter();
                            }
                        }
                    }
                    else if (queTX.DaTiKaType == SwapTiXinDaTiKaType.多排横线)
                    {
                        foreach (var que in queTX.QueList)
                        {
                            var fenttxt = que.GetFenStr(string.IsNullOrEmpty(fentxtxt));
                            var table = Doc.Tables.Add(rangeDtkEnd, 1, 1, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                            var tableRange = table.Cell(1, 1).Range;
                            tableRange.Underline = WdUnderline.wdUnderlineSingle;//下划线
                            var kong1 = new string(' ', 350);
                            tableRange.Text = que.NumberStr + fenttxt + kong1 + ".";
                        }
                    }
                    else if (queTX.DaTiKaType == SwapTiXinDaTiKaType.多排正方形网格)
                    {
                        foreach (var que in queTX.QueList)
                        {
                            var fenttxt = que.GetFenStr(string.IsNullOrEmpty(fentxtxt));
                            rangeDtkEnd.Text = que.NumberStr + fenttxt;
                            rangeDtkEnd.InsertParagraphAfter();
                            rangeDtkEnd = Doc.RangeEnd();

                            //A4纸
                            var lie = 20;
                            var hen = 10;
                            var zhishu = "100字";

                            if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向3)
                            {
                                lie = 15;
                                hen = 12;
                                zhishu = "90字";
                            }
                            else if (daTiKaConfig.ZhiZhangDaXiao == PaperDaTiKa.A3横向)
                            {
                                lie = 25;
                                hen = 8;
                                zhishu = "100字";
                            }

                            var table = Doc.Tables.Add(rangeDtkEnd, hen, lie, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                            table.Rows.Height = table.Columns.Width;
                            foreach (Row item in table.Rows)
                            {
                                //偶数
                                if (item.Index % 2 != 1)
                                {
                                    item.HeightRule = WdRowHeightRule.wdRowHeightExactly;
                                    item.Height = 11.3f;
                                    item.Cells.Merge();

                                    if (item.Index == hen)
                                    {
                                        var cell1Range = item.Cells[1].Range;
                                        cell1Range.Text = zhishu;
                                        cell1Range.Font.Size = 6;
                                        cell1Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (var que in queTX.QueList)
                        {
                            var table = Doc.Tables.Add(rangeDtkEnd, 1, 1, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
                            table.Rows.Height = 120;

                            var fenttxt = que.GetFenStr(string.IsNullOrEmpty(fentxtxt));
                            rangeDtkEnd = table.Cell(1, 1).Range;
                            rangeDtkEnd.Text = que.NumberStr + fenttxt;
                            rangeDtkEnd = Doc.RangeEnd();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 保存到指定文件夹
        /// </summary>
        /// <param name="saveDirectory">保存文件夹</param>
        private static string DocSaveToDirectory(Document Doc, string saveDirectory)
        {
            Directory.CreateDirectory(saveDirectory);

            var name = Path.Combine(saveDirectory, Path.GetRandomFileName().Replace(".", "") + ".docx");
            Doc.SaveAs2(name, WdSaveFormat.wdFormatXMLDocument, AddToRecentFiles: false);
            return name;
        }

    }
}
