
using Tiobon.Core.IServices;
using Tiobon.Core.Model.Models;
using Tiobon.Core.Services.BASE;
using Tiobon.Core.IRepository.Base;
using Tiobon.Core.Common.Caches;
using Newtonsoft.Json.Linq;
using Tiobon.Core.Common;
using Tiobon.Core.Model;
using Newtonsoft.Json;
using Tiobon.Core.Common.Helper;
using Org.BouncyCastle.Crypto;
using SqlSugar;
using MathNet.Numerics.Distributions;
using MongoDB.Driver.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;

namespace Tiobon.Core.Services;

/// <summary>
/// 必选修规则 (服务)
/// </summary>
public class Ghre_StudyRuleServices : BaseServices<Ghre_StudyRule, Ghre_StudyRuleDto, InsertGhre_StudyRuleInput, EditGhre_StudyRuleInput>, IGhre_StudyRuleServices
{
    private readonly IBaseRepository<Ghre_StudyRule> _dal;
    private readonly IGhre_CourseServices _ghre_CourseServices;
    private readonly IGhre_CourseSceneServices _ghre_CourseSceneServices;
    private readonly IGhre_StudyRuleStaffServices _ghre_StudyRuleStaffServices;
    public Ghre_StudyRuleServices(ICaching caching,
        IGhre_CourseServices ghre_CourseServices,
        IGhre_CourseSceneServices ghre_CourseSceneServices,
        IGhre_StudyRuleStaffServices ghre_StudyRuleStaffServices,
        IBaseRepository<Ghre_StudyRule> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
        _ghre_CourseServices = ghre_CourseServices;
        _ghre_CourseSceneServices = ghre_CourseSceneServices;
        _ghre_StudyRuleStaffServices = ghre_StudyRuleStaffServices;
    }


    public override async Task<ServicePageResult<Ghre_StudyRuleDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {
        if (string.IsNullOrWhiteSpace(filter.orderBy))
            filter.orderBy = "CreateTime1 DESC";

        if (filter.pageSize == 0)
            filter.pageSize = 10000;

        var countSql = @$" SELECT COUNT(1) FROM  Ghre_StudyRule_V";
        var sql = @$" SELECT *
                    FROM Ghre_StudyRule_V  A";

        string conditions = " WHERE 1=1 ";

        if (IsEnable == true)
            conditions += " AND IsEnable = 1";
        else if (IsEnable == false)
            conditions += " AND IsEnable = 0";

        if (!string.IsNullOrWhiteSpace(condition))
            conditions += " AND " + condition;


        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 == "StaffId")
                {

                    var jsonParam = JsonHelper.JsonToObj<JsonParam>(value);
                    var ids1 = JsonHelper.JsonToObj<List<string>>(jsonParam.columnValue.ToString());
                    if (ids1 is null)
                        continue;
                    string sql1 = $"SELECT DISTINCT B.Id from Ghre_StudyRuleStaff A join Ghre_StudyRule B ON A.StudyRuleId = B.ID WHERE B.IsEnable=1 AND A.StaffId IN ({string.Join(",", ids1.Select(id => "'" + id + "'"))})";
                    ids1 = await Db.Ado.SqlQueryAsync<string>(sql1);
                    switch (jsonParam.operationKey)
                    {
                        case "EqualAny"://  
                            conditions += $"  AND  Id IN ({string.Join(",", ids1.Select(id => "'" + id + "'"))})";
                            break;
                        case "NotEqualAny"://  
                            conditions += $" AND Id NOT IN ({string.Join(",", ids1.Select(id => "'" + id + "'"))})";

                            break;
                        default:
                            break;
                    }

                    continue;
                }
                if (!string.IsNullOrWhiteSpace(value))
                    conditions = DealConditions(conditions, name, value);
            }

        sql += conditions;
        countSql += conditions;
        int total = await Db.Ado.GetIntAsync(countSql);

        sql = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY " + filter.orderBy + ") NUM FROM (SELECT * FROM (" + sql + " ";
        sql += ") A ) B ) C";

        sql += " WHERE NUM <= " + filter.pageNum * filter.pageSize + " AND NUM >" + (filter.pageNum - 1) * filter.pageSize;

        var entitys = await Db.Ado.SqlQueryAsync<Ghre_StudyRuleDto>(sql);

        var ids = entitys.Select(x => x.Id).ToList();
        var staffs = await _ghre_StudyRuleStaffServices.Query(x => x.StudyRuleId != null && ids.Contains(x.StudyRuleId.Value));

        entitys.ForEach(x =>
        {
            x.StaffNames = string.Join(",", staffs.Where(o => o.StudyRuleId == x.Id).Select(o => o.StaffName));
        });

        return new ServicePageResult<Ghre_StudyRuleDto>(filter.pageNum, total, filter.pageSize, entitys);

    }


    public override async Task<long> Add(InsertGhre_StudyRuleInput entity)
    {
        var result = await base.Add(entity);

        if (entity.Staffs != null && entity.Staffs.Any())
        {
            var insertStaffs = entity.Staffs.Select(x => new InsertGhre_StudyRuleStaffInput
            {
                StaffId = x,
                StudyRuleId = result
            }).ToList();
            await _ghre_StudyRuleStaffServices.Add(insertStaffs);
        }

        string sql = @"UPDATE A
                    SET A.StaffName = B.StaffName
                    FROM Ghre_StudyRuleStaff A LEFT JOIN Ghra_Staff B ON A.StaffId = B.StaffID
                    WHERE A.StaffName IS NULL";
        await Db.Ado.ExecuteCommandAsync(sql);

        await Task.Factory.StartNew(async () => await GenerateStaffStudyRecord(Db, result));
        return result;
    }

    public override async Task<bool> Update(long Id, EditGhre_StudyRuleInput editModel)
    {
        var result = await base.Update(Id, editModel);
        await _ghre_StudyRuleStaffServices.Delete(x => x.StudyRuleId == Id);


        if (editModel.Staffs != null && editModel.Staffs.Any())
        {
            var insertStaffs = editModel.Staffs.Select(x => new InsertGhre_StudyRuleStaffInput
            {
                StaffId = x,
                StudyRuleId = Id
            }).ToList();
            await _ghre_StudyRuleStaffServices.Add(insertStaffs);
        }

        string sql = @"UPDATE A
                    SET A.StaffName = B.StaffName
                    FROM Ghre_StudyRuleStaff A LEFT JOIN Ghra_Staff B ON A.StaffId = B.StaffID
                    WHERE A.StaffName IS NULL";
        await Db.Ado.ExecuteCommandAsync(sql);

        await Task.Factory.StartNew(async () => await GenerateStaffStudyRecord(Db, Id));
        return result;
    }

    public override async Task<ServiceFormResult<Ghre_StudyRuleDto>> QueryForm(QueryForm body)
    {
        var result = await base.QueryForm(body);

        if (result.result.DT_TableDataT1.Any())
        {

            var staffs = await _ghre_StudyRuleStaffServices.Query(x => x.StudyRuleId != null && x.StudyRuleId == result.result.DT_TableDataT1[0].Id);

            var DT_TableDataT1 = result.result.DT_TableDataT1;
            DT_TableDataT1.ForEach(t =>
            {
                t.Staffs = staffs.Where(x => x.StaffId != null).Select(x => x.StaffId.Value).ToList();
            });

            result.result.DT_TableDataT1 = DT_TableDataT1;
        }
        return result;
    }

    public async Task<bool> GenerateStaffStudyRecord(ISqlSugarClient Db, long ruleId)
    {
        try
        {
            await Db.Ado.BeginTranAsync();

            var rule = await Db.Queryable<Ghre_StudyRule>().FirstAsync(x => x.Id == ruleId);

            var ruleStaffs = await Db.Queryable<Ghre_StudyRuleStaff>().Where(x => x.StudyRuleId == ruleId).ToListAsync();

            await Db.Updateable<Ghre_StudyRuleResult>().Where(x => x.StudyRuleId == ruleId && x.IsEnable == 1)
                .SetColumns(it => new Ghre_StudyRuleResult() { IsEnable = 0 })
                .ExecuteCommandAsync();

            var ruleStaffIds = ruleStaffs.Select(x => x.StaffId).ToList();

            var staffs = await Db.Queryable<Ghra_Staff>()
                .Where(x => x.OutDate == null || (x.OutDate != null && x.Indate != null && x.Indate.Value.Date <= DateTime.Now.Date && x.Indate.Value.Date >= DateTime.Now.Date))
                .WhereIF(!rule.ZoneId.IsNull(), x => x.ZoneID == rule.ZoneId)
                .WhereIF(!rule.DeptId.IsNull(), x => x.DeptID == rule.DeptId)
                .WhereIF(!rule.TitleId.IsNull(), x => x.TitleID == rule.TitleId)
                .WhereIF(!rule.GradeId.IsNull(), x => x.GradeID == rule.GradeId)
                .WhereIF(!rule.JobId.IsNull(), x => x.JobID == rule.JobId)
                .WhereIF(!ruleStaffIds.IsNull() && ruleStaffIds.Any(), x => ruleStaffIds.Contains(x.StaffID))
                .WhereIF(!rule.GradeId.IsNull(), x => x.GradeID == rule.GradeId)
                .ToListAsync();

            if (!staffs.IsNull())
            {
                DateTime courseTime = Db.GetDate();
                var snap = await Db.Queryable<Ghre_CourseSnap>().FirstAsync(x => x.CourseId == rule.CourseId);

                if (staffs.Any())
                {
                    var inserts = new List<Ghre_StudyRecord>();
                    var insertExamStaffs = new List<Ghre_ExamStaff>();
                    var insertResults = new List<Ghre_StudyRuleResult>();
                    await Db.Deleteable<Ghre_StudyRecord>().Where(x => x.StudyRuleId == ruleId && x.BeginTime == null).ExecuteCommandAsync();
                    await Db.Deleteable<Ghre_ExamStaff>().Where(x => x.StudyRuleId == ruleId).ExecuteCommandAsync();

                    //var exam = await Db.Queryable<Ghre_Exam>()
                    //        .WhereIF(rule.CourseId != null, x => x.CourseId == rule.CourseId)
                    //        .WhereIF(rule.CourseSceneId != null, x => x.CourseSceneId == rule.CourseSceneId)
                    //        .FirstAsync(x => x.Status == Consts.DicExamStatus.RELEASED);

                    var exam = await Db.Queryable<Ghre_Exam>()
                       .Where(x => x.Status == Consts.DIC_EXAM_STATUS.RELEASED
                       && ((x.DateType == Consts.DicExamDateType.EXAM_DATE
                       && x.BeginTime.Value.Date <= DateTime.Now.Date && x.EndTime.Value.Date >= DateTime.Now.Date) || x.DateType == Consts.DicExamDateType.AFTER_HOW_LONG))
                       .WhereIF(!rule.CourseId.IsNull(), x => x.CourseId == rule.CourseId)
                       .WhereIF(!rule.CourseSceneId.IsNull(), x => x.CourseSceneId == rule.CourseSceneId)
                       .FirstAsync();

                    for (int i = 0; i < staffs.Count; i++)
                    {
                        var staff = staffs[i];

                        var record = await Db.Queryable<Ghre_StudyRecordDto>()
                            .Where(x => x.StudyRuleId != ruleId && x.StaffId == staff.StaffID)
                            .WhereIF(!string.IsNullOrWhiteSpace(rule.Year), x => x.Year == rule.Year)
                            .WhereIF(rule.CourseId != null, x => x.CourseId == rule.CourseId)
                            .WhereIF(rule.CourseSceneId != null, x => x.CourseSceneId == rule.CourseSceneId)
                            .AS("Ghre_StudyRecord_V").FirstAsync();
                        if (record is null)
                        {
                            inserts.Add(new Ghre_StudyRecord()
                            {
                                StaffId = staff.StaffID,
                                ExamId = exam?.Id,
                                CourseSnapId = snap?.Id,
                                CourseId = rule.CourseId,
                                CourseSceneId = rule.CourseSceneId,
                                StudyRuleId = ruleId,
                                JoinTime = courseTime,
                                CourseBeginTime = courseTime.Date,
                                CourseEndTime = courseTime.Date.AddMonths((rule.DeadlineMonth ?? snap?.ValidityPeriod) ?? 1),
                                CourseType = rule.RuleType,
                                CourseStatus = Consts.DIC_STUDY_RECORD_COURSE_STATUS_IN,
                                StudyStatus = Consts.DicStudyRecordStudyStatus.NO_JOIN,
                                Year = rule.Year
                            });
                            insertResults.Add(new Ghre_StudyRuleResult()
                            {
                                StaffId = staff.StaffID,
                                StudyRuleId = ruleId,
                                Status = "SUCCESS",
                                RemarkSz = "生成成功"
                            });

                            if (exam != null)
                                if (!await Db.Queryable<Ghre_ExamStaff>().AnyAsync(x => x.ExamId == exam.Id && x.StaffId == staff.StaffID))
                                    insertExamStaffs.Add(new Ghre_ExamStaff()
                                    {
                                        ExamId = exam.Id,
                                        StudyRuleId = ruleId,
                                        StaffId = staff.StaffID,
                                        Source = "StudyRule" + rule.RuleType
                                    });
                        }
                        else insertResults.Add(new Ghre_StudyRuleResult()
                        {
                            StaffId = staff.StaffID,
                            StudyRuleId = ruleId,
                            Status = "FAIL",
                            RemarkSz = "生成失败，该课程学习记录已被其他规则生成！"
                        });
                    }

                    if (inserts.Any())
                        await Db.Insertable(inserts).ExecuteReturnSnowflakeIdListAsync();
                    if (insertResults.Any())
                        await Db.Insertable(insertResults).ExecuteReturnSnowflakeIdListAsync();

                    if (insertExamStaffs.Any())
                        await Db.Insertable(insertExamStaffs).ExecuteReturnSnowflakeIdListAsync();

                    rule.Result = "数据生成成功";

                }
                else
                    rule.Result = "未匹配到相关关人员数据！";

                await Db.Updateable<Ghre_StudyRule>().Where(x => x.Id == ruleId)
                    .SetColumns(it => new Ghre_StudyRule() { Result = rule.Result })//类只能在表达示里面不能提取
                    .ExecuteCommandAsync();
            }

            await Db.Ado.CommitTranAsync();

            string sql = @"UPDATE A
                        SET A.StaffName = B.StaffName, a.StaffNo = B.StaffNo
                        FROM Ghre_StudyRuleResult A LEFT JOIN Ghra_Staff B ON A.StaffId = B.StaffID
                        WHERE A.StaffName IS NULL";
            await Db.Ado.ExecuteCommandAsync(sql);
        }
        catch (Exception)
        {
            await Db.Ado.RollbackTranAsync();

        }
        return true;
    }
}