namespace Tiobon.Core.Services;

/// <summary>
/// 面试记录 (服务)
/// </summary>
public class Ghrh_InterviewRecordServices : BaseServices<Ghrh_InterviewRecord, Ghrh_InterviewRecordDto, InsertGhrh_InterviewRecordInput, EditGhrh_InterviewRecordInput>, IGhrh_InterviewRecordServices
{
    private readonly IBaseRepository<Ghrh_InterviewRecord> _dal;
    public Ghrh_InterviewRecordServices(ICaching caching, IBaseRepository<Ghrh_InterviewRecord> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
    }

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

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

        Type entityType = typeof(Ghrh_InterviewRecord);

        var countSql = @$" SELECT COUNT(1) FROM Ghrh_InterviewRecord_V A";
        var sql1 = @$"DECLARE @langId   INT = {filter.langId};";
        var sql = @$" SELECT A.* FROM
                           Ghrh_InterviewRecord_V A";

        string conditions = " WHERE 1=1 ";

        if (IsEnable == true)
            conditions += " AND A.IsEnable = 1";
        else if (IsEnable == false)
            conditions += " AND A.IsEnable = 0";
        conditions += " AND A.IsPrimary = 'true'";

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

        var properties = entityType.GetGenericProperties();

        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))
                {
                    //if (name == "RequestNo")
                    //    conditions = DealConditions(conditions, "C." + name, value);
                    //else if (name == "IsPass")
                    //{
                    //    var jsonParam = JsonHelper.JsonToObj<JsonParam>(value);
                    //    if (jsonParam.columnValue.ObjToBool())
                    //        conditions += $" AND A.IsPass='true'";
                    //    else
                    //        conditions += $" AND (A.IsPass !='true' Or A.IsPass IS NULL)";
                    //}
                    //else
                    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;
        sql = sql1 + sql;
        var entitys = await Db.Ado.SqlQueryAsync<Ghrh_InterviewRecordDto>(sql);

        var result = new ServicePageResult<Ghrh_InterviewRecordDto>(filter.pageNum, total, filter.pageSize, entitys);

        var list = result.result.DT_TableDataT1;

        var staffIds = list.Where(x => x.StaffId != null).Select(x => x.StaffId.Value).ToList();
        var orderIds = list.Where(x => x.OrderId != null).Select(x => x.OrderId).ToList();
        //var titleIds = resumes.Where(x => x.TitleId != null).Select(x => x.TitleId.Value).Distinct().ToList();
        //var titles = await Db.Queryable<Ghra_Title>().Where(x => x.TitleID != null && titleIds.Contains(x.TitleID.Value)).ToListAsync();
        var tagIds = new List<long>();
        list.ForEach(x =>
        {
            if (x.Tag.IsNotEmptyOrNull())
                tagIds.AddRange(JsonHelper.JsonToObj<List<long>>(x.Tag));
        });
        var participants = await base.Query(x => orderIds.Contains(x.OrderId) && x.IsPrimary != true);
        if (participants.Any())
            staffIds.AddRange(participants.Where(x => x.StaffId != null).Select(x => x.StaffId.Value));
        staffIds = staffIds.Distinct().ToList();
        var staffs = await Db.Queryable<Ghra_Staff>().Where(x => staffIds.Contains(x.StaffID)).ToListAsync();

        tagIds = tagIds.Distinct().ToList();
        var tags = await Db.Queryable<Ghrh_ResumeTag>().Where(x => tagIds.Contains(x.Id)).ToListAsync();
        for (int i = 0; i < list.Count; i++)
        {
            var entity = list[i];
            if (entity.Tag.IsNotEmptyOrNull())
            {
                var tagIds1 = JsonHelper.JsonToObj<List<long>>(entity.Tag);

                var TagList = tags.Where(o => tagIds1.Contains(o.Id)).Select(o => o.TagName).ToList();
                entity.Tag = string.Join(",", TagList);
            }
            #region 计算年龄
            if (entity.Birthday != null && entity.Birthday > DateTime.MinValue)
            {
                DateTime birthdate = (DateTime)entity.Birthday;
                DateTime now = DateTime.Now;
                int age = now.Year - birthdate.Year;
                if (now.Month < birthdate.Month || (now.Month == birthdate.Month && now.Day < birthdate.Day))
                    age--;
                entity.Age = age;
            }
            #endregion

            switch (entity.Status)
            {
                case "Fail":
                    entity.StatusLabel = "不合适";
                    break;
                case "HasRecommended":
                    entity.StatusLabel = "待预约";
                    break;
                case "Hire":
                    entity.StatusLabel = "不合适";
                    break;
                default:
                    entity.StatusLabel = "已约面";
                    break;
            }

            entity.Interviewer = staffs.Where(x => x.StaffID == entity.StaffId).FirstOrDefault()?.StaffName;
            var participants1 = participants.Where(x => x.StaffId != null && x.OrderId == entity.OrderId && x.IsPrimary != true && x.Round == entity.Round).Select(x => x.StaffId.Value).ToList();
            if (participants1.Any())
                entity.Participant = string.Join("、", staffs.Where(x => participants1.Contains(x.StaffID)).Select(x => x.StaffName));

            if (entity.IdCardNo.IsNotEmptyOrNull())
            {
                int length = entity.IdCardNo.Length;
                if (length > 7)
                {
                    // 只显示前3位和后4位，其余用'*'代替
                    string maskedPart = new string('*', length - 7);
                    entity.IdCardNo = entity.IdCardNo.Substring(0, 3) + maskedPart + entity.IdCardNo.Substring(length - 4);
                }
            }
            entity.CertificateType = await GetParaLabel("D51", entity.CertificateType);
            entity.EduDegree = await GetParaLabel("EducationalBGLevel", entity.EduDegree);
            entity.Gender = await GetParaLabel("Gender", entity.Gender);
            if (entity.IsPass == true)
                entity.InterviewResult = "面试通过";
            else if (entity.IsPass == false)
                entity.InterviewResult = "面试不通过";
        }

        return result;
    }
    #endregion
}