using AgileObjects.AgileMapper.Extensions;

namespace Tiobon.Core.Services;

/// <summary>
/// 招聘模板 (服务)
/// </summary>
public class Ghrh_TemplateServices : BaseServices<Ghrh_Template, Ghrh_TemplateDto, InsertGhrh_TemplateInput, EditGhrh_TemplateInput>, IGhrh_TemplateServices
{
    private readonly IBaseRepository<Ghrh_Template> _dal;
    public Ghrh_TemplateServices(ICaching caching, IBaseRepository<Ghrh_Template> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
    }

    #region 是否开启
    public async Task<ServiceResult> SwitchPublish(long id, int? isPublish)
    {
        //await Db.Updateable<Ghrh_Template>()
        //    .SetColumns(it => new Ghrh_Template()
        //    {
        //        IsPublish = 0,
        //        UpdateBy = App.User.ID,
        //        UpdateTime = DateTime.Now
        //    })
        //   .Where(it => it.IsPublish == 1)
        //   .ExecuteCommandAsync();
        await Db.Updateable<Ghrh_Template>()
            .SetColumns(it => new Ghrh_Template()
            {
                IsPublish = isPublish,
                UpdateBy = App.User.ID,
                UpdateTime = DateTime.Now
            })
           .Where(it => it.Id == id)
           .ExecuteCommandAsync();
        return ServiceResult.OprateSuccess();
    }
    #endregion

    #region 获取Offer模板字段
    public async Task<ServiceResult<List<CustomFieldView>>> QueryOfferTags()
    {
        int? extColumCount = 5;
        var config = await Db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_Custom_Offer_Ext_Column_Count").FirstAsync();
        if (config != null)
        {
            try
            {
                extColumCount = config?.ConfigValue.ObjToInt();
            }
            catch (Exception)
            {

            }
        }
        var extColumnFields = new List<ModelTagView2Item>();
        var extColumnFields1 = new List<ModelTagView2Item>();

        for (int i = 1; i <= extColumCount; i++)
        {
            extColumnFields.Add(new ModelTagView2Item()
            {
                Name = "扩展栏位" + i,
                Code = "扩展栏位" + i,
            });
            extColumnFields1.Add(new ModelTagView2Item()
            {
                Name = "ExtField" + i,
                Code = "ExtField" + i
            });
        }

        var list = new List<CustomFieldView>()
            {
                new CustomFieldView {
                    GroupName = "中文",
                    Fields = StringHelper.GetFieldDesc<OfferTemplate>().Select(o => new ModelTagView2Item { Name=o.Key,Code=o.Key}).ToList(),
                    ExtFields = extColumnFields
                },
                new CustomFieldView {
                    GroupName = "英文",
                    Fields = StringHelper.GetFieldDesc<OfferTemplate>().Select(o => new ModelTagView2Item { Name=o.Value+"_EN",Code=o.Value+"_EN"}).ToList(),
                    ExtFields = extColumnFields1
                },
            };
        return await Task.FromResult(ServiceResult<List<CustomFieldView>>.OprateSuccess("查询成功！", list));
    }
    #endregion

    #region 预览Offer简历
    public async Task<ServiceResult<string>> Preview(long resumeId, long templateId, Dictionary<string, string> extFields)
    {
        var resume = await Db.Queryable<Ghrh_Resume>().Where(x => x.Id == resumeId).SingleAsync();
        var result = string.Empty;
        var template = await base.QuerySingle(x => x.Id == templateId);
        if (template != null)
        {
            result = template.TemplateContent;
            if (result.IsNullOrEmpty())
                return await Task.FromResult(ServiceResult<string>.OprateSuccess("查询成功！", result));
            result = result.Replace("[姓名]", resume.StaffName);
            result = result.Replace("[电话]", resume.Mobile);
            result = result.Replace("[邮箱]", resume.Email);
            result = result.Replace("[身份证号码]", resume.IdCardNo);
            result = result.Replace("[StaffName_EN]", resume.StaffEname);
            result = result.Replace("[Mobile_EN]", resume.Mobile);
            result = result.Replace("[Email_EN]", resume.Email);
            result = result.Replace("[IdCardNo_EN]", resume.IdCardNo);
            var offerApplyOrder = await Db.Queryable<Ghrh_OfferApplyOrder>().Where(x => x.ResumeId == resumeId)
                .OrderByDescending(x => x.ApplyTime).FirstAsync();

            if (offerApplyOrder != null)
            {
                #region 岗位
                if (offerApplyOrder.TitleId.IsNotEmptyOrNull())
                {
                    var title = await Db.Queryable<Ghra_Title>().Where(x => x.TitleID == offerApplyOrder.TitleId).SingleAsync();
                    if (title.MKey.IsNotEmptyOrNull())
                    {
                        var lang = await Db.Queryable<Ghrs_LangKey>().Where(x => x.LangKey == title.MKey).SingleAsync();
                        if (lang != null)
                        {
                            result = result.Replace("[TitleName_EN]", lang.Value03);
                            result = result.Replace("[岗位]", lang.LangValue);
                        }

                    }
                }
                #endregion

                #region 汇报对象
                if (offerApplyOrder.ReportId.IsNotEmptyOrNull())
                {
                    var staff = await Db.Queryable<Ghra_Staff>().Where(x => x.StaffID == offerApplyOrder.ReportId).SingleAsync();
                    if (staff != null)
                    {
                        result = result.Replace("[ReportName_EN]", staff.StaffEname ?? staff.StaffName);
                        result = result.Replace("[汇报对象]", staff.StaffName);
                    }
                }
                #endregion

                #region 试用期薪资
                if (offerApplyOrder.ProbationSalary.IsNotEmptyOrNull())
                {
                    result = result.Replace("[Salary_EN]", offerApplyOrder.ProbationSalary.ObjToString());
                    result = result.Replace("[试用期薪资]", offerApplyOrder.ProbationSalary.ObjToString());
                }
                #endregion

                #region 薪资
                if (offerApplyOrder.ProbationSalary.IsNotEmptyOrNull())
                {
                    result = result.Replace("[AfterSalary_EN]", offerApplyOrder.ProbationAfterSalary.ObjToString());
                    result = result.Replace("[薪资]", offerApplyOrder.ProbationAfterSalary.ObjToString());
                }
                #endregion

                #region 入职日期
                if (offerApplyOrder.InDate.IsNotEmptyOrNull())
                {
                    result = result.Replace("[InDate_EN]", DateTimeHelper.ConvertToDayString(offerApplyOrder.InDate));
                    result = result.Replace("[入职日期]", $" {offerApplyOrder.InDate.Value.Year}年  {offerApplyOrder.InDate.Value.Month} 月 {offerApplyOrder.InDate.Value.Day} 日");
                }
                #endregion

                #region 公司类别
                if (offerApplyOrder.CompanyId.IsNotEmptyOrNull())
                {
                    var company = await Db.Queryable<Ghra_LegalCompany>().Where(x => x.LegalCompanyID == offerApplyOrder.CompanyId).SingleAsync();
                    //var sql = $"Select * from Ghra_LegalCompany where LegalCompanyID='{offerApplyOrder.CompanyId}'";
                    result = result.Replace("[CompanyName_EN]", company?.LegalCompanyEname);
                    result = result.Replace("[公司类别]", company?.LegalCompanyName);
                }
                else
                {
                    result = result.Replace("[CompanyName_EN]", null);
                    result = result.Replace("[公司类别]", null);
                }
                #endregion
            }

            int? extColumCount = 5;
            var config = await Db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_Custom_Offer_Ext_Column_Count").FirstAsync();
            if (config != null)
            {
                try
                {
                    extColumCount = config?.ConfigValue.ObjToInt();
                }
                catch (Exception)
                {

                }
            }

            extFields.ForEach(x =>
            {
                result = result.Replace("[" + x.Key + "]", x.Value);
            });


            for (int i = 1; i <= extColumCount; i++)
            {
                result = result.Replace("[ExtField" + i + "]", null);
                result = result.Replace("[扩展栏位" + i + "]", null);
            }

            StringHelper.GetFieldDesc<OfferTemplate>().Select(o => new ModelTagView2Item { Name = o.Value, Code = o.Key }).ToList()
                .ForEach(x =>
                {
                    result = result.Replace("[" + x.Code + "]", null);
                    result = result.Replace("[" + x.Name + "_EN]", null);
                });
        }
        return await Task.FromResult(ServiceResult<string>.OprateSuccess("查询成功！", result));
    }
    #endregion

    public override async Task<ServicePageResult<Ghrh_TemplateDto>> 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_Template);

        var countSql = @$" SELECT COUNT(1) FROM  {entityType.GetEntityTableName()}";
        var sql1 = @$"DECLARE @langId   INT = {filter.langId};";
        var sql = @$" SELECT A.Id,
       A.CreateBy,
       A.CreateTime,
       A.CreateProg,
       A.CreateIP,
       A.UpdateBy,
       A.UpdateTime,
       A.UpdateProg,
       A.UpdateIP,
       A.OperateLogID,
       A.TemplateName,
       A.TemplateType,
       NULL TemplateContent,
       A.IsPublish,
       A.RemarkSz,
       A.IsDefault,
       A.IsEnable,
       A.Reverse1,
       A.Reverse2,
       A.Reverse3,
       A.Reverse4,
       A.Reverse5,
       A.Reverse6,
       A.Reverse7,
       A.Reverse8,
       A.Reverse9,
       A.Reverse10,
       A.ReverseI1,
       A.ReverseI2,
       ISNULL ((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
                FROM Ghrs_User B
                WHERE B.UserId = A.CreateBy),
               '') CreateDataInfo,
       ISNULL ((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
                FROM Ghrs_User B
                WHERE B.UserId = A.UpdateBy),
               '') UpdateDataInfo,
       ISNULL (A.UpdateTime, A.CreateTime) CreateTime1
FROM Ghrh_Template 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" || !properties.Any(x => x.Name == name))
                    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_TemplateDto>(sql);

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

    }
}