namespace Tiobon.Core.Services;

/// <summary>
/// 面试工单 (服务)
/// </summary>
public class Ghrh_InterviewOrderServices : BaseServices<Ghrh_InterviewOrder, Ghrh_InterviewOrderDto, InsertGhrh_InterviewOrderInput, EditGhrh_InterviewOrderInput>, IGhrh_InterviewOrderServices
{
    private readonly IBaseRepository<Ghrh_InterviewOrder> _dal;
    private readonly IGhrh_InterviewRecordServices _ghrh_InterviewRecordServices;
    public Ghrh_InterviewOrderServices(ICaching caching,
        IGhrh_InterviewRecordServices ghrh_InterviewRecordServices,
        IBaseRepository<Ghrh_InterviewOrder> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
        _ghrh_InterviewRecordServices = ghrh_InterviewRecordServices;
    }


    public override async Task<long> Add(InsertGhrh_InterviewOrderInput entity)
    {
        var result = await base.Add(entity);
        if (entity.RequestId != null)
            await Db.Updateable<Ghrh_HumanRequest>()
                 .SetColumns(it => it.RecommendCount == it.RecommendCount + 1)
                 .Where(it => it.Id == entity.RequestId)
                 .ExecuteCommandAsync();

        return result;
    }

    public override async Task<List<Ghrh_InterviewOrderDto>> QueryDto(Expression<Func<Ghrh_InterviewOrder, bool>> whereExpression)
    {
        var data = await base.QueryDto(whereExpression);
        var ids = data.Select(x => x.Id).ToList();
        var records = await _ghrh_InterviewRecordServices.Query(x => x.OrderId != null && ids.Contains(x.OrderId.Value));

        data.ForEach(x =>
        {
            var record = records.Where(o => x.Round == o.Round && o.OrderId == x.Id).FirstOrDefault();

            if (record != null)
            {
                if (record.PlanInterviewTime1.IsNotEmptyOrNull())
                    x.OptionalInterviewTime += record.PlanInterviewTime1;
                if (record.PlanInterviewTime2.IsNotEmptyOrNull())
                    x.OptionalInterviewTime += "," + record.PlanInterviewTime2;
                if (record.PlanInterviewTime3.IsNotEmptyOrNull())
                    x.OptionalInterviewTime += "," + record.PlanInterviewTime3;
                x.InterviewTime = record.InterviewTime;
                x.InterviewAddress = record.InterviewAddress;
            }
        });

        return data;
    }

    #region 查询
    public override async Task<ServicePageResult<Ghrh_InterviewOrderDto>> 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_InterviewOrder);

        var countSql = @$" SELECT COUNT(1) FROM  Ghrh_InterviewOrder_V";
        var sql1 = @$"DECLARE @langId   INT = {filter.langId};";
        var sql = @$" SELECT * 
                    FROM Ghrh_InterviewOrder_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;

        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))
                    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_InterviewOrderDto>(sql);

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

        var list = result.result.DT_TableDataT1;
        var tagIds = new List<long>();

        list.ForEach(x =>
        {
            if (x.Tag.IsNotEmptyOrNull())
                tagIds.AddRange(JsonHelper.JsonToObj<List<long>>(x.Tag));
        });

        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]; 
            entity.CertificateType = await GetParaLabel("D51", entity.CertificateType);
            entity.EduDegree = await GetParaLabel("EducationalBGLevel", entity.EduDegree);
            entity.Gender = await GetParaLabel("Gender", entity.Gender);

            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;
            }  
            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);
                }
            }
        }

        return result;
    }
    #endregion
}