//package com.red.circle.console.app.scheduler;
//
//
//import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
//import com.red.circle.common.business.enums.OperationUserOrigin;
//import com.red.circle.component.redis.annotation.TaskCacheLock;
//import com.red.circle.console.app.anchoragent.AnchorAgentManager;
//import com.red.circle.framework.core.asserts.ResponseAssert;
//import com.red.circle.mq.rocket.business.producer.TeamSalaryMqMessage;
//import com.red.circle.other.inner.endpoint.activity.ActivityAgentAnchorCountClient;
//import com.red.circle.other.inner.endpoint.activity.AgentActivityCountClient;
//import com.red.circle.other.inner.endpoint.approval.TeamApplicationProcessApprovalClient;
//import com.red.circle.other.inner.endpoint.approval.TeamApplicationProcessClient;
//import com.red.circle.other.inner.endpoint.approval.TeamTerminationFeeRecordClient;
//import com.red.circle.other.inner.endpoint.team.target.TeamMemberClient;
//import com.red.circle.other.inner.endpoint.team.target.TeamMemberTargetClient;
//import com.red.circle.other.inner.endpoint.team.target.TeamProfileClient;
//import com.red.circle.other.inner.enums.team.TeamAppProcessApprovalReason;
//import com.red.circle.other.inner.enums.team.TeamApplicationType;
//import com.red.circle.other.inner.model.cmd.team.TeamMemberIdCmd;
//import com.red.circle.other.inner.model.dto.agency.agency.TeamApplicationProcessApprovalDTO;
//import com.red.circle.other.inner.model.dto.agency.agency.TeamMemberDTO;
//import com.red.circle.other.inner.model.dto.team.TeamApplicationProcessDTO;
//import com.red.circle.other.inner.model.dto.team.TeamTerminationFeeRecordDTO;
//import com.red.circle.tool.core.collection.CollectionUtils;
//import com.red.circle.tool.core.date.TimestampUtils;
//import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
//import com.red.circle.tool.core.sequence.IdWorkerUtils;
//import com.red.circle.wallet.inner.endpoint.wallet.WalletGoldClient;
//import com.red.circle.wallet.inner.model.cmd.GoldReceiptCmd;
//import com.red.circle.wallet.inner.model.dto.WalletReceiptResDTO;
//import com.red.circle.wallet.inner.model.enums.GoldOrigin;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//
//import java.math.BigDecimal;
//import java.math.RoundingMode;
//import java.util.*;
//import java.util.stream.Collectors;
//
///**
// * 每天检查一次是否有提交申请离开团队超过一个月没有得到团队处理的申请，有则系统帮助其退出.
// *
// * @author longli on 2024/03/14.
// */
//@Slf4j
//@Component
//@AllArgsConstructor
//public class DeleteTeamMemberTask {
//
//  private final WalletGoldClient walletGoldClient;
//  //  private final UserWalletService userWalletService;
//  private final TeamMemberClient teamMemberClient;
//  private final AnchorAgentManager anchorAgentManager;
//  private final TeamProfileClient teamProfileService;
//  private final TeamSalaryMqMessage teamSalaryMqMessage;
//  private final TeamMemberTargetClient teamMemberTargetService;
//  private final AgentActivityCountClient agentActivityCountService;
//  private final TeamApplicationProcessClient teamApplicationProcessService;
//  private final TeamTerminationFeeRecordClient teamTerminationFeeRecordClient;
//  private final ActivityAgentAnchorCountClient activityAgentAnchorCountService;
//  private final TeamApplicationProcessApprovalClient teamApplicationProcessApprovalClient;
//
//  /**
//   * 每天凌晨0点执行一次
//   */
//  @Scheduled(cron = "1 0 0 * * ?", zone = "Asia/Riyadh")
//  @TaskCacheLock(key = "DELETE_TEAM_APPLY", expireSecond = 79200)
//  public void deleteTeamApply() {
//
//    log.warn("每天清理团队退出申请 start，时间:{}", TimestampUtils.now());
//
//    // 删除申请退出团队超30天的申请记录
//    delete30Days();
//
//    // 每月2号清理上个月团队为处理的申请退出记录
//    monthlyNo2Delete();
//
//    // 删除有支付申请退出费用的主播,且还没有分钱给代理,且申请时间大于24小时的记录
//    remoteTimeGt24AndPayeeUserNull();
//
//    log.warn("每天清理团队退出申请 end，时间:{}", TimestampUtils.now());
//  }
//
//  /**
//   * 删除有支付主播解约非后申请退出的主播并且还没有分钱给代理并且付钱时间距离当前时间大于24小时的记录
//   */
//  private void remoteTimeGt24AndPayeeUserNull() {
//
//    List<TeamTerminationFeeRecordDTO> terminationFeeRecords = listByTimeGt24AndPayeeUserNull();
//    if (CollectionUtils.isEmpty(terminationFeeRecords)) {
//      return;
//    }
//
//    // 获得申请记录
//    List<TeamApplicationProcessDTO> processList = teamApplicationProcessService.getByIds(
//        terminationFeeRecords.stream().map(TeamTerminationFeeRecordDTO::getId)
//            .collect(Collectors.toSet())).getBody();
//
//    // 处理申请记录与删除团队成员.
//    processApply(processList);
//  }
//
//  private List<TeamTerminationFeeRecordDTO> listByTimeGt24AndPayeeUserNull() {
//    return teamTerminationFeeRecordClient.listByTimeGt24AndPayeeUserNull().getBody();
//  }
//
//  /**
//   * 每月2号清理上个月团队为处理的申请退出记录.
//   */
//  private void monthlyNo2Delete() {
//
//    // 每月2号系统同意上个月申请离开团队成员申请
//    if (TimestampUtils.now().toLocalDateTime().getDayOfMonth() != 2) {
//      return;
//    }
//    List<TeamApplicationProcessDTO> processList = getProcessList();
//    if (CollectionUtils.isEmpty(processList)) {
//      log.warn("DeleteTeamMemberTask-上个月没有申请离开团队未处理的记录,时间:{}",
//          TimestampUtils.now());
//      return;
//    }
//
//    // 处理申请记录与删除团队成员.
//    processApply(processList);
//
//  }
//
//  private List<TeamApplicationProcessDTO> getProcessList() {
//    return teamApplicationProcessService.listLastMonthApplyOutTeamMember();
//  }
//
//  /**
//   * 删除申请离开团队时间大于30天的团队成员.
//   */
//  private void delete30Days() {
//
//    // 当前月份的第一天与最后两天不允许删除操作
//    if (Boolean.FALSE.equals(anchorAgentManager.checkCanDelete())) {
//      log.warn("当前月份的第一天与最后两天不允许删除团队成员，时间:{}", TimestampUtils.now());
//      return;
//    }
//
//    // 获得申请离开团队时间大于30天的团队成员
//    List<TeamApplicationProcessDTO> processList = teamApplicationProcessService
//        .listApplyOutTeamMember(30);
//    if (CollectionUtils.isEmpty(processList)) {
//      log.warn("DeleteTeamMemberTask-没有申请离开团队超过30天未处理的记录,时间:{}",
//          TimestampUtils.now());
//      return;
//    }
//
//    // 处理申请记录与删除团队成员.
//    processApply(processList);
//
//  }
//
//  /**
//   * 处理申请记录与删除团队成员.
//   */
//  private void processApply(List<TeamApplicationProcessDTO> processList) {
//
//    if (CollectionUtils.isEmpty(processList)) {
//      return;
//    }
//
//    Map<Long, TeamMemberDTO> teamMemberMap = getTeamMemberMap(processList);
//    if (CollectionUtils.isEmpty(teamMemberMap)) {
//      return;
//    }
//
//    // 处理申请记录.
//    processList.forEach(process -> {
//
//      // 根据记录id获得该记录最新状态,避免一次处理太多别的地方处理的问题
//      TeamApplicationProcessDTO newProcess = teamApplicationProcessService.getQuitWaitApplyById(
//          process.getId());
//      if (Objects.isNull(newProcess)) {
//        return;
//      }
//
//      TeamMemberDTO teamMember = teamMemberMap.get(newProcess.getCreateUser());
//      if (Objects.isNull(teamMember)) {
//        return;
//      }
//
//      if (!Objects.equals(teamMember.getTeamId(), newProcess.getAssociateId())) {
//        return;
//      }
//
//      // 添加退出团队日志.
//      teamApplicationProcessApprovalClient.add(new TeamApplicationProcessApprovalDTO()
//          .setSysOrigin(teamMember.getSysOrigin())
//          .setType(TeamApplicationType.TEAM)
//          .setReason(TeamAppProcessApprovalReason.MEMBER_APPLY_TIME_OUT)
//          .setAssociateId(process.getAssociateId())
//          .setBeProcessUserId(teamMember.getMemberId())
//          .setCreateTime(TimestampUtils.now())
//          .setCreateUser(0L)
//          .setCreateUserOrigin(OperationUserOrigin.BACK.getValue())
//          .setExpiredTime(TimestampUtils.nowPlusDays(7)));
//
//      // 代理活动.
//      agentActivityCountService.reduceTarget(Set.of(teamMember.getTeamId()),
//          teamMemberTargetService.getLatestInProgressTarget(teamMember.getMemberId()));
//
//      // 删除申请记录.
//      teamApplicationProcessService.deleteById(newProcess.getId());
//
//      List<Long> teamMemberIds = new ArrayList<>();
//      teamMemberIds.add(teamMember.getMemberId());
//      TeamMemberIdCmd teamMemberIdCmd = new TeamMemberIdCmd();
//      teamMemberIdCmd.setIds(teamMemberIds);
//      // 删除团队成员.
//      teamMemberClient.removeMemberTeam(teamMemberIdCmd);
//
//      // 移除最新目标.
//      teamMemberTargetService.removeUserTarget(ZonedDateTimeAsiaRiyadhUtils.nowYearMonthToInt(),
//          teamMember.getMemberId());
//
//      // 重新统计团队工资.
//      teamSalaryMqMessage.sendSalaryCount(Set.of(teamMember.getTeamId()));
//
//      // 归零活动积分
//      activityAgentAnchorCountService.initZero(teamMember.getMemberId(), teamMember.getTeamId());
//
//      // 将解约费拨款给代理
//      sendTerminationFee(newProcess, teamMember.getTeamId());
//    });
//  }
//
//  private void sendTerminationFee(TeamApplicationProcessDTO process, Long teamId) {
//
//    if (Objects.isNull(teamId)) {
//      return;
//    }
//
//    Long teamOwnUserId = teamProfileService.getOwnUserIdById(teamId).getBody();
//    if (Objects.isNull(teamOwnUserId)) {
//      return;
//    }
//
//    TeamTerminationFeeRecordDTO terminationFeeRecord = getTerminationFeeRecord(process);
//    if (Objects.isNull(terminationFeeRecord)) {
//      return;
//    }
//
//    if (Objects.nonNull(terminationFeeRecord.getPayeeUserId())) {
//      return;
//    }
//
//    BigDecimal amount = terminationFeeRecord.getTerminationFee().multiply(BigDecimal.valueOf(0.8))
//        .setScale(0, RoundingMode.DOWN);
//    WalletReceiptResDTO walletReceiptResDTO = ResponseAssert.requiredSuccess(
//        walletGoldClient.changeBalance(GoldReceiptCmd.builder()
//            .appIncome()
//            .eventId(IdWorkerUtils.getId())
//            .userId(teamOwnUserId)
//            .sysOrigin(SysOriginPlatformEnum.valueOf(process.getSysOrigin()))
//            .origin(GoldOrigin.HOST_TERMINATION_FEE)
//            .amount(amount)
//            .build()));
//
//    if (walletReceiptResDTO == null) {
//      return;
//    }
//
//    terminationFeeRecord.setPayeeAmount(amount);
//    terminationFeeRecord.setPayeeUserId(teamOwnUserId);
//    terminationFeeRecord.setPayeeRunningWaterId(walletReceiptResDTO.getAssetRecordId());
//    terminationFeeRecord.setUpdateTime(TimestampUtils.now());
//    terminationFeeRecord.setUpdateUser(1L);
//    teamTerminationFeeRecordClient.updateSelectiveById(terminationFeeRecord);
//  }
//
//  private TeamTerminationFeeRecordDTO getTerminationFeeRecord(TeamApplicationProcessDTO process) {
//    return teamTerminationFeeRecordClient.getById(process.getId()).getBody();
//  }
//
//  private Map<Long, TeamMemberDTO> getTeamMemberMap(List<TeamApplicationProcessDTO> processList) {
//    return teamMemberClient
//        .mapByMemberIds(processList.stream().map(TeamApplicationProcessDTO::getCreateUser)
//            .collect(Collectors.toSet())).getBody();
//  }
//
//
//}
