using Hotline.Application.Snapshot.Contracts;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Tools;
using Hotline.Snapshot;
using Hotline.Snapshot.IRepository;
using Hotline.Tools;
using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;

namespace Hotline.Application.Snapshot;
public class InviteCodeApplication : IInviteCodeApplication, IScopeDependency
{
    private readonly IInviteCodeRepository _inviteCodeRepository;
    private readonly IInviteCodeRecordRepository _inviteCodeRecordRepository;

    public InviteCodeApplication(IInviteCodeRepository inviteCodeRepository, IInviteCodeRecordRepository inviteCodeRecordRepository)
    {
        _inviteCodeRepository = inviteCodeRepository;
        _inviteCodeRecordRepository = inviteCodeRecordRepository;
    }

    public async Task<string> AddInviteCodeAsync(AddInviteCodeInDto dto)
    {
        if (_inviteCodeRepository.Queryable().Where(m => m.OrgName == dto.OrgName).Any())
        {
            throw UserFriendlyException.SameMessage("部门名称已存在");
        }
        var entity = dto.Adapt<InviteCode>();
        if (dto.BeginCode >= dto.EndCode)
        {
            throw UserFriendlyException.SameMessage("开始邀请码不能大于结束邀请码");
        }
        return await _inviteCodeRepository.AddAsync(entity);
    }

    /// <summary>
    /// 删除邀请码
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public async Task DeleteInviteCodeAsync(IList<string> ids)
    {
        await _inviteCodeRepository.Queryable()
            .Where(m => ids.Contains(m.Id))
            .ToListAsync()
            .Then(async invite =>
            {
                for (int i = 0;i < invite.Count;i++)
                {
                    invite[i].IsDeleted = true;
                    await _inviteCodeRepository.UpdateAsync(invite[i]);
                }
            });
    }

    public ISugarQueryable<InviteCode> GetInviteCodeItems()
    {
        return _inviteCodeRepository.Queryable();
    }

    [Description("邀请码统计")]
    public ISugarQueryable<InviteCodeStatisticOutDto> GetInviteCodeStatisticAsync(GetInviteCodeStatisticInDto dto)
    {
        dto.ValidateObject();
        var items = _inviteCodeRecordRepository.Queryable()
            .Where(m => m.CreationTime >= dto.StartTime && m.CreationTime <= dto.EndTime)
            .GroupBy(m => new { m.Id, m.OrgName })
            .Select(m => new InviteCodeStatisticOutDto
            {
                Id = m.Id,
                OrgName = m.OrgName,
                Count = SqlFunc.AggregateCount(m.OrgName)
            });
        return items;
    }

    /// <summary>
    /// 邀请码统计明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<InviteCodeStatisticDetailOutDto> GetInviteCodeStatisticDetail(GetInviteCodeStatisticDetailInDto dto)
    {
        dto.ValidateObject();
        var query = _inviteCodeRecordRepository.Queryable()
            .Where(m => m.CreationTime >= dto.StartTime && m.CreationTime <= dto.EndTime && m.OrgId == dto.OrgId)
            .WhereIF(dto.Name.NotNullOrEmpty(), m => m.Name.Contains(dto.Name))
            .WhereIF(dto.PhoneNumber.NotNullOrEmpty(), m => m.PhoneNumber.Contains(dto.PhoneNumber))
            .WhereIF(dto.InviteCode.NotNullOrEmpty(), m => m.InviteCode.Contains(dto.InviteCode))
            .Select(m => new InviteCodeStatisticDetailOutDto
            { 
                OpenId = m.WXOpenId
            }, true);
        return query;
    }

    public async Task UpdateInviteCodeAsync(UpdateInviteCodeInDto dto)
    {
        var entity = await _inviteCodeRepository.GetAsync(dto.Id)
            ?? throw UserFriendlyException.SameMessage("邀请码不存在");

        dto.Adapt(entity);
        if (dto.BeginCode >= dto.EndCode)
        {
            throw UserFriendlyException.SameMessage("开始邀请码不能大于结束邀请码");
        }
        await _inviteCodeRepository.UpdateAsync(entity);
    }
}
