using static Tiobon.Core.Model.Consts;

namespace Tiobon.Core.Services;

/// <summary>
/// 人力需求维护 (服务)
/// </summary>
public class Ghrh_HumanRequestServices : BaseServices<Ghrh_HumanRequest, Ghrh_HumanRequestDto, InsertGhrh_HumanRequestInput, EditGhrh_HumanRequestInput>, IGhrh_HumanRequestServices
{
    private readonly IBaseRepository<Ghrh_HumanRequest> _dal;
    private readonly IGhrh_HumanRequestDetailServices _ghrh_HumanRequestDetailServices;
    public Ghrh_HumanRequestServices(ICaching caching, IBaseRepository<Ghrh_HumanRequest> dal, IGhrh_HumanRequestDetailServices ghrh_HumanRequestDetailServices)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
        _ghrh_HumanRequestDetailServices = ghrh_HumanRequestDetailServices;
    }

    #region 字典映射、全称、单位转换等
    /// <summary>
    /// 字典映射、全称、单位转换等
    /// </summary>
    /// <param name="view"></param>
    private async Task SetLabel(Ghrh_HumanRequestDto x)
    {
        if (x != null)
        {
            x.GenderLabel = await GetParaLabel("Gender", x.Gender);
            x.InOrOutLabel = await GetParaLabel("ResumeBudgetTypr", x.InOrOut);
            x.ImportanceDegreeLabel = await GetParaLabel("ResumeImportanceDegree", x.ImportanceDegree);
            x.InTime1 = DateTimeHelper.ConvertToDayString(x.InTime);
            x.AgeLabel = await GetParaLabel("AgePeriodSetup", x.Age);
            x.ResumeTypeLabel = await GetParaLabel("ResumeType", x.ResumeType);

            if (x.WorkState.IsNotEmptyOrNull())
            {
                if (x.WorkState == 0) x.WorkStateLabel = "审批中";
                if (x.WorkState == 1) x.WorkStateLabel = "审批通过";
            }
        }
    }
    #endregion

    #region 新增
    public override async Task<long> Add(InsertGhrh_HumanRequestInput entity)
    {
        entity.ApplicantId = GetStaffId();
        entity.RequestNo = await GenerateContinuousSequence("Ghrh_HumanRequest", "RequestNo", "R");
        var id = await base.Add(entity);

        var sql = $"SELECT ISNULL(MAX(id)+1,1) FROM Ghrh_HumanRequest WHERE Id !='{id}'";
        var id1 = await Db.Ado.GetLongAsync(sql);
        sql = $"UPDATE Ghrh_HumanRequest SET Id={id1} WHERE  Id ='{id}'";
        if (entity.Quality != null && entity.Quality.Any())
        {
            var qualitys = entity.Quality.Select(x => new InsertGhrh_HumanRequestDetailInput()
            {
                RequestId = id1,
                DetailName = x,
                Source = "Quality"
            }).ToList();
            await _ghrh_HumanRequestDetailServices.Add(qualitys);
        }

        if (entity.Experience != null && entity.Experience.Any())
        {
            var experiences = entity.Experience.Select(x => new InsertGhrh_HumanRequestDetailInput()
            {
                RequestId = id1,
                DetailName = x.value,
                DetailValue = x.text,
                Source = "Experience"
            }).ToList();
            await _ghrh_HumanRequestDetailServices.Add(experiences);
        }
        await Db.Ado.ExecuteCommandAsync(sql);
        return id1;
    }

    public async Task<ServiceResult<long>> InsertByStatus(InsertGhrh_HumanRequestInput insertModel, string status)
    {
        var data = ServiceResult<long>.OprateSuccess("新增成功", 0);
        insertModel.Status = status;
        var id = await Add(insertModel);

        data.Success = id > 0;
        if (data.Success)
            data.Data = id;
        else
            return ServiceResult<long>.OprateFailed("发布成功！");

        return data;
    }
    #endregion

    #region 查询
    public override async Task<ServicePageResult<Ghrh_HumanRequestDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {
        if (condition.IsNotEmptyOrNull())
            condition += $" AND dbo.[FUserDeptPriv] ({App.User.ID}, DeptId, getdate())=1";
        else
            condition = $"dbo.[FUserDeptPriv] ({App.User.ID}, DeptId, getdate())=1";
        var result = await base.QueryFilterPage(filter, condition, IsEnable);
        var entitys = result.result.DT_TableDataT1;

        var deptIds = entitys.Where(x => x.DeptId != null).Select(x => x.DeptId).ToList();
        var gradeIds = entitys.Where(x => x.GradeId != null).Select(x => x.GradeId).ToList();
        var jobIds = entitys.Where(x => x.JobId != null).Select(x => x.JobId).ToList();
        var titleIds = entitys.Where(x => x.TitleId != null).Select(x => x.TitleId).ToList();
        var reportIds = entitys.Where(x => x.ReportId != null).Select(x => x.ReportId).ToList();

        if (reportIds.Any())
        {
            var staffs = await Db.Queryable<Ghra_Staff>().Where(x => reportIds.Contains(x.StaffID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.ReportName = staffs.FirstOrDefault(o => rule.ReportId == o.StaffID)?.StaffName;
            });
        }

        if (deptIds.Any())
        {
            var depts = await Db.Queryable<Ghro_Dept>().Where(x => deptIds.Contains(x.DeptID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.DeptName = depts.FirstOrDefault(o => rule.DeptId == o.DeptID)?.DeptName;
            });
        }

        if (titleIds.Any())
        {
            var titles = await Db.Queryable<Ghra_Title>().Where(x => titleIds.Contains(x.TitleID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.TitleName = titles.FirstOrDefault(o => rule.TitleId == o.TitleID)?.TitleName;
            });
        }

        if (gradeIds.Any())
        {
            var grades = await Db.Queryable<Ghra_Grade>().Where(x => gradeIds.Contains(x.GradeID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.GradeName = grades.FirstOrDefault(o => rule.GradeId == o.GradeID)?.GradeName;
            });
        }

        if (jobIds.Any())
        {
            var jobs = await Db.Queryable<Ghra_Job>().Where(x => jobIds.Contains(x.JobID)).ToListAsync();

            entitys.ForEach(rule =>
            {
                rule.JobName = jobs.FirstOrDefault(o => rule.JobId == o.JobID)?.JobName;
            });
        }

        for (int i = 0; i < entitys.Count; i++)
        {
            if (entitys[i].YearHumanId.IsNotEmptyOrNull())
                entitys[i].YearHumanName = await Db.Ado.GetStringAsync(@$"SELECT CAST (A.[Year] AS VARCHAR) + '_' + B.TitleName + '_' + C.JobName label
FROM Ghrh_YearHumanSettings A
     LEFT JOIN Ghra_Title B ON A.TitleId = B.TitleID
     LEFT JOIN Ghra_Job C ON A.JobId = C.JobID
WHERE A.IsEnable = 1 AND A.Id = {entitys[i].YearHumanId}");

            if (entitys[i].WorkNo.IsNotEmptyOrNull())
                entitys[i].RequestNo = entitys[i].WorkNo;
        }
        var userIds = entitys.Where(x => x.RefuseUserId != null).Select(x => x.RefuseUserId).Distinct().ToList();
        userIds.AddRange(entitys.Where(x => x.AgreeUserId != null).Select(x => x.AgreeUserId).Distinct());
        var users = await Db.Queryable<Ghrs_User>().Where(x => userIds.Contains(x.UserId)).ToListAsync();
        entitys.ForEach(async x =>
        {
            await SetLabel(x);
            if (x.AgreeUserId != null)
                x.AgreeUserName = users.Where(o => x.AgreeUserId == o.UserId).FirstOrDefault()?.UserName;

            if (x.RefuseUserId != null)
                x.RefuseUserName = users.Where(o => x.RefuseUserId == o.UserId).FirstOrDefault()?.UserName;
        });
        result.result.DT_TableDataT1 = entitys;
        return result;
    }

    public override async Task<Ghrh_HumanRequestDto> QueryById(object objId)
    {
        var result = await base.QueryById(objId);
        if (result != null)
        {
            result.DeptName = (await Db.Queryable<Ghro_Dept>().FirstAsync(o => result.DeptId == o.DeptID))?.DeptName;
            if (result.TitleId.IsNotEmptyOrNull())
                result.TitleName = (await Db.Queryable<Ghra_Title>().FirstAsync(o => result.TitleId == o.TitleID))?.TitleName;

            #region 返回部门负责人信息
            var dept = await Db.Queryable<Ghro_Dept>().Where(x => x.DeptID == result.DeptId).FirstAsync();
            if (dept != null)
            {
                var staff = await Db.Queryable<Ghra_Staff>().Where(x => x.StaffID == dept.DeptManagerID).FirstAsync();
                if (staff != null)
                {
                    result.DeptManagerID = staff.StaffID;
                    result.DeptManagerEmail = staff.Email;
                }
            }
            #endregion

            result.RecommendCount = result.RecommendCount ?? 0;
            result.InterviewCount = result.InterviewCount ?? 0;
            result.OfferCount = result.OfferCount ?? 0;
            result.CheckInCount = result.CheckInCount ?? 0;
            result.ResumeCount = result.RequestCount ?? 0;
        }
        return result;
    }

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

        var DT_TableDataT1 = result.result.DT_TableDataT1;

        if (DT_TableDataT1 != null && DT_TableDataT1.Any())
        {
            var details = await _ghrh_HumanRequestDetailServices.Query(x => x.RequestId == DT_TableDataT1[0].Id);
            DT_TableDataT1[0].Quality = details.Where(x => x.Source == "Quality").Select(x => x.DetailName).ToList();
            DT_TableDataT1[0].Experience = details.Where(x => x.Source == "Experience").Select(x => new Ghrh_HumanRequestExperience()
            {
                value = x.DetailName,
                text = x.DetailValue,
            }).ToList();
        }


        result.result.DT_TableDataT1 = DT_TableDataT1;
        return result;
    }
    public async Task<ServicePageResult<Ghrh_HumanRequestDto>> QueryFilterSummaryPage(QueryBody filter)
    {
        if (string.IsNullOrWhiteSpace(filter.orderBy))
            filter.orderBy = "YearMonth DESC";

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

        Type entityType = typeof(Ghrh_InterviewOrder);

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

        string conditions = " WHERE 1=1 ";

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

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

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

        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++)
        {

        }

        return result;
    }

    public async Task<ServiceResult<ExcelData>> ExportSummaryExcel(QueryExport body)
    {
        QueryBody filter = new QueryBody();
        filter.pageNum = 1;
        filter.jsonParam = body.jsonParam;
        filter.pageSize = 1000000;
        filter.langId = body.langId;

        var condition = "1=1";
        if (body.exportSet.SelectRowKeys != null && body.exportSet.SelectRowKeys.Any())
            condition += $" AND Id IN({string.Join(",", body.exportSet.SelectRowKeys)})";

        var data = await QueryFilterSummaryPage(filter);

        string sql = $@"SELECT *
                            FROM Ghrs_PageSettingQuery
                            WHERE     IsEnable = 1
                                  AND PageNo = '{body.menuName}'
                                  AND (defaultHidden = 'false' OR defaultHidden is null)
                            ORDER BY SortNo ASC";

        var columns = DbAccess.QueryList<QueryExportColumn>(sql);

        var fieldDescs = new Dictionary<string, string>();
        if (body.exportSet.ExFields.Any())
            body.exportSet.ExFields.ForEach(x =>
            {
                if (columns.Any(o => o.field == x))
                {
                    var label = columns.FirstOrDefault(o => o.field == x)?.label;
                    if (!fieldDescs.ContainsKey(x))
                        fieldDescs.Add(x, label);

                }
            });
        else
            fieldDescs = columns.ToDictionary(item => item.field, item => item.label);
        var dt = ToDataTable(data.result.DT_TableDataT1, fieldDescs, null);
        // 获取所有列名
        var dtColumns = dt.Columns;

        var id = SnowFlakeSingle.instance.getID();
        var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
        var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}export{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}";
        if (!Directory.Exists(physicsPath + path))
            Directory.CreateDirectory(physicsPath + path);

        path = path + body.exportSet.TitleName + ".xlsx";
        NPOIHelper.ExportExcel(dt, body.exportSet.TitleName, "sheet1", physicsPath + path);

        var result = new ExcelData();
        result.filePath = "/Advanced" + path;
        result.fileName = body.exportSet.TitleName + ".xlsx";
        return ServiceResult<ExcelData>.OprateSuccess("导出成功", result);
    }
    public async Task<ServicePageResult<Ghrh_HumanRequestDto>> QueryFilterCompletePage(QueryBody filter)
    {
        if (string.IsNullOrWhiteSpace(filter.orderBy))
            filter.orderBy = "YearMonth DESC";

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

        Type entityType = typeof(Ghrh_InterviewOrder);

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

        string conditions = " WHERE 1=1 ";

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

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

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

        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++)
        {

        }

        return result;
    }

    public async Task<ServiceResult<ExcelData>> ExportCompleteExcel(QueryExport body)
    {
        QueryBody filter = new QueryBody();
        filter.pageNum = 1;
        filter.jsonParam = body.jsonParam;
        filter.pageSize = 1000000;
        filter.langId = body.langId;

        var condition = "1=1";
        if (body.exportSet.SelectRowKeys != null && body.exportSet.SelectRowKeys.Any())
            condition += $" AND Id IN({string.Join(",", body.exportSet.SelectRowKeys)})";

        var data = await QueryFilterCompletePage(filter);

        string sql = $@"SELECT *
                            FROM Ghrs_PageSettingQuery
                            WHERE     IsEnable = 1
                                  AND PageNo = '{body.menuName}'
                                  AND (defaultHidden = 'false' OR defaultHidden is null)
                            ORDER BY SortNo ASC";

        var columns = DbAccess.QueryList<QueryExportColumn>(sql);

        var fieldDescs = new Dictionary<string, string>();
        if (body.exportSet.ExFields.Any())
            body.exportSet.ExFields.ForEach(x =>
            {
                if (columns.Any(o => o.field == x))
                {
                    var label = columns.FirstOrDefault(o => o.field == x)?.label;
                    if (!fieldDescs.ContainsKey(x))
                        fieldDescs.Add(x, label);

                }
            });
        else
            fieldDescs = columns.ToDictionary(item => item.field, item => item.label);
        var dt = ToDataTable(data.result.DT_TableDataT1, fieldDescs, null);
        // 获取所有列名
        var dtColumns = dt.Columns;

        var id = SnowFlakeSingle.instance.getID();
        var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
        var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}export{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}";
        if (!Directory.Exists(physicsPath + path))
            Directory.CreateDirectory(physicsPath + path);

        path = path + body.exportSet.TitleName + ".xlsx";
        NPOIHelper.ExportExcel(dt, body.exportSet.TitleName, "sheet1", physicsPath + path);

        var result = new ExcelData();
        result.filePath = "/Advanced" + path;
        result.fileName = body.exportSet.TitleName + ".xlsx";
        return ServiceResult<ExcelData>.OprateSuccess("导出成功", result);
    }
    #endregion

    #region 更新
    public override async Task<bool> Update(long Id, EditGhrh_HumanRequestInput entity)
    {

        await _ghrh_HumanRequestDetailServices.Delete(x => x.RequestId == Id && x.Source == "Quality");
        await _ghrh_HumanRequestDetailServices.Delete(x => x.RequestId == Id && x.Source == "Experience");

        if (entity.Quality != null && entity.Quality.Any())
        {
            var qualitys = entity.Quality.Select(x => new InsertGhrh_HumanRequestDetailInput()
            {
                RequestId = Id,
                DetailName = x,
                Source = "Quality"
            }).ToList();
            await _ghrh_HumanRequestDetailServices.Add(qualitys);
        }

        if (entity.Experience != null && entity.Experience.Any())
        {
            var experiences = entity.Experience.Select(x => new InsertGhrh_HumanRequestDetailInput()
            {
                RequestId = Id,
                DetailName = x.value,
                DetailValue = x.text,
                Source = "Experience"
            }).ToList();
            await _ghrh_HumanRequestDetailServices.Add(experiences);
        }

        return await base.Update(Id, entity, null, ["Status"]);
    }

    public async Task<ServiceResult> UpdateStatus(InsertGhrh_HumanRequestInput input, string status)
    {

        HttpRequest request = UserContext.Context.Request;
        var api = request.Path.ObjToString().TrimEnd('/').ToLower();
        var ip = GetUserIp(UserContext.Context);

        var entities = new List<Ghrh_HumanRequest>();
        foreach (var id in input.Ids)
        {
            if (!BaseDal.Any(id))
                continue;

            var entity = await BaseDal.QueryById(id);


            switch (status)
            {
                case DIC_REQUEST_STATUS.Active:
                    entity.AgreeReason = input.Reason;
                    entity.AgreeTime = DateTime.Now;
                    entity.AgreeUserId = App.User.ID;
                    break;
                case DIC_REQUEST_STATUS.Temporary:
                    entity.RefuseReason = input.Reason;
                    entity.RefuseTime = DateTime.Now;
                    entity.RefuseUserId = App.User.ID;
                    break;
            }

            entity.UpdateIP = ip;
            entity.UpdateProg = api;
            entity.Status = status;
            entities.Add(entity);
        }

        var result = await BaseDal.Update(entities);
        return ServiceResult.OprateSuccess("执行成功！");

    }
    #endregion


    #region Excel导入
    public override async Task<ServiceResult<ExcelData>> ImportExcel(IFormFile file, string menuName = null, long? MasterId = null)
    {
        var data = new ExcelData();
        var (path, filepath) = await ReportHelper.GetImportFilePath(file, menuName);
        string errorFileName = path + SnowFlakeSingle.instance.getID() + FileHelper.GetPostfixStr(filepath);

        var dt = ReportHelper.ReadImportExcel(filepath);
        var columns = await QueryExportColumn(menuName);

        var (dictList, errorCount) = await ReportHelper.ValidImportExcel(Db, columns, dt);

        if (errorCount > 0)
        {
            NPOIHelper.ExportExcel(dt, null, "导入数据", FileHelper.GetPhysicsPath() + errorFileName);
            data.filePath = "/Advanced" + errorFileName;
            data.ErrorCount = errorCount;
        }
        else
        {
            for (int i = 0; i < dictList.Count; i++)
            {
                var dict = dictList[i];
                if (menuName == "F_ManReqMainten")
                    dict.Add("Status", "Wait");
                else
                if (menuName == "F_ManReqMaintenTemporary")
                    dict.Add("Status", "Temporary");

                if (dict.ContainsKey("Quality"))
                {
                    await _ghrh_HumanRequestDetailServices.Add(new InsertGhrh_HumanRequestDetailInput()
                    {
                        RequestId = dict["Id"].ObjToLong(),
                        DetailName = dict["Quality"].ObjToString(),
                        Source = "Quality"
                    });
                    dict.Remove("Quality");
                }
                if (dict.ContainsKey("Experience"))
                {
                    await _ghrh_HumanRequestDetailServices.Add(new InsertGhrh_HumanRequestDetailInput()
                    {
                        RequestId = dict["Id"].ObjToLong(),
                        DetailName = dict["Experience"].ObjToString(),
                        Source = "Experience"
                    });
                    dict.Remove("Experience");
                }
                await Db.Insertable(dict).AS("Ghrh_HumanRequest").ExecuteCommandAsync();

                var sql = $"SELECT ISNULL(MAX(id)+1,1) FROM Ghrh_HumanRequest WHERE Id !='{dict["Id"]}'";
                var id1 = await Db.Ado.GetLongAsync(sql);
                sql = $"UPDATE Ghrh_HumanRequest SET Id={id1} WHERE  Id ='{dict["Id"]}';" +
                    $"UPDATE Ghrh_HumanRequestDetail SET RequestId={id1} WHERE  RequestId ='{dict["Id"]}';";
                await Db.Ado.ExecuteCommandAsync(sql);
            }

            data.SuccessCount = dictList.Count;
        }

        return ServiceResult<ExcelData>.OprateSuccess("导入成功！", data);
    }
    #endregion
}