using DocumentFormat.OpenXml.Office2010.Excel;
using Hotline.Application.Snapshot.Contracts;
using Hotline.Caching.Interfaces;
using Hotline.Orders;
using Hotline.Push.FWMessage;
using Hotline.Share.Attributes;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Push;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Enums.Order;
using Hotline.Share.Enums.Push;
using Hotline.Share.Enums.Snapshot;
using Hotline.Share.Tools;
using Hotline.Snapshot;
using Hotline.Snapshot.Contracts;
using Hotline.Snapshot.IRepository;
using Hotline.ThirdAccountDomainServices.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Client;
using SqlSugar;
using SqlSugar.Extensions;
using System.ComponentModel;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;
using XF.Domain.Repository;
using XF.Utility.EnumExtensions;
using static NPOI.SS.Format.CellNumberFormatter;

namespace Hotline.Application.Snapshot;
public class RedPackApplication : IRedPackApplication, IScopeDependency
{
    private readonly IOrderSnapshotRepository _orderSnapshotRepository;
    private readonly IOrderRepository _orderRepository;
    private readonly ISnapshotSMSTemplateRepository _snapshotSMSTemplateRepository;
    private readonly IIndustryRepository _industryRepository;
    private readonly ISpecialRedPackAuditRepository _specialRedPackAuditRepository;

    /// <summary>
    /// 市民红包审核仓储
    /// </summary>
    private readonly IRedPackAuditRepository _redPackAuditRepository;
    private readonly IRedPackRecordRepository _redPackRecordRepository;
    private readonly IRepository<OrderSpecial> _orderSpecialRepository;
    private readonly ISessionContext _sessionContext;
    private readonly IRedPackGuiderAuditRepository _redPackGuiderAuditRepository;
    private readonly IThirdAccountRepository _thirdAccountRepository;
    private readonly ISupplementRecordRepository _supplementRecordRepository;
    private readonly IPushDomainService _pushDomainService;
    private readonly ILogger<RedPackApplication> _logger;
    private readonly ISystemDicDataCacheManager _systemDic;
    private readonly ISnapshotPointsRecordRepository _snapshotPointsRecordRepository;
    private readonly ISnapshotPointsDomainService _snapshotPointsDomainService;

    public RedPackApplication(IOrderSnapshotRepository orderSnapshotRepository, ISnapshotSMSTemplateRepository snapshotSMSTemplateRepository, IOrderRepository orderRepository, IIndustryRepository industryRepository, IRedPackAuditRepository redPackAuditRepository, IRedPackRecordRepository redPackRecordRepository, IRepository<OrderSpecial> orderSpecialRepository, ISessionContext sessionContext, IRedPackGuiderAuditRepository redPackGuiderAuditRepository, IThirdAccountRepository thirdAccountRepository, ISupplementRecordRepository supplementRecordRepository, IPushDomainService pushDomainService, ILogger<RedPackApplication> logger, ISpecialRedPackAuditRepository specialRedPackAuditRepository, ISystemDicDataCacheManager systemDic, ISnapshotPointsRecordRepository snapshotPointsRecordRepository, ISnapshotPointsDomainService snapshotPointsDomainService)
    {
        _orderSnapshotRepository = orderSnapshotRepository;
        _snapshotSMSTemplateRepository = snapshotSMSTemplateRepository;
        _orderRepository = orderRepository;
        _industryRepository = industryRepository;
        _redPackAuditRepository = redPackAuditRepository;
        _redPackRecordRepository = redPackRecordRepository;
        _orderSpecialRepository = orderSpecialRepository;
        _sessionContext = sessionContext;
        _redPackGuiderAuditRepository = redPackGuiderAuditRepository;
        _thirdAccountRepository = thirdAccountRepository;
        _supplementRecordRepository = supplementRecordRepository;
        _pushDomainService = pushDomainService;
        _logger = logger;
        _specialRedPackAuditRepository = specialRedPackAuditRepository;
        _systemDic = systemDic;
        _snapshotPointsRecordRepository = snapshotPointsRecordRepository;
        _snapshotPointsDomainService = snapshotPointsDomainService;
    }

    /// <summary>
    /// 审核红包发放
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task AuditRedPackAuditAsync(UpdateRedPackAuditInDto dto, CancellationToken token)
    {
        var status = ERedPackAuditStatus.Refuse;
        if (dto.Status == ESnapshotSMSStatus.Agree)
            status = ERedPackAuditStatus.Agree;
        var redPackAudit = await _redPackAuditRepository.GetAsync(dto.RedPackAuditId, token) ?? throw UserFriendlyException.SameMessage("审核记录不存在");
        if (redPackAudit.Status != ERedPackAuditStatus.Pending) throw UserFriendlyException.SameMessage("已审核, 不可重复审核");

        var industry = await _industryRepository.Queryable(includeDeleted: true)
          .LeftJoin<OrderSnapshot>((i, o) => i.Id == o.IndustryId)
          .Where((i, o) => o.Id == redPackAudit.OrderId)
          .Select((i, o) => new {
              i.Id,
              i.CitizenReadPackAmount,
              i.ArgeePoints,
              i.ExtraDeductedPoints,
              i.RefusePoints,
              i.IsPoints,
              o.IsSafetyDepartment,
              i.Name
          })
          .FirstAsync(token);
        redPackAudit.ApprovedAmount = redPackAudit.ShouldAmount;
        if (industry.Name == "安全隐患" && industry.IsSafetyDepartment.HasValue && industry.IsSafetyDepartment == true)
        {
            redPackAudit.ApprovedAmount = 20;
        }
        redPackAudit.SMSTemplateId = dto.SMSTemplateId;
        redPackAudit.Status = status;
        redPackAudit.AuditRemark = dto.Opinion;
        redPackAudit.IsSendSMS = dto.IsSendSms;
        redPackAudit.AuditId = _sessionContext.UserId;
        redPackAudit.AuditName = _sessionContext.UserName;
        redPackAudit.AuditTime = DateTime.Now;
        redPackAudit.AuditOrgId = _sessionContext.OrgId;
        redPackAudit.AuditOrgName = _sessionContext.OrgName;
        redPackAudit.Points = dto.Points;
        redPackAudit.PointsStatus = dto.PointsStatus;
        redPackAudit.PointsOpinion = dto.PointsOpinion;
        redPackAudit.ExtraDeductedPoints = dto.ExtraDeductedPoints;
        redPackAudit.ExtraDeductionPointsTypeId = dto.ExtraDeductionPointsTypeId;
        redPackAudit.ExtraDeductionPointsTypeName = dto.ExtraDeductionPointsTypeName;
        var order = await _orderRepository.Queryable()
            .LeftJoin<OrderSnapshot>((order, snapshot) => order.Id == snapshot.Id)
            .Where((order, snapshot) => order.Id == redPackAudit.OrderId)
            .Select((order, snapshot) => new { order.Id, order.No, order.FromName, order.FromPhone, snapshot.CreatorId })
            .FirstAsync(token) ?? throw UserFriendlyException.SameMessage("工单不存在");
        if (status == ERedPackAuditStatus.Agree)
        {
            var third = await _thirdAccountRepository.GetByExternalIdAsync(order.CreatorId, token);
            var entity = new RedPackRecord
            {
                OrderId = redPackAudit.OrderId,
                RedPackAuditId = redPackAudit.Id,
                PeopleType = EReadPackUserType.Citizen,
                Name = order.FromName,
                PhoneNumber = order.FromPhone,
                WXOpenId = third?.OpenId,
                No = order.No,
                PickupStatus = ERedPackPickupStatus.Unreceived,
                DistributionState = EReadPackSendStatus.Unsend,
            };
            if (redPackAudit.ApprovedAmount.HasValue)
                entity.Amount = redPackAudit.ApprovedAmount.Value;
            await _redPackRecordRepository.AddAsync(entity);
        }
        await _redPackAuditRepository.UpdateAsync(redPackAudit, token);
        await _snapshotPointsDomainService
            .AddPointsAsync(order.Id, EPointsSource.Audit, dto.PointsStatus, dto.ExtraDeductedPoints, dto.ExtraDeductionPointsTypeName);
        if (dto.IsSendSms)
        {
            var smsTemplate = await _snapshotSMSTemplateRepository.GetAsync(dto.SMSTemplateId);
            if (smsTemplate == null) return;
            var inDto = new MessageDto
            {
                TelNumber = order.FromPhone,
                Content = smsTemplate.Content,
                PushBusiness = EPushBusiness.Snapshot,
                Name = order.FromName,
            };
            try
            {
                await _pushDomainService.PushMsgAsync(inDto, CancellationToken.None);
            }
            catch (Exception e)
            {
                _logger.LogError("随手拍发送短信异常:" + e.Message, e);
            }
        }
    }

    /// <summary>
    /// 网格员审核红包发放
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task AuditRedPackGuiderAuditAsync(UpdateRedPackGuiderAuditInDto dto)
    {
        var status = ERedPackAuditStatus.Refuse;
        if (dto.Status == ESnapshotSMSStatus.Agree)
            status = ERedPackAuditStatus.Agree;
        var redPackAudit = await _redPackGuiderAuditRepository.GetAsync(dto.RedPackAuditId) ?? throw UserFriendlyException.SameMessage("审核记录不存在");
        var orgName = _sessionContext.OrgName ?? string.Empty;
        RedPackRecord? entity = null;
        if (orgName.Contains("应急管理局"))
        {
            if (redPackAudit.LevelTwoStatus != ERedPackAuditStatus.Pending) throw UserFriendlyException.SameMessage("已审核, 不可重复审核");
            redPackAudit.LevelTwoStatus = status;

            if (status == ERedPackAuditStatus.Agree)
            {
                var order = await _orderRepository.Queryable()
                    .Where(m => m.Id == redPackAudit.OrderId)
                    .Select(m => new { m.Id, m.No, m.FromName, m.FromPhone })
                    .FirstAsync();
                entity = new RedPackRecord
                {
                    OrderId = redPackAudit.OrderId,
                    RedPackAuditId = redPackAudit.Id,
                    PeopleType = EReadPackUserType.Guider,
                    Name = order.FromName,
                    PhoneNumber = order.FromPhone,
                    No = order.No,
                    PickupStatus = ERedPackPickupStatus.Unreceived,
                    DistributionState = EReadPackSendStatus.Unsend,
                };
                if (redPackAudit.ApprovedAmount.HasValue)
                    entity.Amount = redPackAudit.ApprovedAmount.Value;
            }
        }
        else
        {
            if (redPackAudit.LevelOneStatus != ERedPackAuditStatus.Pending) throw UserFriendlyException.SameMessage("已审核, 不可重复审核");
            redPackAudit.LevelOneStatus = status;
        }
        redPackAudit.Remark = dto.Opinion;
        await _redPackGuiderAuditRepository.UpdateAsync(redPackAudit);
        if (entity != null)
            await _redPackRecordRepository.AddAsync(entity);
    }


    /// <summary>
    /// 获取网格员审核详情
    /// </summary>
    /// <param name="id">工单Id</param>
    /// <returns></returns>
    public async Task<SnapshotOrderAuditDetailOutDto> GetRedPackGuiderAuditDetailAsync(string id)
    {
        var order = await _orderRepository.GetAsync(id) ?? throw UserFriendlyException.SameMessage("工单不存在");
        var outDto = new SnapshotOrderAuditDetailOutDto { Order = order.Adapt<SnapshotOrderAuditOrderDetailOutDto>() };
        var industry = await _industryRepository.Queryable(includeDeleted: true)
            .LeftJoin<OrderSnapshot>((i, o) => i.Id == o.IndustryId)
            .Select((i, o) => new { i.Id, i.GuiderReadPackAmount })
            .FirstAsync();
        outDto.Amount = industry.GuiderReadPackAmount;
        outDto.RedPackTxt = $"{order.FromPhone}【】元; ";
        var dayStart = DateTime.Now.ToString("yyyy-MM-dd 00:00:00").ObjToDate();
        var dayEnd = DateTime.Now.ToString("yyyy-MM-dd 23:59:59").ObjToDate();
        var query = _redPackGuiderAuditRepository.Queryable()
            .Where(m => m.PhoneNumber == order.FromPhone && m.LevelTwoAuditTime >= dayStart && m.LevelTwoAuditTime <= dayEnd && m.LevelTwoStatus == ERedPackAuditStatus.Agree);

        var totalAmount = await query.SumAsync(m => m.ApprovedAmount);
        if (totalAmount != 0)
            outDto.RedPackTxt = $"{order.FromPhone}【{totalAmount}】元; ";
        var count = await query.CountAsync();
        if (count != 0)
            outDto.RedPackTxt += $"今天审批【{count}】个";

        outDto.AuditComBox = EnumExts.GetDescriptions<ESnapshotSMSStatus>();
        return outDto;
    }


    /// <summary>
    /// 获取市民审核详情
    /// </summary>
    /// <param name="id">工单Id</param>
    /// <returns></returns>
    public async Task<SnapshotOrderAuditDetailOutDto> GetRedPackAuditDetailAsync(string id)
    {
        var order = await _orderRepository.GetAsync(id) ?? throw UserFriendlyException.SameMessage("工单不存在");
        var outDto = new SnapshotOrderAuditDetailOutDto { Order = order.Adapt<SnapshotOrderAuditOrderDetailOutDto>() };
        var industry = await _industryRepository.Queryable(includeDeleted: true)
            .LeftJoin<OrderSnapshot>((i, o) => i.Id == o.IndustryId)
            .Where((i, o) => o.Id == id)
            .Select((i, o) => new {
                i.Id,
                i.CitizenReadPackAmount,
                i.ArgeePoints,
                i.ExtraDeductedPoints,
                i.RefusePoints,
                i.IsPoints,
                o.IsSafetyDepartment,
                i.Name
            })
            .FirstAsync();
        outDto.Amount = industry.CitizenReadPackAmount;
        if (industry.Name == "安全隐患" && industry.IsSafetyDepartment.HasValue && industry.IsSafetyDepartment == true)
        {
            outDto.Amount = 20;
        }
        outDto.ArgeePoints = industry.ArgeePoints;
        outDto.ExtraDeductedPoints = industry.ExtraDeductedPoints;
        outDto.RefusePoints = industry.RefusePoints;
        outDto.IsPoints = industry.IsPoints;
        outDto.RedPackTxt = $"{order.FromPhone}【】元; ";
        var dayStart = DateTime.Now.ToString("yyyy-MM-dd 00:00:00").ObjToDate();
        var dayEnd = DateTime.Now.ToString("yyyy-MM-dd 23:59:59").ObjToDate();
        var query = _redPackAuditRepository.Queryable()
            .Where(m => m.PhoneNumber == order.FromPhone && m.AuditTime >= dayStart && m.AuditTime <= dayEnd && m.Status == ERedPackAuditStatus.Agree);

        var totalAmount = await query.SumAsync(m => m.ApprovedAmount);
        if (totalAmount != 0)
            outDto.RedPackTxt = $"{order.FromPhone}【{totalAmount}】元; ";
        var count = await query.CountAsync();
        if (count != 0)
            outDto.RedPackTxt += $"今天审批【{count}】个";

        outDto.AuditComBox = EnumExts.GetDescriptions<ESnapshotSMSStatus>();
        outDto.ExtraDeductionPointsType = _systemDic.ExtraDeductionPointsType;
        return outDto;
    }

    /// <summary>
    /// 特殊红包审批列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [ExportExcel("特殊红包审批")]
    public ISugarQueryable<SnapshotOrderAuditItemsOutDto> GetRedPackSpecialAuditItems(SnapshotOrderAuditItemsInDto dto)
    {
        var beginTime = new DateTime(2024, 8, 1);
        var endTime = new DateTime(2024, 9, 30, 23, 59, 59);
        var query = _redPackAuditRepository.Queryable(includeDeleted: true)
            .LeftJoin<OrderSnapshot>((redPackAudit, snapshot) => redPackAudit.OrderId == snapshot.Id)
            .LeftJoin<Order>((redPackAudit, snapshot, order) => redPackAudit.OrderId == order.Id)
            .LeftJoin<SpecialRedPackAudit>((redPackAudit, snapshot, order, special) => redPackAudit.OrderId == special.OrderId)
            .LeftJoin<SupplementRecord>((redPackAudit, snapshot, order, special, supplement) => special.Id == supplement.RedPackAuditId)
            .Where((redPackAudit, snapshot, order, special) => (redPackAudit.Status == ERedPackAuditStatus.Agree && snapshot.IndustryName == "安全隐患" && (order.OrderTagCode!.Contains("DHZY") || order.OrderTagCode!.Contains("dhzy"))) || (redPackAudit.Status == ERedPackAuditStatus.Agree && order.CreationTime >= beginTime && order.CreationTime <= endTime && redPackAudit.ApprovedAmount == 20 && order.AcceptTypeCode != "30" && snapshot.IndustryName != "电气焊作业申报" && (order.HotspotId == null || order.HotspotId.StartsWith("18") == false)))
            .WhereIF(dto.Status == 0, (redPackAudit, snapshot, order, special) => special.Id == null)
            .WhereIF(dto.Status == 1, (redPackAudit, snapshot, order, special) => special.Status == ERedPackAuditStatus.Agree)
            .WhereIF(dto.Status == 2, (redPackAudit, snapshot, order, special) => special.Status == ERedPackAuditStatus.Refuse)
            .WhereIF(dto.No.NotNullOrEmpty(), (redPackAudit, snapshot, order, special) => order.No!.Contains(dto.No!))
            .WhereIF(dto.Title.NotNullOrEmpty(), (redPackAudit, snapshot, order, special) => order.Title!.Contains(dto.Title!))
            .WhereIF(dto.FromPhone.NotNullOrEmpty(), (redPackAudit, snapshot, order, special) => order.FromPhone!.Contains(dto.FromPhone!))
            .WhereIF(dto.BeginCreationTime.HasValue && dto.EndCreationTime.HasValue, (redPackAudit, snapshot, order, special) => order.CreationTime >= dto.BeginCreationTime && order.CreationTime <= dto.EndCreationTime)
            .WhereIF(dto.IsDeal.HasValue, (redPackAudit, snapshot, order, special) => snapshot.IsDeal == dto.IsDeal)
            .WhereIF(dto.IsTruth.HasValue, (redPackAudit, snapshot, order, special) => snapshot.IsTruth == dto.IsTruth)
            .WhereIF(dto.IsTruthDepartment.HasValue, (redPackAudit, snapshot, order, special) => snapshot.IsTruthDepartment == dto.IsTruthDepartment)
            .WhereIF(dto.BeginAuditTime.HasValue && dto.EndAuditTime.HasValue, (redPackAudit, snapshot, order, special) => redPackAudit.AuditTime >= dto.BeginAuditTime && redPackAudit.AuditTime <= dto.EndAuditTime)
            .WhereIF(dto.BeginFiledTime.HasValue && dto.EndFiledTime.HasValue, (redPackAudit, snapshot, order, special) => order.FiledTime >= dto.BeginFiledTime && order.FiledTime <= dto.EndFiledTime)
            .WhereIF(dto.IsIssued.HasValue, (redPackAudit, snapshot, order, special) => redPackAudit.IsSend == dto.IsIssued)
            .WhereIF(dto.IndustryId.NotNullOrEmpty(), (redPackAudit, snapshot, order, special) => snapshot.IndustryId == dto.IndustryId)
            .WhereIF(dto.ConfigAmount.HasValue, (redPackAudit, snapshot, order, special) => special.ShouldAmount == dto.ConfigAmount)
            .WhereIF(dto.AcutalAmount.HasValue, (redPackAudit, snapshot, order, special) => special.AcutalAmount == dto.AcutalAmount)
            .WhereIF(dto.ApprovedAmount.HasValue, (redPackAudit, snapshot, order, special) => special.ApprovedAmount == dto.ApprovedAmount)
            .WhereIF(dto.IsDanger.HasValue, (redPackAudit, snapshot, order, special) => snapshot.IsDanger == dto.IsDanger)
            .OrderByDescending((redPackAudit, snapshot, order, special, supplement) => redPackAudit.CreationTime)
                        .Select((redPackAudit, snapshot, order, special, supplement) => new SnapshotOrderAuditItemsOutDto
                        {
                            Id = redPackAudit.Id,
                            RedPackAuditId = redPackAudit.Id,
                            OrderId = order.Id,
                            No = order.No,
                            Title = order.Title,
                            IndustryName = snapshot.IndustryName,
                            IndustryId = snapshot.IndustryId,
                            SourceChannel = order.SourceChannel,
                            SourceChannelCode = order.SourceChannelCode,
                            Status = order.Status,
                            IsDanger = snapshot.IsDanger,
                            FromPhone = order.FromPhone,
                            FromName = order.FromName,
                            AuditTime = dto.Status == 0 ? redPackAudit.AuditTime : special.AuditTime,
                            ApprovedAmount = dto.Status == 0 ? redPackAudit.ApprovedAmount : special.ApprovedAmount,
                            AcutalAmount = dto.Status == 0 ? redPackAudit.AcutalAmount : special.AcutalAmount,
                            IsIssued = dto.Status == 0 ? redPackAudit.IsSend : special.IsSend,
                            //RecordRemark = record.Remark,
                            County = order.County,
                            // IsRectify = s.IsRepetition
                            IsDeal = snapshot.IsDeal,
                            IsSafetyDepartment = snapshot.IsSafetyDepartment,
                            NetworkENumber = snapshot.NetworkENumber,
                            IsTruth = snapshot.IsTruth,
                            IsTruthDepartment = snapshot.IsTruthDepartment,
                            IsRepetition = snapshot.IsRepetition,
                            CreationTime = order.CreationTime,
                            OrgLevelOneCode = order.OrgLevelOneCode,
                            OrgLevelOneName = order.OrgLevelOneName,
                            AuditId = special.AuditId,
                            AuditName = special.AuditName,
                            AuditOrgId = special.AuditOrgId,
                            AuditOrgName = special.AuditOrgName,
                            AuditRemark = special.AuditRemark,
                            ReplenishAmount = supplement.ReplenishAmount,
                            BankCardNo = supplement.BankCardNo,
                            OpenBank = supplement.OpenBank,
                            AwardName = supplement.Name,
                            AuditStatus = special.Status,
                            AuditType = supplement.AuditType
                        });
#if DEBUG
        var sql = query.ToSqlString();
#endif        
        return query;
    }

    public async Task RevocationRedPackSpecialAuditAsync(IList<string> ids)
    {
        var specialRedPackAuditIds = await _specialRedPackAuditRepository.Queryable()
            .LeftJoin<Order>((special, order) => special.OrderId == order.Id)
            .LeftJoin<RedPackAudit>((special, order, audit) => order.Id == audit.OrderId)
            .Where((special, order, audit) => ids.Contains(audit.Id))
            .Select((special, order, audit) => special.Id).ToListAsync();
        var has = await _supplementRecordRepository.Queryable()
            .Where(m => specialRedPackAuditIds.Contains(m.RedPackAuditId))
            .AnyAsync();
        if (has) throw UserFriendlyException.SameMessage("该工单已发放红包，不能撤销审批");
        await _specialRedPackAuditRepository.Removeable()
            .Where(m => specialRedPackAuditIds.Contains(m.Id))
            .ExecuteCommandAsync();
    }

    /// <summary>
    /// 红包审核集合
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [ExportExcel("市民红包审批")]
    public ISugarQueryable<SnapshotOrderAuditItemsOutDto> GetRedPackAuditItems(SnapshotOrderAuditItemsInDto dto)
    {
        ERedPackAuditStatus? status = null;
        if (dto.Status != -1 && Enum.TryParse<ERedPackAuditStatus>(dto.Status.ToString(), out var statusParse))
        {
            status = statusParse;
        }

        var query = _redPackAuditRepository.Queryable(includeDeleted: true)
            .LeftJoin<Order>((redPackAudit, order) => redPackAudit.OrderId == order.Id)
            .LeftJoin<OrderSnapshot>((redPackAudit, order, snapshot) => redPackAudit.OrderId == snapshot.Id)
            .LeftJoin<RedPackRecord>((redPackAudit, order, snapshot, record) => redPackAudit.Id == record.OrderId)
            .LeftJoin<Industry>((redPackAudit, order, snapshot, record, industry) => snapshot.IndustryId == industry.Id)
            .LeftJoin<IndustryCase>((redPackAudit, order, snapshot, record, industry, industryCase) => snapshot.IndustryCase == industryCase.Id)
            .Where((redPackAudit, order, snapshot, record, industry) => order.Status >= EOrderStatus.Filed && industry.ApproveOrgId == _sessionContext.OrgId)
            .WhereIF(dto.No.NotNullOrEmpty(), (redPackAudit, order, snapshot, record, industry) => order.No.Contains(dto.No))
            .WhereIF(dto.Title.NotNullOrEmpty(), (redPackAudit, order, snapshot, record, industry) => order.Title.Contains(dto.Title))
            .WhereIF(dto.FromPhone.NotNullOrEmpty(), (redPackAudit, order, snapshot, record, industry) => order.FromPhone.Contains(dto.FromPhone))
            .WhereIF(dto.BeginCreationTime.HasValue && dto.EndCreationTime.HasValue, (redPackAudit, order, snapshot, record, industry) => order.CreationTime <= dto.EndCreationTime && order.CreationTime >= dto.BeginCreationTime)
            .WhereIF(dto.BeginFiledTime.HasValue && dto.EndFiledTime.HasValue, (redPackAudit, order, snapshot, record, industry) => order.FiledTime <= dto.EndFiledTime && order.FiledTime >= dto.BeginFiledTime)
            .WhereIF(dto.IsDeal.HasValue, (redPackAudit, order, snapshot, record, industry) => snapshot.IsDeal == dto.IsDeal)
            .WhereIF(dto.IsTruth.HasValue, (redPackAudit, order, snapshot, record, industry) => snapshot.IsTruth == dto.IsTruth)
            .WhereIF(dto.IsTruthDepartment.HasValue, (redPackAudit, order, snapshot, record, industry) => snapshot.IsTruthDepartment == dto.IsTruthDepartment)
            .WhereIF(dto.BeginAuditTime.HasValue && dto.EndAuditTime.HasValue, (redPackAudit, order, snapshot, record, industry) => redPackAudit.AuditTime <= dto.EndAuditTime && redPackAudit.AuditTime >= dto.BeginAuditTime)
            .WhereIF(dto.IsIssued.HasValue, (redPackAudit, order, snapshot, record, industry) => redPackAudit.IsSend == dto.IsIssued)
            .WhereIF(dto.IndustryId.NotNullOrEmpty(), (redPackAudit, order, snapshot, record, industry) => snapshot.IndustryId == dto.IndustryId)
            .WhereIF(dto.ConfigAmount.HasValue, (redPackAudit, order, snapshot, record, industry) => industry.CitizenReadPackAmount == dto.ConfigAmount)
            .WhereIF(dto.AcutalAmount.HasValue, (redPackAudit, order, snapshot, record, industry) => redPackAudit.AcutalAmount == dto.AcutalAmount)
            .WhereIF(dto.ApprovedAmount.HasValue, (redPackAudit, order, snapshot, record, industry) => redPackAudit.ApprovedAmount == dto.ApprovedAmount)
            .WhereIF(dto.IsDanger.HasValue, (redPackAudit, order, snapshot, record, industry) => snapshot.IsDanger == dto.IsDanger)
            .WhereIF(status.HasValue && status != ERedPackAuditStatus.Agree, (redPackAudit, order, snapshot, record, industry) => redPackAudit.Status == status && (order.HotspotId == null || order.HotspotId.StartsWith("18") == false))
            .WhereIF(status.HasValue && status == ERedPackAuditStatus.Agree, (redPackAudit, order, snapshot, record, industry) => redPackAudit.Status == ERedPackAuditStatus.Agree || record.PickupStatus == ERedPackPickupStatus.Received)
            .OrderByDescending((redPackAudit, order, snapshot, record, industry) => redPackAudit.CreationTime)
            .Select((redPackAudit, order, snapshot, record, industry, industryCase) => new SnapshotOrderAuditItemsOutDto
            {
                Id = redPackAudit.Id,
                RedPackAuditId = redPackAudit.Id,
                OrderId = order.Id,
                No = order.No,
                Title = order.Title,
                IndustryName = industry.Name,
                IndustryCaseId = snapshot.IndustryCase,
                IndustryCase = industryCase.Name,
                IndustryId = industry.Id,
                SourceChannel = order.SourceChannel,
                SourceChannelCode = order.SourceChannelCode,
                Status = order.Status,
                IsDanger = snapshot.IsDanger,
                FromPhone = order.FromPhone,
                FromName = order.FromName,
                AuditTime = redPackAudit.AuditTime,
                ApprovedAmount = redPackAudit.ApprovedAmount,
                AcutalAmount = redPackAudit.AcutalAmount,
                IsIssued = redPackAudit.IsSend,
                RecordRemark = record.Remark,
                County = order.County,
                // IsRectify = s.IsRepetition
                IsDeal = snapshot.IsDeal,
                NetworkENumber = snapshot.NetworkENumber,
                IsTruth = snapshot.IsTruth,
                IsTruthDepartment = snapshot.IsTruthDepartment,
                IsRepetition = snapshot.IsRepetition,
                CreationTime = order.CreationTime,
                OrgLevelOneCode = order.OrgLevelOneCode,
                OrgLevelOneName = order.OrgLevelOneName,
                AuditId = redPackAudit.AuditId,
                AuditName = redPackAudit.AuditName,
                AuditOrgId = redPackAudit.AuditOrgId,
                AuditOrgName = redPackAudit.AuditOrgName,
                AuditRemark = redPackAudit.AuditRemark,
                BankCardNo = record.BankCardNo,
                AwardName = record.Name,
                OpenBank = record.OpenBank,
                AuditStatus = redPackAudit.Status,
            }, true);
        return query;
    }

    /// <summary>
    /// 网格员审核集合
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [ExportExcel("网格员红包审批")]
    public ISugarQueryable<SnapshotOrderGuiderAuditItemsOutDto> GetRedPackGuiderAuditItems(SnapshotOrderGuiderAuditItemsInDto dto)
    {
        var areaCode = _sessionContext.OrgAreaCode;
        if (_sessionContext.OrgIsCenter)
        {
            areaCode = null;
        }
        ERedPackAuditStatus? status = null;
        if (dto.Status != -1 && Enum.TryParse<ERedPackAuditStatus>(dto.Status.ToString(), out var statusParse))
        {
            status = statusParse;
        }

        var query = _redPackGuiderAuditRepository.Queryable(includeDeleted: true)
            .LeftJoin<Order>((redPackAudit, order) => redPackAudit.OrderId == order.Id)
            .LeftJoin<OrderSnapshot>((redPackAudit, order, snapshot) => redPackAudit.OrderId == snapshot.Id)
            .LeftJoin<Industry>((redPackAudit, order, snapshot, industry) => snapshot.IndustryId == industry.Id)
            .Where((redPackAudit, order, snapshot, industry) => order.Status >= EOrderStatus.Filed)
            .WhereIF(dto.No.NotNullOrEmpty(), (redPackAudit, order, snapshot, industry) => order.No.Contains(dto.No))
            .WhereIF(dto.Title.NotNullOrEmpty(), (redPackAudit, order, snapshot, industry) => order.Title.Contains(dto.Title))
            .WhereIF(areaCode.NotNullOrEmpty(), (redPackAudit, order, snapshot, industry) => order.AreaCode == areaCode);

        var orgName = _sessionContext.OrgName ?? string.Empty;
        if (orgName.Contains("应急管理局") && status != null)
            query = query.Where((redPackAudit, order, snapshot, industry) => redPackAudit.LevelOneStatus == ERedPackAuditStatus.Agree && redPackAudit.LevelTwoStatus == status);
        else if (status != null)
            query = query.Where((redPackAudit, order, snapshot, industry) => redPackAudit.LevelOneStatus == status);

        query = query.OrderByDescending(redPackAudit => redPackAudit.CreationTime);
        return query.Select((redPackAudit, order, snapshot, industry) => new SnapshotOrderGuiderAuditItemsOutDto
        {
            Id = redPackAudit.Id,
            RedPackAuditId = redPackAudit.Id,
            OrderId = order.Id,
            No = order.No,
            Title = order.Title,
            SourceChannel = order.SourceChannel,
            SourceChannelCode = order.SourceChannelCode,
            Status = order.Status,
            FromPhone = order.FromPhone,
            FromName = order.FromName,
            ApprovedAmount = redPackAudit.ApprovedAmount,
            IsIssued = redPackAudit.IsIssued,
            County = order.County,
            IsDeal = snapshot.IsDeal,
            NetworkENumber = snapshot.NetworkENumber,
            IsTruth = snapshot.IsTruth,
            IsTruthDepartment = snapshot.IsTruthDepartment,
            IsRepetition = snapshot.IsRepetition,
            IsRectify = snapshot.IsRectifyDepartment,
            CreationTime = order.CreationTime,
            LevelOneAuditName = redPackAudit.LevelOneAuditName,
            LevelOneAuditOrgName = redPackAudit.LevelOneAuditOrgName,
            LevelOneAuditRemark = redPackAudit.LevelOneAuditRemark,
            LevelOneAuditTime = redPackAudit.LevelOneAuditTime,
            NetworkRemark = snapshot.NetworkRemark,
            LevelOneStatus = redPackAudit.LevelOneStatus,
            LevelTwoStatus = redPackAudit.LevelTwoStatus,
            LevelTwoAuditTime = redPackAudit.LevelTwoAuditTime,
            LevelTwoAuditRemark = redPackAudit.LevelTwoAuditRemark,
        }, true);
    }

    /// <summary>
    /// 获取审核短信模板
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<IList<GetRedPackAuditSMSTemplateOutDto>> GetRedPackAuditSMSTemplateAsync(GetRedPackAuditSMSTemplateInDto dto)
    {
        var industryId = await _orderSnapshotRepository.Queryable()
            .Where(m => m.Id == dto.OrderId)
            .Select(m => m.IndustryId).FirstAsync();
        var items = await _snapshotSMSTemplateRepository.Queryable(includeDeleted: true)
            .Where(sms => (sms.IsPublic == true || sms.IndustryId == industryId)
             && sms.Status == dto.Status && sms.IsEnable == true && sms.IsDeleted == false)
            .Select(sms => new GetRedPackAuditSMSTemplateOutDto
            {
                Id = sms.Id,
                Content = sms.Content
            })
            .GroupBy(sms => new { sms.Id, sms.Content })
            .ToListAsync();
        return items;
    }

    /// <summary>
    /// 审核添加备注
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task UpdateRedPackAuditRemarkAsync(UpdateRedPackAuditRemarkInDto dto)
    {
        var audit = await _redPackAuditRepository.GetAsync(dto.RedPackAuditId) ?? throw UserFriendlyException.SameMessage("审核记录不存在");
        if (audit.AcutalAmount == 0)
            audit.IsSend = false;
        else
            audit.IsSend = dto.IsSend;
        audit.AcutalAmount = dto.AcutalAmount;
        audit.IsSend = dto.IsSend;
        audit.SendRemarks = dto.SendRemarks;
        await _redPackRecordRepository.Queryable()
            .Where(m => m.RedPackAuditId == audit.Id)
            .FirstAsync()
            .Then(async (record) =>
            {
                if (dto.FailCase != null)
                {
                    record.FailCase = dto.FailCase.Value;
                    record.DistributionState = EReadPackSendStatus.Fail;
                    if (record.FailCase == ERedPackPickupFailCase.Excuse)
                        record.PickupStatus = ERedPackPickupStatus.Excuse;
                }
                if (dto.IsSend)
                {
                    record.DistributionState = EReadPackSendStatus.Successful;
                    record.PickupStatus = ERedPackPickupStatus.Received;
                }
                if (dto.AcutalAmount == 0)
                {
                    record.PickupStatus = ERedPackPickupStatus.Unreceived;
                    record.DistributionState = EReadPackSendStatus.Unsend;
                }
                record.Amount = dto.AcutalAmount;
                await _redPackRecordRepository.UpdateAsync(record);
            });

        await _redPackAuditRepository.UpdateAsync(audit);
    }

    /// <summary>
    /// 添加补充发放信息
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task UpdateRedPackRecordAsync(UpdateRedPackRecordInDto dto)
    {
        await _redPackAuditRepository.Queryable().Where(m => m.Id == dto.RedPackAuditId)
            .Select(m => new { m.Id, m.OrderId })
            .FirstAsync()
            .Then(async audit =>
            {
                var orderNo = await _orderRepository.Queryable().Where(m => m.Id == audit.OrderId).Select(m => m.No).FirstAsync();

                var entity = dto.Adapt<SupplementRecord>();
                var industryName = await _orderSnapshotRepository.Queryable()
                    .Where(m => m.Id == audit.OrderId)
                    .Select(m => new { m.IndustryName, m.IndustryId })
                    .FirstAsync();
                entity.OrderId = audit.OrderId;
                entity.RedPackAuditId = audit.Id;
                entity.No = orderNo;
                entity.IndustryName = industryName.IndustryName;
                entity.IndustryId = industryName.IndustryId;
                entity.ReplenishRemark = dto.ReplenishRemark;
                await _supplementRecordRepository.AddAsync(entity);

                if (dto.IsSendSMS)
                {
                    // TODO: 发送短信
                }
            });
    }

    /// <summary>
    /// 添加补充发放信息(特殊红包)
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task UpdateRedPackSpecialRecordAsync(UpdateRedPackRecordInDto dto)
    {
        await _specialRedPackAuditRepository.Queryable()
            .Where(m => m.Id == dto.RedPackAuditId)
            .Select(m => new { m.Id, m.OrderId })
            .FirstAsync()
            .Then(async audit =>
            {
                var orderNo = await _orderRepository.Queryable().Where(m => m.Id == audit.OrderId).Select(m => m.No).FirstAsync();
                var auditTypeId = _systemDic.SnapshotRedPackSpecialType.FirstOrDefault(m => m.DicDataName.StartsWith(dto.AuditType))?.DicDataValue;

                var entity = dto.Adapt<SupplementRecord>();
                var industryName = await _orderSnapshotRepository.Queryable()
                    .Where(m => m.Id == audit.OrderId)
                    .Select(m => new { m.IndustryName, m.IndustryId })
                    .FirstAsync();
                entity.OrderId = audit.OrderId;
                entity.RedPackAuditId = audit.Id;
                entity.No = orderNo;
                entity.IndustryName = industryName.IndustryName;
                entity.IndustryId = industryName.IndustryId;
                entity.ReplenishRemark = dto.ReplenishRemark;
                entity.AuditType = dto.AuditType;
                entity.AuditTypeCode = auditTypeId;
                await _supplementRecordRepository.AddAsync(entity);

                if (dto.IsSendSMS)
                {
                    // TODO: 发送短信
                }
            });
    }


    #region 红包发放记录

    /// <summary>
    /// 市民红包发放记录
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [ExportExcel("市民红包发放记录")]
    public ISugarQueryable<SnapshotRedPackRecordItemsOutDto> GetRedPackRecordItems(SnapshotRedPackRecordItemsInDto dto)
    {
        var query = _redPackRecordRepository.Queryable()
            .Where(m => m.PeopleType == EReadPackUserType.Citizen)
            .WhereIF(dto.BeginCreationTime.HasValue && dto.EndCreationTime.HasValue, m => m.CreationTime >= dto.BeginCreationTime && m.CreationTime <= dto.EndCreationTime)
            .WhereIF(dto.No.NotNullOrEmpty(), m => m.No.Contains(dto.No))
            .WhereIF(dto.PhoneNumber.NotNullOrEmpty(), m => m.PhoneNumber.Contains(dto.PhoneNumber))
            .Select<SnapshotRedPackRecordItemsOutDto>();

        if (dto.Status == 3)
            query = query.Where(m => m.PickupStatus == ERedPackPickupStatus.Excuse);
        else
        {
            if (Enum.TryParse(dto.Status.ToString(), out EReadPackSendStatus status))
                query = query.Where(m => m.DistributionState == status);
        }
        return query;
    }

    /// <summary>
    /// 获取特提参数
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<GetAuditBackBaseDataOutDto> GetAuditBackBaseDataAsync(string id)
    {
        var order = await _orderRepository.Queryable()
            .Where(m => m.Id == id)
            .Select<GetAuditBackBaseDataOutDto>()
            .FirstAsync()
            ?? throw UserFriendlyException.SameMessage("工单不存在");

        order.SpecialNum = await _orderSpecialRepository.CountAsync(x => x.OrderId == id);
        return order;
    }

    [ExportExcel("网格员红包发放记录")]
    public ISugarQueryable<SnapshotRedPackRecordItemsGuiderOutDto> GetRedPackRecordGuiderItems(SnapshotRedPackRecordItemsGuiderInDto dto)
    {
        var query = _redPackRecordRepository.Queryable()
            .Where(m => m.PeopleType == EReadPackUserType.Guider)
            .WhereIF(dto.BeginCreationTime.HasValue && dto.EndCreationTime.HasValue, m => m.CreationTime >= dto.BeginCreationTime && m.CreationTime <= dto.EndCreationTime)
            .WhereIF(dto.No.NotNullOrEmpty(), m => m.No.Contains(dto.No))
            .WhereIF(dto.PhoneNumber.NotNullOrEmpty(), m => m.PhoneNumber.Contains(dto.PhoneNumber))
            .WhereIF(dto.Name.NotNullOrEmpty(), m => m.Name.Contains(dto.Name))
            .OrderByDescending(m => m.CreationTime)
            .Select<SnapshotRedPackRecordItemsGuiderOutDto>();

        if (dto.Status == 3)
            query = query.Where(m => m.PickupStatus == ERedPackPickupStatus.Excuse);
        else
        {
            if (Enum.TryParse(dto.Status.ToString(), out EReadPackSendStatus status))
                query = query.Where(m => m.DistributionState == status);
        }
        return query;
    }

    [ExportExcel("红包发放明细")]
    public ISugarQueryable<SnapshotRedPackRecordSendOutDto> GetRedPackRecordDetail(SnapshotRedPackRecordSendInDto dto)
    {
        var query = _redPackRecordRepository.Queryable()
            .LeftJoin<OrderSnapshot>((m, snapshot) => m.OrderId == snapshot.Id)
            .LeftJoin<Order>((m, snapshot, order) => m.OrderId == order.Id)
            .Where(m => m.DistributionState != EReadPackSendStatus.Unsend)
            .WhereIF(dto.Status == 1, m => m.PickupStatus == ERedPackPickupStatus.Received)
            .WhereIF(dto.Status == 2, m => m.PickupStatus == ERedPackPickupStatus.Back)
            .WhereIF(dto.Status == 3, m => m.DistributionState == EReadPackSendStatus.Fail)
            .WhereIF(dto.Status == 4, m => m.PickupStatus == ERedPackPickupStatus.Unreceived)
            .WhereIF(dto.IndustryId.NotNullOrEmpty(), (m, snapshot) => snapshot.IndustryId == dto.IndustryId)
            .WhereIF(dto.No.NotNullOrEmpty(), order => order.No.Contains(dto.No))
            .WhereIF(dto.UserType.HasValue, m => m.PeopleType == dto.UserType)
            .WhereIF(dto.OpenId.NotNullOrEmpty(), m => m.WXOpenId == dto.OpenId)
            .WhereIF(dto.SendStatus.HasValue, m => m.DistributionState == dto.SendStatus)
            .WhereIF(dto.IsReceive.HasValue && dto.IsReceive == true, m => m.PickupStatus == ERedPackPickupStatus.Received)
            .WhereIF(dto.IsReceive.HasValue && dto.IsReceive == false, m => m.PickupStatus == ERedPackPickupStatus.Unreceived)
            .WhereIF(dto.BeginCreationTime.HasValue && dto.EndCreationTime.HasValue, m => m.CreationTime >= dto.BeginCreationTime && m.CreationTime <= dto.EndCreationTime)
            .Select((m, snapshot, order) => new SnapshotRedPackRecordSendOutDto
            {
                OrderId = m.OrderId,
                UserType = m.PeopleType,
                IndustryName = snapshot.IndustryName,
                WXOpenId = m.WXOpenId,
                MerchantCode = m.MerchantCode
            }, true);
        return query;
    }

    /// <summary>
    /// 补充发放集合
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [ExportExcel("补充发放")]
    public ISugarQueryable<SnapshotRedPackRecordSupplementItemsOutDto> GetRedPackRecordSupplementItems(SnapshotRedPackRecordSupplementItemsInDto dto)
    {
        var query = _supplementRecordRepository.Queryable()
            .LeftJoin<Order>((supp, order) => supp.OrderId == order.Id)
            .WhereIF(dto.No.NotNullOrEmpty(), (supp, order) => order.No.Contains(dto.No))
            .WhereIF(dto.FromPhone.NotNullOrEmpty(), (supp, order) => order.FromPhone.Contains(dto.FromPhone))
            .WhereIF(dto.Title.NotNullOrEmpty(), (supp, order) => order.Title.Contains(dto.Title))
            .WhereIF(dto.IndustryId.NotNullOrEmpty(), (supp, order) => supp.IndustryId == dto.IndustryId)
            .WhereIF(dto.BeginCreationTime.HasValue && dto.EndCreationTime.HasValue, (supp, order) => supp.CreationTime >= dto.BeginCreationTime && supp.CreationTime <= dto.EndCreationTime)
            .Select((supp, order) => new SnapshotRedPackRecordSupplementItemsOutDto
            {
                Remark = supp.ReplenishRemark
            }, true);
        return query;
    }

    public async Task AuditRedPackSpecialAuditAsync(UpdateRedPackSpecialAuditInDto dto)
    {
        var audit = await _redPackAuditRepository.GetAsync(dto.RedPackAuditId) ?? throw UserFriendlyException.SameMessage("审核记录不存在");
        if (_specialRedPackAuditRepository.ExistByOrderId(audit.OrderId)) throw UserFriendlyException.SameMessage("已审核, 不可重复审核");
        var specialAudit = audit.Adapt<SpecialRedPackAudit>();
        if (dto.AuditTypeId.NotNullOrEmpty())
        {
            var specialType = _systemDic.SnapshotRedPackSpecialType.FirstOrDefault(m => m.Id == dto.AuditTypeId);
            if (specialType != null)
            {
                specialAudit.AuditType = specialType.DicDataName.Split('|')[0];
                specialAudit.AuditTypeCode = specialType.DicDataValue;
            }
        }
        specialAudit.Status = dto.Status;
        specialAudit.ApprovedAmount = dto.ApprovedAmount;
        specialAudit.AuditId = _sessionContext.UserId;
        specialAudit.AuditName = _sessionContext.UserName;
        specialAudit.AuditOrgId = _sessionContext.OrgId;
        specialAudit.AuditOrgName = _sessionContext.OrgName;
        await _specialRedPackAuditRepository.AddAsync(specialAudit);
    }

    public async Task<SnapshotOrderAuditSpecialDetailOutDto> GetRedPackSpecialAuditBaseDataAsync(string id)
    {
        var outDto = new SnapshotOrderAuditSpecialDetailOutDto();
        var order = await _orderRepository.GetAsync(id) ?? throw new UserFriendlyException("工单不存在");
        outDto.Order = order.Adapt<SnapshotOrderAuditOrderDetailOutDto>();
        outDto.AuditType = _systemDic.SnapshotRedPackSpecialType.Adapt<List<SystemDicDataAmountOutDto>>();
        outDto.AuditComBox = EnumExts.GetDescriptions<ERedPackAuditStatus>().Where(m => m.Key != 0).ToList();
        var audit = await _redPackAuditRepository.GetAsync(m => m.OrderId == id);
        outDto.AuditDetail = audit.Adapt<SnapshotOrderAuditSpecialAuditDetailOutDto>();
        return outDto;
    }

    /// <summary>
    /// 获取补充发放记录基础数据
    /// </summary>
    /// <param name="v"></param>
    /// <param name="orderId"></param>
    /// <returns></returns>
    public async Task<GetRedPackRecordBaseDataOutDto> GetRedPackRecordBaseDataAsync(string orderId)
    {
        var snapshot = await _orderSnapshotRepository.Queryable()
            .Where(m => m.Id == orderId)
            .Select(m => new
            {
                m.Id,
                m.AwardBankCardNo,
                m.AwardOpenBank,
                m.AwardName,
            })
            .FirstAsync();
        var outDto = new GetRedPackRecordBaseDataOutDto();
        if (snapshot != null)
        {
            outDto.BankCardNo = snapshot.AwardBankCardNo;
            outDto.OpenBank = snapshot.AwardOpenBank;
            outDto.Name = snapshot.AwardName;
        }
        var audit = await _specialRedPackAuditRepository.Queryable().Where(m => m.OrderId == orderId).FirstAsync()
            ?? throw new UserFriendlyException("审核记录不存在");
        if (audit != null)
        {
            outDto.AuditType = audit.AuditType;
            outDto.AuditTypeCode = audit.AuditTypeCode;
            outDto.RedPackAuditId = audit.Id;
            outDto.Amount = audit.ApprovedAmount;
        }
        outDto.OrderId = orderId;
        outDto.ReplenishType = _systemDic.SnapshotReplenishType;
        return outDto;
    }



    #endregion
}
