using Microsoft.Office.Tools.Ribbon;
using System;
using System.Diagnostics;
using AIProofread.Controls;
using UtilLib;
using Microsoft.Office.Interop.Word;
using AIProofread.Util;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AIProofread.core;
using System.Windows.Forms;
using AIProofread.Properties;
using System.Security.Policy;

namespace AIProofread
{
    public partial class Ribbon1
    {
        private bool IS_LOGIN = false;
        private Userinfo currentLoginUserinfo;

        private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {
            //btnLogin.Label = "用户\n登录";
            //btnLogout.Label = "退出\n登录";

            Globals.ThisAddIn.ribbon = this;
            ShowDebug();
        }

        /// <summary>
        /// 用于调试或测试
        /// </summary>
        public void ShowDebug()
        {
            if (Config.RUN_IN_DEBUG)
            {
                grpDebug.Visible = true;
            }
        }

        public void SetCommonBtnStatus(bool status)
        {
            // BtnProofreadAll.Enabled = status;
            menuProofreadList.Enabled = status;

            btnClear.Enabled = status;
            btnOpenLexicon.Enabled = status;
            btnSetting.Enabled = status;
            BtnUpdate.Enabled = status;
            btnLogin.Enabled = status;
            btnLogout.Enabled = status;
            ButtonLoadCache.Enabled = status;
            ButtonSaveCache.Enabled = status;
            menuSencenDect.Enabled = status;
            //BtnShowPanel.Enabled = status;
            BtnExportProofreadResult.Enabled = status;
        }
        public void SetBtnStatus(string key, bool status)
        {
            if (key == "proofread-status")
            {
                SetCommonBtnStatus(status);
            }
            else if (key == "view-panel")
            {
                BtnShowPanel.Enabled = status;
            }
            else if (key == "disable-by-upgrade")
            {
                SetCommonBtnStatus(status);
                BtnUpdate.Enabled = true;
                BtnShowPanel.Enabled = status;
            }
        }

        /// <summary>
        /// 初始化WPS相关功能(图标)
        /// </summary>
        public void InitWPS()
        {

            BtnProofreadAll.Image = AIProofread.Properties.Resources.icon_proofread_wps;
            menuProofreadList.Image = AIProofread.Properties.Resources.icon_proofread_wps;
            btnClear.Image = AIProofread.Properties.Resources.icon_clear_wps;
            btnOpenLexicon.Image = AIProofread.Properties.Resources.icon_book_wps;
            btnSetting.Image = AIProofread.Properties.Resources.icon_setting_wps;
            BtnGetContact.Image = AIProofread.Properties.Resources.icon_phone_wps;
            BtnUpdate.Image = AIProofread.Properties.Resources.icon_update_wps;
            btnLogin.Image = AIProofread.Properties.Resources.icon_user_wps;
            menuSencenDect.Image = AIProofread.Properties.Resources.icon_ai_robot_wps;
            btnLogout.Image = AIProofread.Properties.Resources.icon_logout_wps;
            // 缓存相关
            ButtonLoadCache.Image = AIProofread.Properties.Resources.icon_refresh_wps;
            ButtonSaveCache.Image = AIProofread.Properties.Resources.icon_save_wps;
            // 显示面板
            BtnShowPanel.Image = AIProofread.Properties.Resources.icon_panel_wps;
            // 导出校对结果
            BtnExportProofreadResult.Image = AIProofread.Properties.Resources.icon_export_wps;
            BtnShowManual.Image = AIProofread.Properties.Resources.icon_manual_wps;
        }

        public void ProcessLoginInfo(Userinfo userinfo)
        {
            if (userinfo == null) return;
            currentLoginUserinfo = userinfo;
            // 登录状态
            IS_LOGIN = true;
            // 切换登录状态
            ToggleLogin();
            LblNickname.Label = userinfo.nickname;
            LblDate.Label = userinfo.expiration;

            // 关闭所有登录窗口
            foreach (var item in Globals.ThisAddIn.LoginFormList)
            {
                try
                {
                    if (!item.IsDisposed)
                    {
                        item.Close();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(this.Name, ex);
                }
            }
            Globals.ThisAddIn.LoginFormList.Clear();
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        public void ProcessLogout()
        {
            IS_LOGIN = false;
            currentLoginUserinfo = null;
            ToggleLogin();
            Globals.ThisAddIn.HideAllPanel();
        }

        // 处理是否登录的展示
        private void ToggleLogin()
        {

            btnLogin.Visible = !IS_LOGIN;

            btnLogout.Visible = IS_LOGIN;
            //LblNickname.Visible = IS_LOGIN;
            //LblDate.Visible = IS_LOGIN;
        }

        // 弹出登录窗口
        private void btnLogin_Click(object sender, RibbonControlEventArgs e)
        {
            Bridge.bridge.ShowLoginForm(null);
        }

        // 注销登录
        private void btnLogout_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.ActiveDocument.ShowDialog(currentLoginUserinfo.phone + " 退出AI校对王？", "确定", "logout");

            //Globals.ThisAddIn.ShowDialog("退出AI校对王",)
            // 注销吧
            //Bridge.bridge.Logout(null);
            //Globals.ThisAddIn.HideAllPanel();

            //Globals.ThisAddIn.SendMessageToWeb("confirm-logout", null);
        }


        private void btnOpenLexicon_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.SendMessageToWeb("show-lexicon", null);
            //(new FormLexicon()).Show();
        }

        private void btnSetting_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.SendMessageToWeb("show-setting", null);
        }

        private void BtnGetContact_Click(object sender, RibbonControlEventArgs e)
        {
            var frm = new FormContact();
            Globals.ThisAddIn.ActiveDocument.RunInMainThread(() =>
            {
                frm.ShowDialog();
            });
        }

        private void BtnUpdate_Click(object sender, RibbonControlEventArgs e)
        {
            //System.Windows.Forms.MessageBox.Show("当前插件是最新版本");
            //Globals.ThisAddIn.SendMessageToWeb("upgrade", Config.APP_VERSION);
            Bridge.bridge.ShowUpgradeView();
        }

        private void BtnProofreadAll_Click(object sender, RibbonControlEventArgs e)
        {
            string time = DateTime.Now.ToString("yyyy - MM - dd HH: mm:ss: fff:ffffff");
            Globals.ThisAddIn.SendMessageToWeb("start", time);
        }

        private void btnClear_Click(object sender, RibbonControlEventArgs e)
        {
            //DocumentUtil.ClearProofreadMarks();

            Globals.ThisAddIn.ActiveDocument.ShowDialog("请确认是否清除此文档的所有校对标注?", "确定", "clear-tips");
            //if (result == DialogResult.OK)
            //{
            //    //Bridge.bridge.clearAllProofreadMark(null);
            //    Globals.ThisAddIn.ClearAllProofreadMark();
            //}
        }

        private void btnShowPane_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.ShowPanel();
        }

        private void btnHidePane_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.HidePanel();
        }

        private Microsoft.Office.Interop.Word.Document CurrentDocument;

        private void TestSplit()
        {
            //try
            //{
            //    this.CurrentDocument = Globals.ThisAddIn.Application.ActiveDocument;

            //    string rangeText = GetRangeText(CurrentDocument.Content);


            //    // 获取所有数学公式吗
            //    foreach (OMath oMath in CurrentDocument.OMaths)
            //    {
            //        Console.WriteLine("xx");
            //    }

            //    // 形状哟
            //    int count = CurrentDocument.Shapes.Count;
            //    System.Windows.Forms.MessageBox.Show(string.Format("Shapes总计:{0}", count));
            //    foreach (Microsoft.Office.Interop.Word.Shape shape in CurrentDocument.Shapes)
            //    {
            //    }
            //    int count2 = CurrentDocument.InlineShapes.Count;
            //    System.Windows.Forms.MessageBox.Show(string.Format("InlineShapes总计:{0}", count2));
            //    foreach (InlineShape inlineShape in CurrentDocument.InlineShapes)
            //    {
            //    }

            //    string text5 = rangeText;
            //    Logger.Log($"Removed unuseable section article: {text5}");
            //    string text6 = HostHelper.ReplaceSpecialChars(rangeText, isReplaceMultSpaceLine: true);
            //    Logger.Log($"Removed unuseable section upload: {text6}");
            //    int end = CurrentDocument.Content.End;
            //    // 分割
            //    string[] separator = new string[5] { "\r\a", "\a", "\r", "\v", "\f" };
            //    string[] array4 = text5.Split(separator, StringSplitOptions.None);
            //    string[] array5 = text6.Split('\n');

            //    object Start = 0;
            //    object End = 1;
            //    //int pagenumber = GetIndexPageNumber(CurrentDocument.Range(ref Start, ref End));

            //    int start = 0;
            //    int start2 = 0;
            //    int start3 = 0;
            //    string empty = string.Empty;
            //    string empty2 = string.Empty;
            //    string empty3 = string.Empty;
            //    Range lastRange = null;

            //    for (int j = 0; j < array5.Length; j++)
            //    {
            //        empty3 = string.Empty;
            //        List<CorrectionCharacter> characters = new List<CorrectionCharacter>();
            //        CorrectionFragmentAbstract correctionFragmentAbstract = null;
            //        //Logger.Instance.Info($"Handling {j + 1} upload part");
            //        empty2 = array5[j];
            //        if (string.IsNullOrEmpty(empty2))
            //        {
            //            continue;
            //        }
            //        int num4 = start + empty2.Length + 1;
            //        for (; string.IsNullOrEmpty(HostHelper.RemoveInvisibleCharas(array4[i])); i++)
            //        {
            //            num4 += array4[i].Length + 1;
            //        }
            //        empty = array4[i];
            //        //Logger.Instance.Info($"Upload part is {empty2}");
            //        End = start;
            //        Start = num4;

            //        Range range3 = CurrentDocument.Range(ref End, ref Start);
            //        string rangeText3 = GetRangeText(range3);

            //        //Logger.Instance.Info($"Text is {rangeText3}");
            //        StringBuilder stringBuilder = new StringBuilder();
            //        string text7 = (string.IsNullOrEmpty(rangeText3) ? "" : rangeText3.Last().ToString());
            //        if (HostHelper.RemoveInvisibleCharas(rangeText3) != empty2 || (text7 != "\r" && text7 != "\r\a" && text7 != "\a" && text7 != "\f" && text7 != "\v"))
            //        {
            //            int articleIndex = start;

            //            Start = articleIndex;
            //            End = articleIndex + 1;
            //            Range range4 = CurrentDocument.Range(ref Start, ref End);
            //            text7 = GetRangeText(range4);
            //            bool flag = true;
            //            while ((text7 != "\r" && text7 != "\r\a" && text7 != "\a" && text7 != "\f" && text7 != "\v") || flag)
            //            {
            //                if (flag)
            //                {
            //                    //Logger.Instance.Info(string.Format("Special text default logic.", rangeText3));
            //                    GetInvisibleCharacters(ref articleIndex, empty2, end, stringBuilder, characters, flag);
            //                }
            //                else
            //                {
            //                    //Logger.Instance.Info(string.Format("Text not contains \\r.", rangeText3));
            //                    GetInvisibleCharacters(ref articleIndex, "\r", end, stringBuilder, characters, flag);
            //                }
            //                End = articleIndex;
            //                Start = articleIndex + 1;
            //                range4 = CurrentDocument.Range(ref End, ref Start);
            //                text7 = GetRangeText(range4);
            //                flag = false;
            //            }
            //            stringBuilder.Append(text7);
            //            string text8 = stringBuilder.ToString();
            //            empty = text8.Replace("\a", "");
            //            num4 = range4.End;
            //            //Logger./*Instance*/.Info($"Article part is {empty}");
            //            if (empty.ToUpper().Contains("PAGEREF _TOC"))
            //            {
            //                start = num4;
            //                //Logger.Instance.Info("String Contains 'PAGEREF _TOC' Struct.");
            //                continue;
            //            }
            //        }
            //        else
            //        {
            //            empty = rangeText3.Replace("\a", "");
            //            int tempIndex = start;
            //            empty.ToCharArray().ToList().ForEach(delegate (char x)
            //            {
            //                characters.Add(new CorrectionCharacter(x, _v: true, tempIndex));
            //                tempIndex++;
            //            });
            //        }
            //    }

            //}
            //catch (Exception ex)
            //{
            //    System.Windows.Forms.MessageBox.Show("出现了异常:" + ex.Message);
            //}
        }


        private string GetInvisibleCharacters(ref int articleIndex, string articlePart, int end, StringBuilder stringBuilder, List<CorrectionCharacter> characters, bool isFirst = true)
        {
            int num = articleIndex;
            if (!isFirst)
            {
                articlePart = HostHelper.RemoveInvisibleCharas(articlePart);
            }
            int num2 = ((articlePart.Length + articleIndex < end) ? articlePart.Length : (end - articleIndex));
            Range range = null;
            string empty = string.Empty;
            if (string.IsNullOrEmpty(articlePart))
            {
                string[] source = new string[4] { "\r", "\r\a", "\v", "\f" };
                empty = string.Empty;
                while (range == null || range.Text == null || !source.Contains(empty))
                {
                    if (!string.IsNullOrEmpty(empty))
                    {
                        stringBuilder.Append(empty);
                        num++;
                    }
                    if (num >= end)
                    {
                        //Logger.Instance.Error($"Correction dictionary over length：{stringBuilder.ToString()}");
                        throw new ArgumentOutOfRangeException($"Not pair character: \\r \\f \\v \\r\\a, position {articleIndex}");
                    }
                    object Start = num;
                    object End = num + 1;
                    range = CurrentDocument.Range(ref Start, ref End);
                    empty = GetRangeText(range);
                    string text = empty;
                    string text2 = text;
                    if (text2 != null && (text2 == null || text2.Length != 0))
                    {
                        if (text2 == "\u001e")
                        {
                            empty = "-";
                        }
                    }
                    else
                    {
                        empty = "\n";
                    }
                    characters.Add(new CorrectionCharacter(empty.First(), source.Contains(empty), range.Start));
                }
            }
            else
            {
                for (int i = 0; i < num2; i++)
                {
                    string text3 = articlePart[i].ToString();
                    empty = string.Empty;
                    while (range == null || range.Text == null || !empty.Contains(text3))
                    {
                        if (num >= end)
                        {
                            //Logger.Instance.Error($"Correction dictionary over length：{stringBuilder.ToString()}");
                            throw new ArgumentOutOfRangeException($"Not pair character: {text3}, position {articleIndex}");
                        }
                        object End = num;
                        object Start = num + 1;
                        range = CurrentDocument.Range(ref End, ref Start);
                        empty = GetRangeText(range);
                        string text4 = empty;
                        string text5 = text4;
                        if (text5 != null && (text5 == null || text5.Length != 0))
                        {
                            if (text5 == "\u001e")
                            {
                                empty = "-";
                            }
                        }
                        else
                        {
                            empty = "\n";
                        }
                        stringBuilder.Append(empty);
                        num++;
                        characters.Add(new CorrectionCharacter(empty.First(), empty.Contains(text3), range.Start));
                    }
                }
            }
            articleIndex = num;
            return stringBuilder.ToString();
        }

        public static int GetIndexPageNumber(Range range)
        {
            int result = -1;
            try
            {
                result = int.Parse(range.get_Information(WdInformation.wdActiveEndPageNumber).ToString());
            }
            catch (Exception exception)
            {
                Logger.Log(exception);
            }
            return result;
        }


        protected string GetRangeText(Range range)
        {
            return string.IsNullOrEmpty(range.Text) ? "" : range.Text;
        }
        private void BtnOpenLog_Click(object sender, RibbonControlEventArgs e)
        {
            // 打开日志目录
            Process.Start(Config.APP_LOG_PATH);
        }

        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            Bridge.StartUpgradeProcess();
        }

        private void BtnOpenLogger_Click(object sender, RibbonControlEventArgs e)
        {
            // 判断日志窗口是否已经存在或者打开
            if (Logger.LoggerForm == null || Logger.LoggerForm.IsDisposed)
            {
                // 创建日志窗口
                Logger.LoggerForm = new FormLogger();
            }
            Logger.LoggerForm.Show();
        }

        private int GetRangeParagraphNumber(Range range)
        {
            var app = Globals.ThisAddIn.Application;
            int paragraphNumber = 0;
            if (range.Paragraphs.Count > 0)
            {
                // 获取当前文本在文档的段落数
                var currentParagraph = range.Paragraphs.First;
                var currentParagraphStart = currentParagraph.Range.Start;
                var allParagraphs = app.ActiveDocument.Paragraphs;
                for (var i = 1; i <= allParagraphs.Count; i++)
                {
                    var paragraph = allParagraphs[i];
                    var paragraphStart = paragraph.Range.Start;
                    if (paragraphStart > currentParagraphStart)
                    {
                        break;
                    }
                    if (currentParagraphStart == paragraphStart || paragraph == currentParagraph)
                    {
                        paragraphNumber = i;
                        break;
                    }
                }
            }
            return paragraphNumber;
        }

        private void BtnTest_Click(object sender, RibbonControlEventArgs e)
        {
            // 获取当前系统时间戳
            //int time = (int)(DateTime.Now.Ticks / 10000000);
            //BtnTest.Label = "测试按钮" + time;
            //var result = MessageBox.Show("Test", "xxx");
            //Globals.ThisAddIn.Application.
            var app = Globals.ThisAddIn.Application;
            var selection = app.Selection;
            var range = selection.Range.Duplicate;
            range.End = selection.Start;
            // 获取所在页
            var pageNumber = GetIndexPageNumber(range);
            // 获取所在行
            var rowNumber = range.get_Information(WdInformation.wdFirstCharacterLineNumber);
            int paragraphNumber = GetRangeParagraphNumber(range);


            MessageBox.Show($"当前页：{pageNumber}, 行：{rowNumber}, 段落：{paragraphNumber}");
        }

        private void ButtonSaveCache_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.SendMessageToWeb("save-cache", "");
        }

        private void ButtonLoadCache_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.ShowDialog("即将加载最近保存的进度，新的修改可能会丢失！", "确定", "load-cache");
        }

        private void BtnShowPanel_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.SendMessageToWeb("show-panel", "");
        }

        private void BtnOpenAppDir_Click(object sender, RibbonControlEventArgs e)
        {
            // 打开日志目录
            Process.Start(AppDomain.CurrentDomain.BaseDirectory);
        }



        private void BtnExportProofreadResult_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.SendMessageToWeb("export-result", "");
        }

        private void BtnShowVersion_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.SendMessageToWeb("show-version", "");
        }

        public Range currectSelectRange;

        private void btnDetectionAll_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.SendMessageToWeb("show-check-all", "");
        }

        private void btnDetectionParagraph_Click(object sender, RibbonControlEventArgs e)
        {
            // 获取当前选中的选区的首尾段落起始与结束位置
            var start = currectSelectRange.Start; // .Paragraphs.First.Range
            var end = currectSelectRange.End; // .Paragraphs.Last.Range
            var data = JSONObject.Create().Put("start", start).Put("end", end).ToString();

            Globals.ThisAddIn.SendMessageToWeb("show-check-range", data);
        }

        private void btnDetectionHistory_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.SendMessageToWeb("show-check-history", "");
        }

        /// <summary>
        /// 存储当前选区
        /// </summary>
        /// <param name="s"></param>
        public void ParseSelectionChange(Selection s)
        {
            var r = s.Range;
            this.currectSelectRange = r;
            if (CommonSenseDetection.instance.isChecking)
            {
                return;
            }
            btnDetectionParagraph.Enabled = r.Start != r.End;
            btnDetectionAll.Enabled = r.Start == r.End;
        }

        public void SetDetectionBtnStatus(bool allStatus,bool rangeStatus)
        {
            btnDetectionAll.Enabled = allStatus;
            btnDetectionParagraph.Enabled = rangeStatus;
        }

        private void BtnShowManual_Click(object sender, RibbonControlEventArgs e)
        {
            try
            {
                Process.Start(Config.USER_MANUAL_URL);
            }catch (Exception) {
                Globals.ThisAddIn.ActiveDocument.ShowMessage("打开用户手册失败", 2000, false);
            }
        }

        private void BtnProofreadExact_Click(object sender, RibbonControlEventArgs e)
        {
            // 
            Globals.ThisAddIn.ActiveDocument.CheckPanel();
            Globals.ThisAddIn.SendMessageToWeb("start", "exact");
        }

        private void BtnProofreadFull_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.ThisAddIn.ActiveDocument.CheckPanel();
            Globals.ThisAddIn.SendMessageToWeb("start", "full");
        }
    }
}
