using System.Globalization;
using Xceed.Document.NET;
using Xceed.Words.NET;

namespace IRaCIS.Core.Application.Helper;

/// <summary>
/// 利用DocX 库 处理word国际化模板
/// </summary>
public static class WordTempleteHelper
{
    public static void DocX_GetInternationalTempleteStream(string filePath, Stream memoryStream)
    {

        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        using (DocX document = DocX.Load(filePath))
        {
            // 查找书签
            var bookmarkEn_Start = document.Bookmarks.FirstOrDefault(b => b.Name == StaticData.CultureInfo.en_US_bookMark);

            if (bookmarkEn_Start != null)
            {
                // 获取书签的起始位置
                //int bookmarkCNStartPos = bookmarkCn_Start.Paragraph.StartIndex;

                var bookmarkENStartPos = bookmarkEn_Start.Paragraph.StartIndex;

                // 创建一个要删除段落的列表
                List<Paragraph> paragraphsToRemove = new List<Paragraph>();

                foreach (var item in document.Paragraphs)
                {
                    //中文模板在前，英文在后，英文模板，就删除英文之前的，中文模板就删除英文之后的

                    if (isEn_US ? item.EndIndex < bookmarkENStartPos : item.StartIndex >= bookmarkENStartPos)
                    {
                        paragraphsToRemove.Add(item);
                    }
                }

                foreach (var paragraph in paragraphsToRemove)
                {
                    document.RemoveParagraph(paragraph);
                }

            }

            // 保存修改
            document.SaveAs(memoryStream);
        }
    }


    //public static void Npoi_GetInternationalTempleteStream(string filePath, Stream memoryStream)
    //{

    //    var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

    //    using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    //    {
    //        XWPFDocument doc = new XWPFDocument(fs);

    //        // 查找包含指定书签的段落及其索引
    //        var bookmarkParagraph = doc.Paragraphs
    //            .FirstOrDefault(p => p.GetCTP().GetBookmarkStartList().Any(b => b.name == StaticData.CultureInfo.en_US_bookMark));

    //        if (bookmarkParagraph != null)
    //        {
    //            int bookmarkIndex = doc.Paragraphs.IndexOf(bookmarkParagraph);

    //            if (isEn_US)
    //            {
    //                // 从书签所在段落开始，删除之前的所有段落
    //                for (int i = bookmarkIndex - 1; i >= 0; i--)
    //                {
    //                    doc.RemoveBodyElement(i);
    //                }
    //            }
    //            else
    //            {
    //                // 删除书签之后的所有段落
    //                for (int i = doc.Paragraphs.Count - 1; i >= bookmarkIndex; i--)
    //                {
    //                    doc.RemoveBodyElement(i);
    //                }
    //            }
    //        }
    //        doc.Write(memoryStream);
    //    }
    //}

}
