
using Furion.DatabaseAccessor.Extensions;
using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 机构信息服务
/// </summary>
public class SysOrgService : ISysOrgService, ITransient
{
    private readonly IRepository<SysOrg> _rep;
    public SysOrgService(IRepository<SysOrg> rep)
    {
        _rep = rep;
    }

    /// <summary>
    /// 添加机构
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Add(AddSysOrgInput input)
    {
        if (await _rep.AnyAsync(t => t.FullName.ToUpper() == input.FullName.ToUpper() || t.Name.ToUpper() == input.Name.ToUpper() || t.ShortName.ToUpper() == input.ShortName.ToUpper()))
        {
            throw Oops.Oh(ErrorCode.E2003, "", "全称、名称或简称");
        }
        if (await _rep.AnyAsync(t => t.OrgType == input.OrgType && t.EducationStage == input.EducationStage && t.Code.ToUpper() == input.Code.ToUpper()))
        {
            throw Oops.Oh(ErrorCode.E2003, "", "代码");
        }

        var item = input.Adapt<SysOrg>();
        await item.InsertAsync();
    }
    /// <summary>
    /// 更新机构
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Update(UpdateSysOrgInput input)
    {
        if (await _rep.AnyAsync(t => t.Id != input.Id && (t.FullName.ToUpper() == input.FullName.ToUpper() || t.Name.ToUpper() == input.Name.ToUpper() || t.ShortName.ToUpper() == input.ShortName.ToUpper())))
        {
            throw Oops.Oh(ErrorCode.E2003, "其他机构", "的全称、名称或简称");
        }
        if (await _rep.AnyAsync(t => t.Id != input.Id && t.OrgType == input.OrgType && t.EducationStage == input.EducationStage && t.Code.ToUpper() == input.Code.ToUpper()))
        {
            throw Oops.Oh(ErrorCode.E2003, "其他机构", "的代码");
        }

        var item = input.Adapt<SysOrg>();
        await item.UpdateAsync();
    }
    /// <summary>
    /// 删除机构
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Del(BaseId<short> input)
    {
        var item = await _rep.FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
        item.Status = CommonStatus.DELETED;
        await item.UpdateIncludeAsync(new[] { nameof(item.Status) });
        await item.FakeDeleteAsync();
    }
    /// <summary>
    /// 启用禁用机构
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task ChangeStatus(BaseId<short> input)
    {
        var item = await _rep.FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
        item.Status = item.Status == CommonStatus.ENABLE ? CommonStatus.DISABLE : CommonStatus.ENABLE;
        await item.UpdateIncludeAsync(new[] { nameof(item.Status) });
    }
    /// <summary>
    /// 根据ID获取机构
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<SysOrgOutput> GetById(short id)
    {
        var item = await _rep.FirstOrDefaultAsync(t => t.Id == id) ?? throw Oops.Oh(ErrorCode.E2001);
        return item.Adapt<SysOrgOutput>();
    }
    /// <summary>
    /// 查询机构列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<List<SysOrgLiteOutput>> QueryList(QuerySysOrgInput input)
    {
        var name = !string.IsNullOrEmpty(input.Name?.Trim());
        var code = !string.IsNullOrEmpty(input.Code?.Trim());

        var items = await _rep.DetachedEntities
                              .Where((name, u => EF.Functions.Like(u.ShortName, $"%{input.Name.Trim()}%") || EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%") || EF.Functions.Like(u.FullName, $"%{input.Name.Trim()}%")))
                              .Where((code, u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%")))
                              .Where(input.OrgType.HasValue, u => u.OrgType == input.OrgType)
                              .Where(input.EducationStage.HasValue, u => u.EducationStage == input.EducationStage)
                              .Where(input.OrgFundSource.HasValue, u => u.OrgFundSource == input.OrgFundSource)
                              .Where(input.UrbanRuralType.HasValue, u => u.UrbanRuralType == input.UrbanRuralType)
                              .Where(input.Status.HasValue, u => u.Status == input.Status)
                              .Where(t => t.IsDeleted == false)
                              .OrderBy(u => u.OrgType).ThenBy(t => t.EducationStage).ThenBy(t => t.Code)
                              .ProjectToType<SysOrgLiteOutput>()
                              .ToListAsync();
        return items;
    }
    /// <summary>
    /// 分页查询机构列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<PageResult<SysOrgOutput>> QueryPageList(SysOrgPageInput input)
    {
        var name = !string.IsNullOrEmpty(input.Name?.Trim());
        var code = !string.IsNullOrEmpty(input.Code?.Trim());

        var ret = await _rep.DetachedEntities
                              .Where((name, u => EF.Functions.Like(u.ShortName, $"%{input.Name.Trim()}%") || EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%") || EF.Functions.Like(u.FullName, $"%{input.Name.Trim()}%")))
                              .Where((code, u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%")))
                              .Where(input.OrgType.HasValue, u => u.OrgType == input.OrgType)
                              .Where(input.EducationStage.HasValue, u => u.EducationStage == input.EducationStage)
                              .Where(input.OrgFundSource.HasValue, u => u.OrgFundSource == input.OrgFundSource)
                              .Where(input.UrbanRuralType.HasValue, u => u.UrbanRuralType == input.UrbanRuralType)
                              .Where(input.Status.HasValue, u => u.Status == input.Status)
                              .Where(t => t.IsDeleted == false)
                              .OrderBy(u => u.OrgType).ThenBy(t => t.EducationStage).ThenBy(t => t.Code)
                              .ProjectToType<SysOrgOutput>()
                              .ToADPagedListAsync(input.PageIndex, input.PageSize);
        return ret;
    }
    /// <summary>
    /// 获取全部机构列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<SysOrgLiteOutput>> GetAllList()
    {
        var items = await _rep.DetachedEntities.Where(t => t.IsDeleted == false).ProjectToType<SysOrgLiteOutput>().ToListAsync();
        return items;
    }
    /// <summary>
    /// 根据学校ID获取校区列表
    /// </summary>
    /// <param name="orgId"></param>
    /// <returns></returns>
    public async Task<List<SysOrgLiteOutput>> GetOrgBranchByOrgId(short orgId)
    {
        var items = await _rep.DetachedEntities.Where(t => t.OrgType == OrgType.SCHOOL_BRANCH && t.Pid == orgId).ProjectToType<SysOrgLiteOutput>().ToListAsync();
        return items;
    }
}
