using Org.BouncyCastle.Crypto;

namespace Tiobon.Core.Services;

/// <summary>
/// 问卷题库 (服务)
/// </summary>
public class Ghre_SurveyQuestionPoolServices : BaseServices<Ghre_SurveyQuestionPool, Ghre_SurveyQuestionPoolDto, InsertGhre_SurveyQuestionPoolInput, EditGhre_SurveyQuestionPoolInput>, IGhre_SurveyQuestionPoolServices
{
    private readonly IBaseRepository<Ghre_SurveyQuestionPool> _dal;
    private IGhre_SurveyQuestionPoolOptionServices _ghre_SurveyQuestionPoolOptionServicesServices;
    public Ghre_SurveyQuestionPoolServices(IBaseRepository<Ghre_SurveyQuestionPool> dal,
        ICaching caching,
        IGhre_SurveyQuestionPoolOptionServices ghre_SurveyQuestionPoolOptionServices)
    {
        base.BaseDal = dal;
        base._caching = caching;

        _ghre_SurveyQuestionPoolOptionServicesServices = ghre_SurveyQuestionPoolOptionServices;
    }

    public override async Task<ServicePageResult<Ghre_SurveyQuestionPoolDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {

        var result = await base.QueryFilterPage(filter, condition, IsEnable);


        var ids = result.result.DT_TableDataT1.Select(x => x.Id).ToList();
        var answers = await _ghre_SurveyQuestionPoolOptionServicesServices.Query(x => x.SurveyQuestionPoolId != null && ids.Contains(x.SurveyQuestionPoolId.Value), "TaxisNo ASC");

        //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);
        //    if (x.CourseIds.IsNotEmptyOrNull())
        //    {

        //        var courseClass = courses.Where(a => x.CourseIds.Contains(a.Id.ToString())).ToList();
        //        x.CourseName = string.Join("，", courseClass.Select(a => a.CourseName + " (" + a.CourseNo + ")"));
        //    }
        //    x.BuiltInLabel = x.BuiltIn == 1 ? "是" : "否";
        //});

        result.result.DT_TableDataT1.ForEach(async x =>
        {
            x.BuiltInLabel = x.BuiltIn == 1 ? "是" : "否";
            if (filter.menuName.IsNotEmptyOrNull())
                x.QuestionType = await GetParaLabel("SurveyQuestionType", x.QuestionType);

            x.Options = answers.Where(o => o.SurveyQuestionPoolId == x.Id)
            .Select(x => new InsertGhre_SurveyOptionExtend()
            {
                OptionNo = x.OptionNo,
                OptionContent = x.OptionContent,
                IsOther = x.IsOther,
                ImageUrl = x.ImageUrl,
                ImageWidthPc = x.ImageWidthPc,
                ImageWidthApp = x.ImageWidthApp,
                Score = x.Score,
            }).ToList();
        });



        return result;
    }

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

        #region Column
        data.Column.Add(new FromGhre_QuestionColumn()
        {
            label = "系统内置",
            field = "BuiltIn",
            elementType = "Switch",
            required = false,
            multipleSelect = false,
            editable = true,
            dataSource = "",
            placeholder = "保存后自动生成"
        });

        #endregion

        #region PageData


        var options = new List<InsertGhre_SurveyOptionExtend>
        {
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo= "A",
                OptionContent="非常满意",
                Score=5
            },
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo="B",
                OptionContent= "满意",
                Score= 4,
            },
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo="C",
                OptionContent= "一般",
                Score= 3,
            },
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo="D",
                OptionContent= "不满意",
                Score= 2,
            },
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo="E",
                OptionContent= "非常不满意",
                Score=1
            }
        };


        var options1 = new List<InsertGhre_SurveyOptionExtend>
        {
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo= "A",
                OptionContent="非常满意",
                Score=5
            },
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo="B",
                OptionContent= "满意",
                Score= 4,
            },
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo="C",
                OptionContent= "一般",
                Score= 3,
            },
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo="D",
                OptionContent= "不满意",
                Score= 2,
            },
            new InsertGhre_SurveyOptionExtend()
            {
                OptionNo="E",
                OptionContent= "非常不满意",
                Score=1
            }
        };
        data.PageData.questionType = new List<FromGhre_SurveyQuestionPoolType>
        {
            new FromGhre_SurveyQuestionPoolType()
            {
                QuestionContent = "单选题",
                QuestionType = "Single",
                isActive = 1,
                Options=options
            },
            new FromGhre_SurveyQuestionPoolType()
            {
                QuestionContent = "多选题",
                QuestionType = "Multiple",
                isActive = 0,
              Options=options
            },
            new FromGhre_SurveyQuestionPoolType()
            {
                QuestionContent = "简答",
                QuestionType = "ShortAnswer",
                isActive = 0
            },
            new FromGhre_SurveyQuestionPoolType()
            {
                QuestionContent = "单选评分",
                QuestionType = "SingleScore",
                isActive = 0,
                Options=options
            },
            new FromGhre_SurveyQuestionPoolType()
            {
                QuestionContent = "多选评分",
                QuestionType = "MultipleScore",
                isActive = 0,
                Options=options
            },
            new FromGhre_SurveyQuestionPoolType()
            {
                QuestionContent = "评分",
                QuestionType = "Rate",
                isActive = 0,
                StartTips= "很不满意",
                EndTips="非常满意",
                QuestionIcon="ghr-survey-icon0"
            },
            new FromGhre_SurveyQuestionPoolType()
            {
                QuestionContent = "量表",
                QuestionType = "Scale",
                isActive = 0,
                StartTips= "很不满意",
                EndTips="非常满意",
                QuestionIcon="ghr-survey-icon0"
            }
        };

        if (Id != 0)
        {
            var question = await base.QueryById(Id);
            var questionType = data.PageData.questionType.Where(x => x.QuestionType == question.QuestionType).FirstOrDefault();
            if (questionType != null)
            {
                var answers = await _ghre_SurveyQuestionPoolOptionServicesServices.Query(x => x.SurveyQuestionPoolId == Id, "TaxisNo ASC");
                questionType.isActive = 1;
                questionType.QuestionContent = question.QuestionContent;
                questionType.BuiltIn = question.BuiltIn;
                questionType.QuestionAnalysis = question.QuestionAnalysis;

                questionType.Options = answers.Select(x => new InsertGhre_SurveyOptionExtend()
                {
                    OptionNo = x.OptionNo,
                    OptionContent = x.OptionContent,
                    IsOther = x.IsOther,
                    ImageUrl = x.ImageUrl,
                    ImageWidthPc = x.ImageWidthPc,
                    ImageWidthApp = x.ImageWidthApp,
                    Score = x.Score,
                }).ToList();
            }

            data.PageData.baseData.CreateDataInfo = question.CreateDataInfo;
            data.PageData.baseData.UpdateDataInfo = question.UpdateDataInfo;
            data.PageData.baseData.BuiltIn = question.BuiltIn;
        }
        #endregion
        return ServiceResult<FromGhre_SurveyQuestionPoolInput>.OprateSuccess("查询成功！", data);
    }

    public async Task<ServiceResult> InsertFrom(FromGhre_SurveyQuestionPoolPageData insertModel)
    {
        var questionType = insertModel.questionType.Where(x => x.isActive == 1).FirstOrDefault();


        await Db.Ado.BeginTranAsync();

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

            var insert = new InsertGhre_SurveyQuestionPoolInput();
            insert.BuiltIn = insertModel.baseData.BuiltIn;

            insert.QuestionType = questionType.QuestionType;
            insert.QuestionNo = await GenerateContinuousSequence(insert.QuestionType.Substring(0, 1));
            insert.QuestionContent = questionType.QuestionContent;
            insert.QuestionAnalysis = questionType.QuestionAnalysis;

            var id = await base.Add(insert);

            var insertAnswers = questionType.Options.Select(x => new InsertGhre_SurveyQuestionPoolOptionInput()
            {
                OptionNo = x.OptionNo,
                OptionContent = x.OptionContent,
                Score = x.Score,
                IsOther = x.IsOther,
                ImageUrl = x.ImageUrl,
                ImageWidthPc = x.ImageWidthPc,
                ImageWidthApp = x.ImageWidthApp,
            }).ToList();
            int i = 100;
            insertAnswers.ForEach(x =>
            {
                x.TaxisNo = i;
                x.SurveyQuestionPoolId = id;
                i = i + 100;
            });


            await _ghre_SurveyQuestionPoolOptionServicesServices.Add(insertAnswers);
            //}
            await Db.Ado.CommitTranAsync();
            return ServiceResult.OprateSuccess("新增成功！");
        }
        catch (Exception)
        {
            await Db.Ado.RollbackTranAsync();
            throw;
        }
    }
    //{
    //    var question = Mapper.Map(insertModel).ToANew<Ghre_SurveyQuestionPool>();

    //    question.QuestionNo = await GenerateContinuousSequence("Q");
    //    var questionId = await Db.Insertable(question).ExecuteReturnSnowflakeIdAsync();

    //    for (int j = 0; j < insertModel.Options.Count; j++)
    //    {
    //        var option = Mapper.Map(insertModel.Options[j]).ToANew<Ghre_SurveyQuestionPoolOption>();
    //        option.SurveyQuestionPoolId = questionId;
    //        option.SortNo = j;
    //        await Db.Insertable(option).ExecuteReturnSnowflakeIdAsync();
    //    }
    //    return ServiceResult.OprateSuccess("新增成功！");

    //}

    public async Task<ServiceResult> UpdateFrom(long Id, FromGhre_SurveyQuestionPoolPageData editModel)
    {
        var questionType = editModel.questionType.Where(x => x.isActive == 1).FirstOrDefault();


        await Db.Ado.BeginTranAsync();

        try
        {
            string questionTypeName = ConvertQuestionType(questionType.QuestionType);
            var data = await base.QueryById(Id);

            var insert = Mapper.Map(data).ToANew<EditGhre_SurveyQuestionPoolInput>();
            await _ghre_SurveyQuestionPoolOptionServicesServices.Delete(x => x.SurveyQuestionPoolId == Id);

            insert.BuiltIn = editModel.baseData.BuiltIn;

            insert.QuestionType = questionType.QuestionType;
            insert.QuestionContent = questionType.QuestionContent;
            insert.QuestionAnalysis = questionType.QuestionAnalysis;

            await base.Update(Id, insert);

            var insertAnswers = questionType.Options.Select(x => new InsertGhre_SurveyQuestionPoolOptionInput()
            {
                OptionNo = x.OptionNo,
                OptionContent = x.OptionContent,
                Score = x.Score,
                IsOther = x.IsOther,
                ImageUrl = x.ImageUrl,
                ImageWidthPc = x.ImageWidthPc,
                ImageWidthApp = x.ImageWidthApp,
            }).ToList();
            int i = 100;
            insertAnswers.ForEach(x =>
            {
                x.TaxisNo = i;
                x.SurveyQuestionPoolId = Id;
                i = i + 100;
            });


            await _ghre_SurveyQuestionPoolOptionServicesServices.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_SurveyQuestionPool";
            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 string ConvertQuestionType1(string type)
    {
        string questionTypeName = string.Empty;
        if (type == "单选题")
            questionTypeName = "Single";
        else if (type == "多选题")
            questionTypeName = "Multiple";
        else if (type == "判断题")
            questionTypeName = "TrueOrFalse";
        else if (type == "填空题")
            questionTypeName = "Completion";
        else if (type == "简答题")
            questionTypeName = "ShortAnswer";
        return questionTypeName;
    }
    public static string ConvertDifficultyLevel1(string type)
    {

        string questionTypeName = string.Empty;
        if (type == "简单")
            questionTypeName = "Easy";
        else if (type == "普通")
            questionTypeName = "Normal";
        else if (type == "困难")
            questionTypeName = "Hard";
        return questionTypeName;
    }

    //public static void ValidForm(FromGhre_SurveyQuestionPoolPageData 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("题目解析必填！");
    //}

}