using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using Edu.Common.Plugin;

namespace Edu.Common.Data
{
    /// <summary>
    /// 导入问题帮助类
    /// </summary>
    public class QuestionHelper
    {
        /// <summary>
        /// 根据Excel文件获取问题列表
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List<ImportModel> GetXlsQuestionData(string filePath)
        {
            List<ImportModel> xlsItems = new List<ImportModel>();
            var dt = Common.Plugin.NPOIHelper.ImportExcelToDatatable(filePath, 0, 0, true);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    xlsItems.Add(DataRowToModel(item));
                }
            }
            return xlsItems;

        }

        /// <summary>
        /// DataRow转实体
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private static ImportModel DataRowToModel(DataRow dr)
        {
            ImportModel model = new ImportModel();
            if (dr != null)
            {
                if (dr.Table.Columns.Contains("目录") && !string.IsNullOrEmpty(dr["目录"].ToString()))
                {
                    model.DirName = dr["目录"].ToString();
                }
                if (dr.Table.Columns.Contains("题型") && !string.IsNullOrEmpty(dr["题型"].ToString()))
                {
                    model.QuestionTypeName = dr["题型"].ToString();
                }
                if (dr.Table.Columns.Contains("题干") && !string.IsNullOrEmpty(dr["题干"].ToString()))
                {
                    model.QuestionTitle = dr["题干"].ToString();
                }
                if (dr.Table.Columns.Contains("正确答案") && !string.IsNullOrEmpty(dr["正确答案"].ToString()))
                {
                    model.QuestionAnswer = dr["正确答案"].ToString();
                }
                if (dr.Table.Columns.Contains("答案解析") && !string.IsNullOrEmpty(dr["答案解析"].ToString()))
                {
                    model.AnswerAnalysis = dr["答案解析"].ToString();
                }
                if (dr.Table.Columns.Contains("难易度") && !string.IsNullOrEmpty(dr["难易度"].ToString()))
                {
                    model.EasyType = dr["难易度"].ToString();
                }
                if (dr.Table.Columns.Contains("选项数") && !string.IsNullOrEmpty(dr["选项数"].ToString()))
                {
                    model.ChooseOptionCount = dr["选项数"].ToString();
                }
                if (dr.Table.Columns.Contains("A") && !string.IsNullOrEmpty(dr["A"].ToString()))
                {
                    model.OptionA = dr["A"].ToString();
                }
                if (dr.Table.Columns.Contains("B") && !string.IsNullOrEmpty(dr["B"].ToString()))
                {
                    model.OptionB = dr["B"].ToString();
                }
                if (dr.Table.Columns.Contains("C") && !string.IsNullOrEmpty(dr["C"].ToString()))
                {
                    model.OptionC = dr["C"].ToString();
                }
                if (dr.Table.Columns.Contains("D") && !string.IsNullOrEmpty(dr["D"].ToString()))
                {
                    model.OptionD = dr["D"].ToString();
                }
                if (dr.Table.Columns.Contains("E") && !string.IsNullOrEmpty(dr["E"].ToString()))
                {
                    model.OptionE = dr["E"].ToString();
                }
                if (dr.Table.Columns.Contains("F") && !string.IsNullOrEmpty(dr["F"].ToString()))
                {
                    model.OptionF = dr["F"].ToString();
                }
                if (dr.Table.Columns.Contains("G") && !string.IsNullOrEmpty(dr["G"].ToString()))
                {
                    model.OptionG = dr["G"].ToString();
                }
                if (dr.Table.Columns.Contains("H") && !string.IsNullOrEmpty(dr["H"].ToString()))
                {
                    model.OptionH = dr["H"].ToString();
                }
            }
            return model;
        }

        /// <summary>
        /// 获取Word数据
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List<ImportModel> GetWordQuestionData(string filePath)
        {
            List<ImportModel> list = new List<ImportModel>();
            var questionList = Common.Plugin.WordHelper.GetWordData(filePath,out List<QuestionTitleData> htmlList);
            if (questionList != null && questionList.Count > 0)
            {
                foreach (var rootItem in questionList)
                {
                    if (rootItem.QuestionList != null && rootItem.QuestionList.Count > 0)
                    {
                        if (rootItem.BigTitle == "阅读选择")
                        {
                            foreach (var item in rootItem.QuestionList)
                            {
                                if(!string.IsNullOrEmpty(item))
                                {
                                    string readStr = item.Replace("阅读选择", "").Trim();
                                    if (!string.IsNullOrEmpty(readStr))
                                    {
                                        ImportModel model = new ImportModel
                                        {
                                            Category = rootItem.BigTitle.Trim(),
                                            SubQuestionList = new List<ImportModel>(),
                                            QuestionTypeName= "阅读理解"
                                        };
                                        AnalysisReadingQuestion(item, model, htmlList);
                                        list.Add(model);
                                    }
                                }
                            }
                        }
                        else
                        {
                            foreach (var item in rootItem.QuestionList)
                            {
                                ImportModel model = new ImportModel()
                                {
                                    Category = rootItem.BigTitle.Trim()
                                };
                                if (!string.IsNullOrEmpty(item))
                                {
                                    AnalysisQuestionTitle(item, model, htmlList);
                                    list.Add(model);
                                }
                            }
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 解析问题题干
        /// </summary>
        /// <param name="item"></param>
        /// <param name="model"></param>
        private static void AnalysisQuestionTitle(string item, ImportModel model,List<QuestionTitleData> htmlList)
        {
            string pattern = @"\r\n";
            var tempArray = Regex.Split(item, pattern);
            string answerObj = "";//答案
            if (tempArray != null && tempArray.Length > 0)
            {
                string strTitle = tempArray[0].Trim();
                if (htmlList != null && htmlList.Count > 0)
                {
                    foreach (var hItem in htmlList)
                    {
                        try
                        {
                            if (strTitle.Contains(hItem.UnderLine))
                            {
                                foreach (var subItem in htmlList.Where(qitem => qitem.UnderLine == hItem.UnderLine))
                                {
                                    if (subItem.BeforeAfter != null)
                                    {
                                        if (subItem.BeforeAfter.Count == 1)
                                        {
                                            if (strTitle.Contains(subItem.BeforeAfter[0]))
                                            {
                                                strTitle = strTitle.Replace(hItem.UnderLine, Common.ConvertHelper.GetSpanString(hItem.UnderLine));
                                            }
                                        }
                                        else if (subItem.BeforeAfter.Count == 2)
                                        {
                                            if (strTitle.Contains(subItem.BeforeAfter[0]) || strTitle.Contains(subItem.BeforeAfter[1]))
                                            {
                                                strTitle = strTitle.Replace(hItem.UnderLine, Common.ConvertHelper.GetSpanString(hItem.UnderLine));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "AnalysisQuestionTitle");
                        }
                    }
                }

                model.QuestionTitle = strTitle;
                foreach (var subItem in tempArray)
                {
                    if (!string.IsNullOrEmpty(subItem))
                    {
                        if (subItem.Contains("答案解析：")|| subItem.Contains("答案解析:") || subItem.Contains("解析：") || subItem.Contains("解析:"))
                        {
                            string answerReg1 = @"答案解析[：:]";
                            string answerReg2 = @"解析[：:]";
                            Regex reg = new Regex(answerReg1);
                            Regex reg2 = new Regex(answerReg2);
                            string[] answerAnalysisArray = null;
                            if (reg2.IsMatch(subItem))
                            {
                                answerAnalysisArray = Regex.Split(subItem, answerReg2);
                            }
                            if (reg.IsMatch(subItem))
                            {
                                answerAnalysisArray = Regex.Split(subItem, answerReg1);
                            }
                            if (answerAnalysisArray != null && answerAnalysisArray.Length > 0)
                            {
                                model.AnswerAnalysis = answerAnalysisArray.Length > 1 ? answerAnalysisArray[1] : "";
                            }
                        }
                        if (subItem.Contains("答案：")|| subItem.Contains("答案:"))
                        {
                            answerObj = subItem;
                            var answerArray = Regex.Split(subItem, "[答][案][：:]");
                            if (answerArray != null && answerArray.Length > 0)
                            {
                                model.QuestionAnswer = answerArray.Length > 1 ? answerArray[1] : "";
                            }
                        }
                        if (subItem.Contains("难易程度：")||subItem.Contains("难易程度:") || subItem.Contains("难易度：") || subItem.Contains("难易度:"))
                        {
                            string easyReg1 = @"难易程度[：:]";
                            string easyReg2 = @"难易度[：:]";
                            Regex reg = new Regex(easyReg1);
                            Regex reg2 = new Regex(easyReg2);
                            string[] easyTypeArray = null;
                            if (reg.IsMatch(subItem))
                            {
                                easyTypeArray = Regex.Split(subItem, easyReg1);
                            }
                            if (reg2.IsMatch(subItem))
                            {
                                easyTypeArray = Regex.Split(subItem, easyReg2);
                            }
                            if (easyTypeArray != null && easyTypeArray.Length > 0)
                            {
                                model.EasyType = easyTypeArray.Length > 1 ? easyTypeArray[1] : "易";
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(answerObj))
            {
                AnalysisQuestionContent(answerObj, tempArray, model);
            }
        }

        /// <summary>
        /// 解析问题内容【判断题、选择题、填空题，简答题】
        /// </summary>
        /// <param name="answerObj"></param>
        /// <param name="tempArray"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private static void AnalysisQuestionContent(string answerObj, string[] tempArray, ImportModel model)
        {
            //判断题
            if (answerObj.Contains("答案：对") || answerObj.Contains("答案：错"))
            {
                model.QuestionTypeName = "判断题";
                model.OptionA = "对";
                model.OptionB = "错";
                model.ChooseOptionCount = "2";
            }
            //选择题
            else if (Common.Plugin.StringHelper.IsUpperLetter(model.QuestionAnswer))
            {
                if (model.QuestionAnswer.Length == 1)
                {
                    model.QuestionTypeName = "单选题";
                }
                if (model.QuestionAnswer.Length > 1)
                {
                    model.QuestionTypeName = "多选题";
                }
                if (model.QuestionAnswer == "Ａ")
                {
                    model.QuestionAnswer = "A";
                }
                if (model.QuestionAnswer == "Ｂ")
                {
                    model.QuestionAnswer = "B";
                }
                if (model.QuestionAnswer == "Ｃ")
                {
                    model.QuestionAnswer = "C";
                }
                if (model.QuestionAnswer == "Ｄ")
                {
                    model.QuestionAnswer = "D";
                }
                int index = 0;
                int chooseCount = 0;
                foreach (var item in tempArray)
                {
                    string pattern = @"[ABCDEFGHIＡＢＣＤ][.、]";
                    var tempArray2 = Regex.Split(item, pattern);
                    if (tempArray2 != null && tempArray2.Length == 2)
                    {
                        var tempStr = tempArray2[1].Replace(". ", "").Replace("、", "").Trim();
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            chooseCount++;
                        }
                        if (index == 0)
                        {
                            model.OptionA = tempStr;
                        }
                        if (index == 1)
                        {
                            model.OptionB = tempStr;
                        }
                        if (index == 2)
                        {
                            model.OptionC = tempStr;
                        }
                        if (index == 3)
                        {
                            model.OptionD = tempStr;
                        }
                        if (index == 4)
                        {
                            model.OptionE = tempStr;
                        }
                        if (index == 5)
                        {
                            model.OptionF = tempStr;
                        }
                        if (index == 6)
                        {
                            model.OptionG = tempStr;
                        }
                        if (index == 7)
                        {
                            model.OptionH = tempStr;
                        }
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            index++;
                        }
                    }
                }
                model.ChooseOptionCount = chooseCount.ToString();
            }
            //填空题
            else if (model.QuestionTitle.Contains("_"))
            {
                model.QuestionTypeName = "填空题";
                var answerArray = Regex.Split(answerObj, "答案：");
                if (answerArray != null && answerArray.Length == 2)
                {
                    var answerResultArray = Regex.Split(answerArray[1], "；");
                    int index = 0;
                    foreach (var item in answerResultArray)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            var tempStr = item;
                            if (index == 0)
                            {
                                model.OptionA = tempStr;
                            }
                            if (index == 1)
                            {
                                model.OptionB = tempStr;
                            }
                            if (index == 2)
                            {
                                model.OptionC = tempStr;
                            }
                            if (index == 3)
                            {
                                model.OptionD = tempStr;
                            }
                            if (index == 4)
                            {
                                model.OptionE = tempStr;
                            }
                            if (index == 5)
                            {
                                model.OptionF = tempStr;
                            }
                            if (index == 6)
                            {
                                model.OptionG = tempStr;
                            }
                            if (index == 7)
                            {
                                model.OptionH = tempStr;
                            }
                            index++;
                        }
                    }
                    model.ChooseOptionCount = (index + 1).ToString();
                }
            }
            //数字选择题
            else if (model.QuestionAnswer.Contains(Common.Config.NumberQuestionChar))
            {
                if (model.QuestionAnswer.Replace(Common.Config.NumberQuestionChar,"").Length == 1)
                {
                    model.QuestionTypeName = "单选题(数字)";
                }
               
                int index = 0;
                int chooseCount = 0;
                foreach (var item in tempArray)
                {
                    string pattern = @"[@][123456789][.、]";
                    var tempArray2 = Regex.Split(item, pattern);
                    if (tempArray2 != null && tempArray2.Length == 2)
                    {
                        var tempStr = tempArray2[1].Replace(". ", "").Replace("、", "").Trim();
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            chooseCount++;
                        }
                        if (index == 0)
                        {
                            model.OptionA = tempStr;
                        }
                        if (index == 1)
                        {
                            model.OptionB = tempStr;
                        }
                        if (index == 2)
                        {
                            model.OptionC = tempStr;
                        }
                        if (index == 3)
                        {
                            model.OptionD = tempStr;
                        }
                        if (index == 4)
                        {
                            model.OptionE = tempStr;
                        }
                        if (index == 5)
                        {
                            model.OptionF = tempStr;
                        }
                        if (index == 6)
                        {
                            model.OptionG = tempStr;
                        }
                        if (index == 7)
                        {
                            model.OptionH = tempStr;
                        }
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            index++;
                        }
                    }
                }
                model.ChooseOptionCount = chooseCount.ToString();
                model.QuestionAnswer = model.QuestionAnswer.Replace(Common.Config.NumberQuestionChar, "");
            }
            //数字选择题
            else if (Common.Plugin.StringHelper.IsNumber(model.QuestionAnswer.Trim()))
            {
                if (model.QuestionAnswer.Trim().Length == 1)
                {
                    model.QuestionTypeName = "单选题(数字)";
                }
                int index = 0;
                int chooseCount = 0;
                foreach (var item in tempArray)
                {
                    string pattern = @"[123456789][.]";
                    var tempArray2 = Regex.Split(item, pattern);
                    if (tempArray2 != null && tempArray2.Length == 2)
                    {
                        var tempStr = tempArray2[1].Replace(". ", "").Replace("、", "").Trim();
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            chooseCount++;
                        }
                        if (index == 0)
                        {
                            model.OptionA = tempStr;
                        }
                        if (index == 1)
                        {
                            model.OptionB = tempStr;
                        }
                        if (index == 2)
                        {
                            model.OptionC = tempStr;
                        }
                        if (index == 3)
                        {
                            model.OptionD = tempStr;
                        }
                        if (index == 4)
                        {
                            model.OptionE = tempStr;
                        }
                        if (index == 5)
                        {
                            model.OptionF = tempStr;
                        }
                        if (index == 6)
                        {
                            model.OptionG = tempStr;
                        }
                        if (index == 7)
                        {
                            model.OptionH = tempStr;
                        }
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            index++;
                        }
                    }
                }
                model.ChooseOptionCount = chooseCount.ToString();
                model.QuestionAnswer = model.QuestionAnswer.Trim();
            }
            //简答题
            else
            {
                model.QuestionTypeName = "简答题";
                model.ChooseOptionCount = "1";
            }
        }

        /// <summary>
        /// 解析Word中阅读理解
        /// </summary>
        /// <param name="questionStr"></param>
        /// <param name="model"></param>
        private static void AnalysisReadingQuestion(string questionStr, ImportModel model,List<QuestionTitleData> htmlList)
        {
            string[] tempArray = null;
            //“\r\n”开始+“1234567890”出现1次到多次+“、或.”结尾
            string pattern1 = @"\r\n[1234567890１２３４５６７８９０]*[、]";
            Regex reg1 = new Regex(pattern1);
            tempArray = Regex.Split(questionStr, pattern1);
            if (tempArray != null && tempArray.Length > 0)
            {
                model.QuestionTitle = tempArray[0];
                int index = 0;
                foreach (var item in tempArray)
                {
                    if (index > 0)
                    {
                        ImportModel subQuestion = new ImportModel();
                        AnalysisQuestionTitle(item, subQuestion,htmlList);
                        model.SubQuestionList.Add(subQuestion);
                        model.AnswerAnalysis += "<p>"+(index) + "、" + subQuestion.AnswerAnalysis+"</p>";
                    }
                    index++;
                }
                if (model.SubQuestionList != null && model.SubQuestionList.Count > 0)
                {
                    if (model.SubQuestionList.Where(qitem => qitem.EasyType == "中").Count() > 0)
                    {
                        model.EasyType = "中";
                    }
                    else if (model.SubQuestionList.Where(qitem => qitem.EasyType == "难").Count() > 0)
                    {
                        model.EasyType = "难";
                    }
                }
            }
        }
    }

    /// <summary>
    /// 导入数据格式
    /// </summary>
    public class ImportModel
    {
        /// <summary>
        /// 目录
        /// </summary>
        public string DirName { get; set; }

        /// <summary>
        /// 题型
        /// </summary>
        public string QuestionTypeName { get; set; }

        /// <summary>
        /// 题干
        /// </summary>
        public string QuestionTitle { get; set; }

        /// <summary>
        /// 正确答案
        /// </summary>
        public string QuestionAnswer { get; set; }

        /// <summary>
        /// 答案解析
        /// </summary>
        public string AnswerAnalysis { get; set; }

        /// <summary>
        /// 难易程度
        /// </summary>
        public string EasyType { get; set; }

        /// <summary>
        /// 选项数
        /// </summary>
        public string ChooseOptionCount { get; set; }

        /// <summary>
        /// A 
        /// </summary>
        public string OptionA { get; set; }

        /// <summary>
        /// B
        /// </summary>
        public string OptionB { get; set; }

        /// <summary>
        /// C
        /// </summary>
        public string OptionC { get; set; }

        /// <summary>
        /// D
        /// </summary>
        public string OptionD { get; set; }

        /// <summary>
        /// E
        /// </summary>
        public string OptionE { get; set; }

        /// <summary>
        /// F
        /// </summary>
        public string OptionF { get; set; }

        /// <summary>
        /// G
        /// </summary>
        public string OptionG { get; set; }

        /// <summary>
        /// H
        /// </summary>
        public string OptionH { get; set; }

        /// <summary>
        /// 大分类分类名称
        /// </summary>
        public string Category { get; set; }

        /// <summary>
        /// 子项题目列表
        /// </summary>
        public List<ImportModel> SubQuestionList { get; set; }
    }
}
