package com.red.circle.other.app.command.bd.query;

import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.TeamBdMemberBillAnchorDetailCO;
import com.red.circle.other.app.dto.clientobject.TeamBdMemberBillDetailCO;
import com.red.circle.other.app.dto.cmd.TeamBdMemberBillDetailCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.dto.team.TeamBillSettleResult;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamBillCycle;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamMemberTarget;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamProfile;
import com.red.circle.other.infra.database.mongo.service.team.TeamBillCycleUtils;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamBillCycleService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamMemberTargetService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamProfileService;
import com.red.circle.other.infra.database.rds.entity.team.BusinessDevelopmentTeam;
import com.red.circle.other.infra.database.rds.service.team.BusinessDevelopmentTeamService;
import com.red.circle.other.inner.model.dto.agency.agency.TeamCounter;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.enums.team.TeamMemberTargetSettlementResult;
import com.red.circle.tool.core.collection.CollectionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 查询 BD 成员账单明细执行器.
 *
 * @author tf
 * @since 2025-10-28
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TeamBdMemberBillDetailQryExe {

    private final BusinessDevelopmentTeamService businessDevelopmentTeamService;
    private final TeamBillCycleService teamBillCycleService;
    private final TeamProfileService teamProfileService;
    private final TeamMemberTargetService teamMemberTargetService;
    private final UserProfileGateway userProfileGateway;
    private final UserProfileAppConvertor userProfileAppConvertor;

    /**
     * 执行查询.
     *
     * @param cmd 查询命令
     * @return 账单明细列表
     */
    public List<TeamBdMemberBillDetailCO> execute(TeamBdMemberBillDetailCmd cmd) {
        Long teamId = cmd.getTeamId();

        // 2. 查询团队的最新账单列表（使用 listLatestBill 获取最近的账单记录）
        List<TeamBillCycle> billCycleList = teamBillCycleService.listLatestBill(teamId, 10);
        
        if (CollectionUtils.isEmpty(billCycleList)) {
            return Collections.emptyList();
        }

        // 3. 获取团队Profile信息
        TeamProfile teamProfile = teamProfileService.getById(teamId);
        Integer teamMemberCount = Optional.ofNullable(teamProfile)
                .map(TeamProfile::getCounter)
                .map(TeamCounter::getMemberQuantity)
                .map(Long::intValue)
                .orElse(0);

        // 4. 遍历每个账单周期，组装明细数据
        return billCycleList.stream()
                .map(billCycle -> buildBillDetailCO(billCycle, teamMemberCount))
                .collect(Collectors.toList());
    }

    /**
     * 构建账单明细CO.
     */
    private TeamBdMemberBillDetailCO buildBillDetailCO(TeamBillCycle billCycle, Integer teamMemberCount) {
        TeamBdMemberBillDetailCO co = new TeamBdMemberBillDetailCO();

        // 1. 账单周期日期
        String[] dates = TeamBillCycleUtils.parseBillBelongToDateRange(billCycle.getBillBelong());
        co.setStartDate(dates[0]);
        co.setEndDate(dates[1]);

        // 2. 团队人数
        co.setTeamMemberCount(teamMemberCount);

        // 3. 账单状态
        co.setStatus(billCycle.getStatus());

        // 4. 团队薪资和充值
        TeamBillSettleResult settleResult = billCycle.getSettleResult();
        if (settleResult != null) {
            co.setTeamSalaryAmount(settleResult.getTotalSalary());
            co.setTeamRechargeAmount(BigDecimal.ZERO);

            // BD收益计算
            BigDecimal salaryRatio = new BigDecimal("0.03"); // 3%
            BigDecimal rechargeRatio = new BigDecimal("0.05"); // 5%

            co.setBdRatioSalary(salaryRatio.multiply(new BigDecimal("100")));
            co.setBdRatioRecharge(rechargeRatio.multiply(new BigDecimal("100")));

            BigDecimal bdSalaryIncome = Optional.ofNullable(settleResult.getTotalSalary())
                    .orElse(BigDecimal.ZERO)
                    .multiply(salaryRatio);
            BigDecimal bdRechargeIncome = Optional.ofNullable(BigDecimal.ZERO)
                    .orElse(BigDecimal.ZERO)
                    .multiply(rechargeRatio);

            co.setBdIncomeSalary(bdSalaryIncome);
            co.setBdIncomeRecharge(bdRechargeIncome);
        } else {
            co.setTeamSalaryAmount(BigDecimal.ZERO);
            co.setTeamRechargeAmount(BigDecimal.ZERO);
            co.setBdIncomeSalary(BigDecimal.ZERO);
            co.setBdIncomeRecharge(BigDecimal.ZERO);
            co.setBdRatioSalary(BigDecimal.ZERO);
            co.setBdRatioRecharge(BigDecimal.ZERO);
        }

        // 5. 查询主播明细列表
        List<TeamBdMemberBillAnchorDetailCO> anchorDetails = buildAnchorDetails(
                billCycle.getTeamId(), billCycle.getBillBelong());
        co.setAnchorDetails(anchorDetails);

        return co;
    }

    /**
     * 构建主播明细列表.
     */
    private List<TeamBdMemberBillAnchorDetailCO> buildAnchorDetails(Long teamId, Integer billBelong) {
        // 1. 查询该账单周期下的所有成员Target
        List<TeamMemberTarget> memberTargets = teamMemberTargetService.listByBillBelong(teamId, billBelong);

        if (CollectionUtils.isEmpty(memberTargets)) {
            return Collections.emptyList();
        }

        // 2. 获取所有成员的用户信息
        Set<Long> userIdSet = memberTargets.stream()
                .map(TeamMemberTarget::getUserId)
                .collect(Collectors.toSet());

        Map<Long, UserProfileDTO> userProfileMap = userProfileAppConvertor.toMapUserProfileDTO(
                userProfileGateway.mapByUserIds(userIdSet));

        // 3. 组装主播明细
        return memberTargets.stream()
                .map(target -> buildAnchorDetailCO(target, userProfileMap))
                .collect(Collectors.toList());
    }

    /**
     * 构建主播明细CO.
     */
    private TeamBdMemberBillAnchorDetailCO buildAnchorDetailCO(
            TeamMemberTarget target,
            Map<Long, UserProfileDTO> userProfileMap) {

        TeamBdMemberBillAnchorDetailCO co = new TeamBdMemberBillAnchorDetailCO();

        // 用户信息
        UserProfileDTO userProfile = userProfileMap.get(target.getUserId());
        if (userProfile != null) {
            co.setUserId(target.getUserId());
            co.setUserName(userProfile.getUserNickname());
            co.setAvatar(userProfile.getUserAvatar());
        }

        // 从 settlementResult 中获取薪资数据
        TeamMemberTargetSettlementResult settlementResult = target.getSettlementResult();
        if (settlementResult != null) {
            // 薪资（totalSalary）
            co.setSalary(settlementResult.getTotalSalary());
            // 充值（acceptGiftValue）
            co.setRecharge(BigDecimal.ZERO);
        } else {
            co.setSalary(BigDecimal.ZERO);
            co.setRecharge(BigDecimal.ZERO);
        }

        // 开播次数 TODO: 从直播记录中统计
        co.setHostCount(0);

        return co;
    }
}
