using System.Data;
using System.Net;
using AgileObjects.AgileMapper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using Tiobon.Core.Common;
using Tiobon.Core.Common.Caches;
using Tiobon.Core.IRepository.Base;
using Tiobon.Core.IServices;
using Tiobon.Core.Model;
using Tiobon.Core.Model.Models;
using Tiobon.Core.Services.BASE;

namespace Tiobon.Core.Services;

/// <summary>
/// 题目 (服务)
/// </summary>
public class Ghre_QuestionServices : BaseServices<Ghre_Question, Ghre_QuestionDto, InsertGhre_QuestionInput, EditGhre_QuestionInput>, IGhre_QuestionServices
{
    private readonly IBaseRepository<Ghre_Question> _dal;
    private IGhre_QuestionAnswerServices _ghre_QuestionAnswerServices;
    private IGhre_CourseServices _ghre_CourseServices;
    private IGhre_CourseClassServices _ghre_CourseClassServices;
    public Ghre_QuestionServices(IBaseRepository<Ghre_Question> dal,
        IGhre_QuestionAnswerServices ghre_QuestionAnswerServices,
        IGhre_CourseServices ghre_CourseServices,
        ICaching caching,
        IGhre_CourseClassServices ghre_CourseClassServices)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
        _ghre_QuestionAnswerServices = ghre_QuestionAnswerServices;
        _ghre_CourseServices = ghre_CourseServices;
        _ghre_CourseClassServices = ghre_CourseClassServices;
    }

    public async Task<ServicePageResult<Ghre_QuestionDto>> QueryFilterPage1(QueryBody filter)
    {
        //var data1 = await BaseDal.QueryFilterPage(body);

        RefAsync<int> totalCount = 0;
        var query = Db.Queryable<Ghre_Question>();

        if (string.IsNullOrWhiteSpace(filter.orderBy))
            filter.orderBy = "CreateTime DESC";

        string conditions = "1=1";
        if (filter.jsonParam != null)
            foreach (JProperty jProperty in filter.jsonParam.Properties())
            {
                var name = jProperty.Name;
                var value = jProperty.Value.ToString();
                if (name == "page" || name == "pageSize")
                    continue;
                if (name == "CourseName")
                {
                    string sql = string.Empty;
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);

                        switch (jsonParam.operationKey)
                        {
                            case "Include":
                                var ids = await Db.Queryable<Ghre_Course>().Where(x => x.CourseName.Contains(jsonParam.columnValue)).Select(x => x.Id).ToListAsync();
                                query = query.Where(x => x.CourseId != null && ids.Contains(x.CourseId.Value));
                                break;
                            case "NotInclude":
                                var ids1 = await Db.Queryable<Ghre_Course>().Where(x => x.CourseName.Contains(jsonParam.columnValue)).Select(x => x.Id).ToListAsync();
                                query = query.Where(x => x.CourseId != null && !ids1.Contains(x.CourseId.Value));
                                break;
                            case "IsNull":
                                query = query.Where(x => x.CourseId == null);
                                break;
                            case "NotNull":
                                query = query.Where(x => x.CourseId != null);
                                break;
                            case "Equal":
                                var id = await Db.Queryable<Ghre_Course>().Where(x => x.CourseName == jsonParam.columnValue).Select(x => x.Id).FirstAsync();
                                query = query.Where(x => x.CourseId == id);

                                break;
                            case "NotEqual":
                                var id1 = await Db.Queryable<Ghre_Course>().Where(x => x.CourseName == jsonParam.columnValue).Select(x => x.Id).FirstAsync();
                                query = query.Where(x => x.CourseId != id1);
                                break;
                            default:
                                break;
                        }
                    }
                }
                else
                if (!string.IsNullOrWhiteSpace(value))
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);

                    switch (jsonParam.operationKey)
                    {
                        case "Include":
                            conditions += $" AND {name} LIKE '%{jsonParam.columnValue}%'";
                            break;
                        case "NotInclude":
                            conditions += $" AND {name} NOT LIKE '%{jsonParam.columnValue}%'";
                            break;
                        case "IsNull":
                            conditions += $" AND {name} IS NULL";
                            break;
                        case "NotNull":
                            conditions += $" AND {name} IS NOT NULL";
                            break;
                        case "Equal":
                            conditions += $" AND {name} ='{jsonParam.columnValue}'";
                            break;
                        case "NotEqual":
                            conditions += $" AND {name} !='{jsonParam.columnValue}'";
                            break;
                        default:
                            break;
                    }
                }
            }
        if (filter.pageSize == 0)
            filter.pageSize = 10000;
        query = query.Where(conditions);
        var list = await query
            .OrderByIF(!string.IsNullOrEmpty(filter.orderBy), filter.orderBy)
        .ToPageListAsync(filter.pageNum, filter.pageSize, totalCount);

        var data1 = new ServicePageResult<Ghre_Question>(filter.pageNum, totalCount, filter.pageSize, list);

        var data = Mapper.Map(data1.result.DT_TableDataT1).ToANew<List<Ghre_QuestionDto>>();
        var courseIds = data.Where(x => x.CourseId != null).Select(x => x.CourseId).Distinct().ToList();

        var courses = await _ghre_CourseServices.Query(x => courseIds.Contains(x.Id));
        var classsIds = courses.Select(x => x.CourseClassId).Distinct().ToList();
        var classs = await _ghre_CourseClassServices.Query(x => classsIds.Contains(x.Id));
        data.ForEach(async x =>
        {
            x.DifficultyLevelLabel = await GetParaLabel("DifficultyLevel", x.DifficultyLevel);
            x.QuestionTypeLabel = await GetParaLabel("QuestionType", x.QuestionType);

            if (x.CourseId != null)
            {
                var course = courses.Where(a => a.Id == x.CourseId).FirstOrDefault();
                x.CourseName = course?.CourseName;
                var courseClass = classs.Where(a => a.Id == course.CourseClassId).FirstOrDefault();
                x.CourseType = courseClass.ClassName;
                x.CourseTypeId = courseClass.Id;
            }
        });

        return new ServicePageResult<Ghre_QuestionDto>(filter.pageNum, data1.result.DT_TablePageInfoT1.TotalCount, filter.pageSize, data);
    }
    public override async Task<ServicePageResult<Ghre_QuestionDto>> QueryFilterPage(QueryBody filter)
    {

        RefAsync<int> totalCount = 0;
        string sql = @"SELECT *
                        FROM (SELECT A.*,
                                     B.CourseName,
                                     C.Id CourseTypeId,
                                     C.ClassName CourseType
                              FROM Ghre_Question A
                                   LEFT JOIN Ghre_Course B ON A.CourseId = B.Id
                                   LEFT JOIN Ghre_CourseClass C ON B.CourseClassId = C.Id
                              WHERE A.IsEnable = 1) A";

        if (string.IsNullOrWhiteSpace(filter.orderBy))
            filter.orderBy = "CreateTime DESC";

        string conditions = "1=1";
        if (filter.jsonParam != null)
            foreach (JProperty jProperty in filter.jsonParam.Properties())
            {
                var name = jProperty.Name;
                var value = jProperty.Value.ToString();
                if (name == "page" || name == "pageSize")
                    continue;

                if (!string.IsNullOrWhiteSpace(value))
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);

                    switch (jsonParam.operationKey)
                    {
                        case "Include":
                            conditions += $" AND {name} LIKE '%{jsonParam.columnValue}%'";
                            break;
                        case "NotInclude":
                            conditions += $" AND {name} NOT LIKE '%{jsonParam.columnValue}%'";
                            break;
                        case "IsNull":
                            conditions += $" AND {name} IS NULL";
                            break;
                        case "NotNull":
                            conditions += $" AND {name} IS NOT NULL";
                            break;
                        case "Equal":
                            conditions += $" AND {name} ='{jsonParam.columnValue}'";
                            break;
                        case "NotEqual":
                            conditions += $" AND {name} !='{jsonParam.columnValue}'";
                            break;
                        default:
                            break;
                    }
                }
            }
        if (filter.pageSize == 0)
            filter.pageSize = 10000;
        var data = await Db.SqlQueryable<Ghre_QuestionDto>(sql)
            .OrderBy(filter.orderBy)
            .ToPageListAsync(filter.pageNum, filter.pageSize, totalCount);

        data.ForEach(async x =>
        {
            x.DifficultyLevelLabel = await GetParaLabel("DifficultyLevel", x.DifficultyLevel);
            x.QuestionTypeLabel = await GetParaLabel("QuestionType", x.QuestionType);
            if (!string.IsNullOrEmpty(x.QuestionContent))
                x.QuestionContent = WebUtility.HtmlDecode(x.QuestionContent);

        });


        return new ServicePageResult<Ghre_QuestionDto>(filter.pageNum, totalCount, filter.pageSize, data);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<ServiceResult<FromGhre_QuestionInput>> QueryFrom(long Id)
    {
        var data = new FromGhre_QuestionInput();

        #region Column
        data.Column.Add(new FromGhre_QuestionColumn()
        {
            label = "课程名称",
            field = "courseID",
            elementType = "ApiSelect",
            required = true,
            multipleSelect = true,
            editable = true,
            dataSource = "api/Common/GetSelect/Ghre_Course?FW=DOTNETCORE"
        });
        data.Column.Add(new FromGhre_QuestionColumn()
        {
            label = "题目编号",
            field = "questionNo",
            elementType = "Input",
            required = false,
            multipleSelect = false,
            editable = false,
            dataSource = "",
            placeholder = "保存后自动生成"
        });

        #endregion

        #region PageData


        var answerList = new List<FromGhre_QuestionQuestionAnswerList>
        {
            new FromGhre_QuestionQuestionAnswerList()
            {
                No = "A",
            },
            new FromGhre_QuestionQuestionAnswerList()
            {
                No = "B",
            },
            new FromGhre_QuestionQuestionAnswerList()
            {
                No = "C",
            },
            new FromGhre_QuestionQuestionAnswerList()
            {
                No = "D",
            }
        };
        var answerList1 = new List<FromGhre_QuestionQuestionAnswerList>
        {
            new FromGhre_QuestionQuestionAnswerList()
            {
                No = "A",
                label="对"
            },
            new FromGhre_QuestionQuestionAnswerList()
            {
                No = "B",
                label="错"
            }
        };
        data.PageData.questionType = new List<FromGhre_QuestionQuestionType>
        {
            new FromGhre_QuestionQuestionType()
            {
                label = "单选题",
                type = "Single",
                isActive = 1,
                detail= new FromGhre_QuestionQuestionTypeDetail()
                {
                    answerList=answerList
                }
            },
            new FromGhre_QuestionQuestionType()
            {
                label = "多选题",
                type = "Multiple",
                isActive = 0,
                detail= new FromGhre_QuestionQuestionTypeDetail()
                {
                    answerList=answerList
                }
            },
            new FromGhre_QuestionQuestionType()
            {
                label = "判断题",
                type = "TrueOrFalse",
                isActive = 0,
                detail= new FromGhre_QuestionQuestionTypeDetail()
                {
                    answerList=answerList1
                }
            },
            new FromGhre_QuestionQuestionType()
            {
                label = "填空题",
                type = "Completion",
                isActive = 0,
                detail = new FromGhre_QuestionQuestionTypeDetail()
                {
                    content = "演示演示____演示",
                    answerList= new List<FromGhre_QuestionQuestionAnswerList>
                    {
                        new FromGhre_QuestionQuestionAnswerList()
                        {
                            No = "A",
                        }
                    }
                }
            },
            new FromGhre_QuestionQuestionType()
            {
                label = "简答题",
                type = "ShortAnswer",
                isActive = 0,
                detail = new FromGhre_QuestionQuestionTypeDetail()
                {
                    answerList= new List<FromGhre_QuestionQuestionAnswerList>(),
                    answer1 =  new List<string>
                    {
                        ""
                    }
                }
            }
        };

        if (Id != 0)
        {
            var question = await base.QueryById(Id);
            data.PageData.questionType.ForEach(x => x.isActive = 0);
            data.PageData.baseData.questionNo = question.QuestionNo;
            data.PageData.baseData.courseID.Add(question.CourseId);
            data.PageData.baseData.CreateDataInfo = question.CreateDataInfo;
            data.PageData.baseData.UpdateDataInfo = question.UpdateDataInfo;

            var questionType = data.PageData.questionType.Where(x => x.type == question.QuestionType).FirstOrDefault();
            if (questionType != null)
            {
                var answers = await _ghre_QuestionAnswerServices.Query(x => x.QuestionId == Id, "TaxisNo ASC");
                questionType.isActive = 1;
                questionType.detail.difficulty = question.DifficultyLevel;
                questionType.detail.answer = answers.Where(x => x.IsCorrect == true).FirstOrDefault()?.QuestionNo;
                questionType.detail.answer1 = answers.Where(x => x.IsCorrect == true).Select(x => x.QuestionNo).ToList();
                questionType.detail.content = question.QuestionContent;
                if (!string.IsNullOrEmpty(questionType.detail.content))
                    questionType.detail.content = WebUtility.HtmlDecode(questionType.detail.content);

                questionType.detail.RemarkSz = question.QuestionAnalysis;
                questionType.detail.answerList = answers.Select(x => new FromGhre_QuestionQuestionAnswerList()
                {
                    No = x.QuestionNo,
                    label = x.AnswerContent,
                    imageUrl = x.ImageUrl,
                    imgWidthPc = x.ImageWidthPc,
                    imgWidthApp = x.ImageWidthApp,
                }).ToList();
            }
        }
        #endregion

        return ServiceResult<FromGhre_QuestionInput>.OprateSuccess("查询成功！", data);
    }

    public async Task<ServiceResult> InsertFrom(FromGhre_QuestionPageData insertModel)
    {
        var questionType = insertModel.questionType.Where(x => x.isActive == 1).FirstOrDefault();
        #region 填空题处理
        if (questionType.type == "Completion")
            questionType.detail.answerList = questionType.detail.answer1
                    .Select(x => new FromGhre_QuestionQuestionAnswerList()
                    {
                        No = x,
                        label = x,
                    }).ToList();
        else if (questionType.type == "ShortAnswer")
            questionType.detail.answer1 = questionType.detail.answerList.Select(x => x.No).ToList();

        #endregion

        ValidForm(insertModel);
        await Db.Ado.BeginTranAsync();

        try
        {
            string questionTypeName = ConvertQuestionType(questionType.type);

            if (!string.IsNullOrEmpty(questionType.detail.content))
                questionType.detail.content = WebUtility.HtmlEncode(questionType.detail.content);

            #region 判断是否重复
            for (int j = 0; j < insertModel.baseData.courseID.Count; j++)
            {
                var courseID = insertModel.baseData.courseID[j];
                string sql = "SELECT * FROM Ghre_Question where QuestionType='{0}' and CourseId='{1}' and QuestionContent ='{2}'";
                sql = string.Format(sql, questionType.type, courseID, questionType.detail.content);
                DataTable dt = Db.Ado.GetDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    var course = await _ghre_CourseServices.QueryById(courseID);
                    throw new Exception($"课程【{course.CourseName}】存在相同内容【{questionTypeName}】");
                }
            }
            #endregion 
            for (int j = 0; j < insertModel.baseData.courseID.Count; j++)
            {
                var courseID = insertModel.baseData.courseID[j];
                var insert = new InsertGhre_QuestionInput();
                insert.CourseId = courseID;

                insert.QuestionType = questionType.type;
                insert.DifficultyLevel = questionType.detail.difficulty;
                insert.QuestionContent = questionType.detail.content;
                insert.QuestionAnalysis = questionType.detail.RemarkSz;
                insert.QuestionNo = await GenerateContinuousSequence(insert.QuestionType.Substring(0, 1));

                var id = await base.Add(insert);

                var insertAnswers = questionType.detail.answerList.Select(x => new InsertGhre_QuestionAnswerInput()
                {
                    QuestionNo = x.No,
                    AnswerContent = x.label,
                    ImageUrl = x.imageUrl,
                    ImageWidthPc = x.imgWidthPc,
                    ImageWidthApp = x.imgWidthApp,
                }).ToList();
                int i = 100;
                insertAnswers.ForEach(x =>
                {
                    x.TaxisNo = i;
                    x.QuestionId = id;
                    if (questionType.detail.answer != null && questionType.detail.answer == x.QuestionNo && (insert.QuestionType == "Single" || insert.QuestionType == "TrueOrFalse"))
                        x.IsCorrect = true;
                    if (questionType.detail.answer1 != null && questionType.detail.answer1.Contains(x.QuestionNo) && (insert.QuestionType == "ShortAnswer" || insert.QuestionType == "Multiple" || insert.QuestionType == "Completion"))
                        x.IsCorrect = true;
                    i = i + 100;
                });

                if (insertAnswers.Where(b => string.IsNullOrWhiteSpace(b.AnswerContent)).Any())
                    throw new Exception(insert.QuestionType == "ShortAnswer" ? "关键词存在空值！" : "答案选项存在空值！");
                if (!insertAnswers.Where(b => b.IsCorrect == true).Any())
                    throw new Exception(insert.QuestionType == "ShortAnswer" ? "关键词未填写！" : "正确答案未标记！");
                await _ghre_QuestionAnswerServices.Add(insertAnswers);
            }
            await Db.Ado.CommitTranAsync();
            return ServiceResult.OprateSuccess("新增成功！");
        }
        catch (Exception)
        {
            await Db.Ado.RollbackTranAsync();
            throw;
        }
    }

    public async Task<ServiceResult> UpdareFrom(long Id, FromGhre_QuestionPageData editModel)
    {

        var questionType = editModel.questionType.Where(x => x.isActive == 1).FirstOrDefault();

        if (!string.IsNullOrEmpty(questionType.detail.content))
            questionType.detail.content = WebUtility.HtmlEncode(questionType.detail.content);

        #region 填空题处理
        if (questionType.type == "Completion")
            questionType.detail.answerList = questionType.detail.answer1
                    .Select(x => new FromGhre_QuestionQuestionAnswerList()
                    {
                        No = x,
                        label = x,
                    }).ToList();
        else if (questionType.type == "ShortAnswer")
            questionType.detail.answer1 = questionType.detail.answerList.Select(x => x.No).ToList();
        #endregion

        ValidForm(editModel);

        await Db.Ado.BeginTranAsync();

        try
        {
            string questionTypeName = ConvertQuestionType(questionType.type);

            #region 判断是否重复
            for (int j = 0; j < editModel.baseData.courseID.Count; j++)
            {
                var courseID = editModel.baseData.courseID[j];
                string sql = "SELECT * FROM Ghre_Question where QuestionType='{0}' and CourseId='{1}' and QuestionContent ='{2}'  AND Id !='{3}'";
                sql = string.Format(sql, questionType.type, courseID, questionType.detail.content, Id);
                DataTable dt = Db.Ado.GetDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    var course = await _ghre_CourseServices.QueryById(courseID);
                    throw new Exception($"课程【{course.CourseName}】存在相同内容【{questionTypeName}】");
                }
            }
            #endregion



            var data = await base.QueryById(Id);
            await _ghre_QuestionAnswerServices.Delete(x => x.QuestionId == Id);
            var edit = Mapper.Map(data).ToANew<EditGhre_QuestionInput>();
            edit.CourseId = editModel.baseData.courseID[0];

            edit.QuestionType = questionType.type;
            edit.DifficultyLevel = questionType.detail.difficulty;
            edit.QuestionContent = questionType.detail.content;
            edit.QuestionAnalysis = questionType.detail.RemarkSz;

            await base.Update(Id, edit);
            var insertAnswers = questionType.detail.answerList.Select(x => new InsertGhre_QuestionAnswerInput()
            {
                QuestionNo = x.No,
                AnswerContent = x.label,
                ImageUrl = x.imageUrl,
                ImageWidthPc = x.imgWidthPc,
                ImageWidthApp = x.imgWidthApp,
            }).ToList();
            int i = 100;
            insertAnswers.ForEach(x =>
            {
                x.TaxisNo = i;
                x.QuestionId = Id;
                if (questionType.detail.answer != null && questionType.detail.answer == x.QuestionNo && (edit.QuestionType == "Single" || edit.QuestionType == "TrueOrFalse"))
                    x.IsCorrect = true;
                if (questionType.detail.answer1 != null && questionType.detail.answer1.Contains(x.QuestionNo) && (edit.QuestionType == "ShortAnswer" || edit.QuestionType == "Multiple" || edit.QuestionType == "Completion"))
                    x.IsCorrect = true;
                i = i + 100;
            });
            if (insertAnswers.Where(b => string.IsNullOrWhiteSpace(b.AnswerContent)).Any())
                throw new Exception(edit.QuestionType == "ShortAnswer" ? "关键词存在空值！" : "答案选项存在空值！");
            if (!insertAnswers.Where(b => b.IsCorrect == true).Any())
                throw new Exception(edit.QuestionType == "ShortAnswer" ? "关键词未填写！" : "正确答案未标记！");

            await _ghre_QuestionAnswerServices.Add(insertAnswers);

            for (int j = 0; j < editModel.baseData.courseID.Count; j++)
            {
                if (j == 0)
                    continue;

                var courseID = editModel.baseData.courseID[j];
                var insert = new InsertGhre_QuestionInput();
                insert.CourseId = courseID;

                insert.QuestionType = questionType.type;
                insert.DifficultyLevel = questionType.detail.difficulty;
                insert.QuestionContent = questionType.detail.content;
                insert.QuestionAnalysis = questionType.detail.RemarkSz;
                insert.QuestionNo = await GenerateContinuousSequence(insert.QuestionType.Substring(0, 1));

                var id = await base.Add(insert);

                insertAnswers = questionType.detail.answerList.Select(x => new InsertGhre_QuestionAnswerInput()
                {
                    QuestionNo = x.No,
                    AnswerContent = x.label,
                    ImageUrl = x.imageUrl,
                    ImageWidthPc = x.imgWidthPc,
                    ImageWidthApp = x.imgWidthApp,
                }).ToList();
                i = 100;
                insertAnswers.ForEach(x =>
                {
                    x.TaxisNo = i;
                    x.QuestionId = id;
                    if (questionType.detail.answer != null && questionType.detail.answer == x.QuestionNo && (insert.QuestionType == "Single" || insert.QuestionType == "TrueOrFalse"))
                        x.IsCorrect = true;
                    if (questionType.detail.answer1 != null && questionType.detail.answer1.Contains(x.QuestionNo) && (insert.QuestionType == "ShortAnswer" || insert.QuestionType == "Multiple" || insert.QuestionType == "Completion"))
                        x.IsCorrect = true;
                    i = i + 100;
                });
                if (insertAnswers.Where(b => string.IsNullOrWhiteSpace(b.AnswerContent)).Any())
                    throw new Exception(insert.QuestionType == "ShortAnswer" ? "关键词存在空值！" : "答案选项存在空值！");
                if (!insertAnswers.Where(b => b.IsCorrect == true).Any())
                    throw new Exception(insert.QuestionType == "ShortAnswer" ? "关键词未填写！" : "正确答案未标记！");

                await _ghre_QuestionAnswerServices.Add(insertAnswers);
            }
            await Db.Ado.CommitTranAsync();

            return ServiceResult.OprateSuccess("更新成功！");
        }
        catch (Exception)
        {
            await Db.Ado.RollbackTranAsync();
            throw;
        }
    }

    public async Task<string> GenerateContinuousSequence(string prefixTemp)
    {
        try
        {
            string result = string.Empty;
            string tableCode = "Ghre_Question";
            string columnCode = "QuestionNo";
            int length = 7;
            int tempLength = 6;
            int sequence;

            #region 查询
            DbSelect dbSelect = new DbSelect(tableCode + " A", "A", null);
            dbSelect.IsInitDefaultValue = false;

            if (!string.IsNullOrEmpty(prefixTemp))
                dbSelect.Select("MAX(SUBSTRING(A." + columnCode + "," + (prefixTemp.Length + 1).ToString() + "," + tempLength.ToString() + "))");
            else
                dbSelect.Select("MAX(A." + columnCode + ")");
            //}
            //dbSelect.Select("MAX(CONVERT(DECIMAL,SUBSTRING(A.ISSUE_NO," + (prefix.Length + dateString.Length + 1).ToString() + "," + tempLength.ToString() + ")))");
            if (!string.IsNullOrEmpty(prefixTemp))
                dbSelect.Where("SUBSTRING(A." + columnCode + ",1," + (prefixTemp.Length).ToString() + ")", " = ", prefixTemp);
            dbSelect.Where("LEN(A." + columnCode + ")", "=", length);
            string sql = dbSelect.GetSql();
            //await Db.Ado.GetScalarAsync(sql)
            string maxSequence = Convert.ToString(await Db.Ado.GetScalarAsync(sql));
            #endregion
            //tempLength = tempLength - dateString.Length;
            if (string.IsNullOrEmpty(maxSequence))
                result = prefixTemp + Convert.ToString(1).PadLeft(tempLength, '0');
            else
            {
                if (!string.IsNullOrEmpty(prefixTemp))
                {
                    if (int.TryParse(maxSequence, out sequence))
                    {
                        sequence += 1;
                        if (sequence.ToString().Length > tempLength)
                            throw new Exception("自动生成字串长度已经超过设定长度!");
                    }
                    else
                        throw new Exception("表中的数据无法进行自动编号,请联系软件开发商!");
                    result = prefixTemp + sequence.ToString().PadLeft(tempLength, '0');
                }
                else
                {
                    if (int.TryParse(maxSequence, out sequence))
                    {
                        sequence += 1;
                        if (sequence.ToString().Length > length)
                            throw new Exception("自动生成字串长度已经超过设定长度!");
                    }
                    else
                        throw new Exception("表中的数据无法进行自动编号,请联系软件开发商!");
                    result = sequence.ToString().PadLeft(length, '0');
                }
            }
            return result;
        }
        catch (Exception) { throw; }
    }

    public static string ConvertQuestionType(string type)
    {
        string questionTypeName = string.Empty;
        if (type == "Single")
            questionTypeName = "单选题";
        else if (type == "Multiple")
            questionTypeName = "多选题";
        else if (type == "TrueOrFalse")
            questionTypeName = "判断题";
        else if (type == "Completion")
            questionTypeName = "填空题";
        else if (type == "ShortAnswer")
            questionTypeName = "简答题";
        return questionTypeName;
    }
    public static string ConvertDifficultyLevel(string type)
    {

        string questionTypeName = string.Empty;
        if (type == "Easy")
            questionTypeName = "简单";
        else if (type == "Normal")
            questionTypeName = "普通";
        else if (type == "Hard")
            questionTypeName = "困难";
        return questionTypeName;
    }
    public static void ValidForm(FromGhre_QuestionPageData model)
    {
        if (model.baseData.courseID is null || (model.baseData.courseID != null && !model.baseData.courseID.Any()))
            throw new Exception("课程必填！");

        var questionType = model.questionType.Where(x => x.isActive == 1).FirstOrDefault();

        if (questionType is null)
            throw new Exception("提交参数异常！");
        if (string.IsNullOrWhiteSpace(questionType.detail.difficulty))
            throw new Exception("难易程度必填！");

        if (string.IsNullOrWhiteSpace(ConvertDifficultyLevel(questionType.detail.difficulty)))
            throw new Exception("无效的难易程度类型！");
        if (string.IsNullOrWhiteSpace(questionType.detail.content))
            throw new Exception("题目内容必填！");
        if (questionType.detail.answerList is null || (questionType.detail.answerList != null && !questionType.detail.answerList.Any()))
            throw new Exception(questionType.type == "ShortAnswer" ? "关键词未填写！" : "答案选项必填！");
        if (questionType.detail.answerList.Count < 2 && questionType.type != "ShortAnswer" && questionType.type != "Completion")
            throw new Exception("答案选项不能少于两个！");

        if ((questionType.type == "Single" || questionType.type == "TrueOrFalse") && string.IsNullOrWhiteSpace(questionType.detail.answer))
            throw new Exception("正确答案未标记！");
        else if (questionType.type == "Multiple" && (questionType.detail.answer1 == null || (questionType.detail.answer1 != null && !questionType.detail.answer1.Any())))
            throw new Exception("正确答案未标记！");

        if (questionType.type == "Multiple" && questionType.detail.answer1.Count < 2)
            throw new Exception("答案至少需标记处两个正确答案！");

        if (string.IsNullOrWhiteSpace(questionType.detail.RemarkSz))
            throw new Exception("题目解析必填！");
    }
}