
using System;
using System.Drawing;
using AIProofread;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word;
using Bookmark = Microsoft.Office.Tools.Word.Bookmark;

namespace UtilLib
{

    public class ProofreadItem
    {
        public Bookmark mark;
        public string OriginSentence { get; set; }
        public CorrectItem content;
        public float originSize;
        public WdColor originColor;
        public WdColor originBackgroundColor;
        public string Name { get; set; }
        public int DocumentId { get; set; }

        public ProofreadItem(CorrectItem content, string originSentence, int documentId)
        {
            this.content = content;
            this.DocumentId = documentId;
            this.OriginSentence = originSentence;
            InitBookMark(null);
            SetMarkName();
        }

        private void SetMarkName()
        {
            this.Name = this.mark != null ? mark.Name : Config.BuildBookmarkName(content.Id);
        }

        public ProofreadItem(CorrectItem content, string originSentence, Bookmark bookmark, int documentId)
        {
            this.DocumentId = documentId;
            this.OriginSentence = originSentence;
            this.content = content;
            if (bookmark != null)
            {
                this.mark = bookmark;
                // 记录目前字体
                originSize = bookmark.Range.Font.Size;
                originBackgroundColor = bookmark.Shading.BackgroundPatternColor;
                originColor = bookmark.Shading.ForegroundPatternColor;
                //mark.Selected += OnMarkSelected;
            }
            SetMarkName();
            //InitBookMark(bookmark);
        }

        private void InitBookMark(Bookmark bookmark)
        {
            // 创建mark
            this.mark = bookmark != null ? bookmark
                : DocumentUtil.AddBookmark(content.Tag == "i" ? null : content.Color, content.Start, content.End);
            if (mark != null)
            {
                // 记录目前字体
                originSize = mark.Range.Font.Size;
                // 设置名称
                mark.Name = Config.BuildBookmarkName(content.Id);
            }
        }

        private void OnMarkSelectionChange(object sender, Microsoft.Office.Tools.Word.SelectionEventArgs e)
        {
            //throw new System.NotImplementedException();
            //mark.Range.Font.Size = originSize;
            //Console.WriteLine("xxx");
        }

        private void OnMarkSelected(object sender, Microsoft.Office.Tools.Word.SelectionEventArgs e)
        {
            //throw new System.NotImplementedException();
            Bridge.bridge.SelectMarkById(content.Id, DocumentId);
        }

        public void Select()
        {
            if (mark == null) return;
            mark.Range.Font.Size = originSize + 2; // 将选中标签文本放大字体
            //mark.Select();

        }
        public void UnSelect()
        {
            try
            {
                if (mark == null) return;
                mark.Range.Font.Size = originSize; // 还原
                mark.Shading.ForegroundPatternColor = originColor;
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }
        }

        private void SetMarkStyle()
        {
            try
            {
                if (mark == null) return;

                // 颜色转码
                var color = (WdColor)ColorTranslator.ToOle(Colors.FromHex(Config.TextBackgroundColor));
                // 给选区添加背景颜色
                mark.Shading.BackgroundPatternColor = color;
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }
        }

        public void ResetMarkStyle()
        {
            if (mark == null) return;
            if (mark.Range == null) return;
            try
            {
                mark.Range.Font.Size = originSize; // 还原
                //mark.Range.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
                //originBackgroundColor = bookmark.Shading.BackgroundPatternColor;
                mark.Shading.ForegroundPatternColor = originColor;
                mark.Range.Shading.BackgroundPatternColor = originColor;// Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }
        }
        private void PrepareCommentProcess(Bookmark mark)
        {
            var doc = Globals.ThisAddIn.Application.ActiveDocument;
            var fullRange = doc.Range();

            var range = mark.Range;
            var checkRange = doc.Range(
                Math.Max(range.Start - 2, fullRange.Start),
                Math.Min(range.End + 2, fullRange.End)
                );
            var comments = checkRange.Comments;
            // 判断当前书签选区内容是否有评论
            if (comments != null && comments.Count > 0)
            {
                Logger.Log("有批注");
                foreach (Microsoft.Office.Interop.Word.Comment item in comments)
                {
                    // 判断当前评论和书签选区是否一致
                    if (item.Scope.Start == range.Start && item.Scope.End == range.End)
                    {
                        Logger.Log("删除批注:" + item.Range.Text);
                        // 删除评论
                        item.Delete();
                    }
                }
            }
        }

        /// <summary>
        /// 处理校对项
        /// </summary>
        /// <param name="status"></param>
        public void Process(int status)
        {

            if (mark == null) return;
            // 
            content.IsAccept = status;
            // 采纳
            if (status == AcceptStatus.Accept)
            {
                PrepareCommentProcess(mark);
                if (content.Tag == "r" || content.Tag == "i")
                {
                    mark.Text = content.Text;
                }
                else if (content.Tag == "d")
                {
                    mark.Text = "";
                }
                ResetMarkStyle();
            } // 复核 或者 忽略
            else if (status == AcceptStatus.Review || status == AcceptStatus.Ignore)
            {
                ResetMarkStyle();
                // 新增添加了空格 所以当忽略时还原
                if (content.Tag == "i")
                {
                    mark.Text = "";
                }
            }
            // 撤销处理
            else if (status == AcceptStatus.Default)
            {
                // 撤销
                if (content.Tag == "r" || content.Tag == "d")
                {
                    mark.Text = content.Origin;
                }
                else if (content.Tag == "i")
                {
                    mark.Text = ToolUtil.GetBlankText(content.Text.Length);
                }
                SetMarkStyle();
            }
            // 处理由于批注导致出现百分号
            AfterMarkTextChanged(mark);
        }

        private void AfterMarkTextChanged(Bookmark mark)
        {
            // 获取标签所在段落最后的位置
            var paragraphEnd = mark.Paragraphs.Last.Range.End;
            var end = mark.End + 2 > paragraphEnd ? paragraphEnd : mark.End + 2;
            var rng = Globals.ThisAddIn.ActiveDocument.Range(mark.End, end);

            // 判断书签范围内是否有批注

            if (rng.Text?.IndexOf("%") != -1)
            {
                Logger.Log($"处理百分号问题:有批注");
                if (rng.Comments != null && rng.Comments.Count > 0)
                {
                    for (var i = 1; i < rng.Comments.Count; i++)
                    {
                        var comment = rng.Comments[i];
                        comment.Scope.Text = comment.Scope.Text.Replace("%", "");
                    }
                }
                else
                {
                    rng.Text = rng.Text.Replace("%", "");
                }
            }
        }
    }
}
