package com.red.circle.other.app.service.team;

import com.red.circle.other.app.dto.clientobject.team.*;
import com.red.circle.other.app.dto.cmd.team.BdHistoryMoreQryCmd;
import com.red.circle.other.app.dto.cmd.team.BdHistoryQryCmd;
import com.red.circle.other.app.dto.cmd.team.BdLeaderHistoryMoreQryCmd;
import com.red.circle.other.app.dto.cmd.team.BdLeaderHistoryQryCmd;
import com.red.circle.other.infra.database.mongo.entity.bd.BdLeaderSalarySettlementRecord;
import com.red.circle.other.infra.database.mongo.entity.bd.BdSalarySettlementRecord;
import com.red.circle.other.infra.database.mongo.entity.bd.detail.BdLeaderTeamMemberDetail;
import com.red.circle.other.infra.database.mongo.entity.bd.detail.BdTeamMemberDetail;
import com.red.circle.other.infra.enums.BdSettlementStatus;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * BD历史记录服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeamBdHistoryServiceImpl implements TeamBdHistoryService {

    private final MongoTemplate mongoTemplate;

    @Override
    public BdHistorySummaryCO queryBdHistory(BdHistoryQryCmd cmd) {
        Long userId = cmd.getReqUserId();
        String sysOrigin = cmd.getReqSysOrigin().getOrigin();

        // 构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("bdUserId").is(userId));
        query.addCriteria(Criteria.where("sysOrigin").is(sysOrigin));
        
        // 如果指定了状态，添加状态过滤
        if (StringUtils.isNotBlank(cmd.getStatus())) {
            query.addCriteria(Criteria.where("status").is(BdSettlementStatus.valueOf(cmd.getStatus())));
        }
        
        // 按结算周期降序排序
        query.with(org.springframework.data.domain.Sort.by(
            org.springframework.data.domain.Sort.Direction.DESC, "billBelong"));

        // 查询记录
        List<BdSalarySettlementRecord> records = mongoTemplate.find(
            query, BdSalarySettlementRecord.class);

        // 构建返回结果
        BdHistorySummaryCO summary = new BdHistorySummaryCO();
        
        if (CollectionUtils.isEmpty(records)) {
            summary.setTotalIncome(BigDecimal.ZERO);
            summary.setPreviousPeriodIncome(BigDecimal.ZERO);
            summary.setIncomeDetails(new ArrayList<>());
            return summary;
        }

        // 计算总收入（SUCCESS状态的记录）
        BigDecimal totalIncome = records.stream()
            .filter(r -> BdSettlementStatus.SUCCESS.equals(r.getStatus()))
            .map(BdSalarySettlementRecord::getSettlementSalary)
            .filter(java.util.Objects::nonNull)
            .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 获取上个周期收入（最近的一条SUCCESS记录）
        BigDecimal previousPeriodIncome = records.stream()
            .filter(r -> BdSettlementStatus.SUCCESS.equals(r.getStatus()))
            .findFirst()
            .map(BdSalarySettlementRecord::getSettlementSalary)
            .orElse(BigDecimal.ZERO);

        // 转换为DTO列表
        List<BdHistoryCO> incomeDetails = records.stream()
            .map(this::convertToBdHistoryCO)
            .toList();

        summary.setTotalIncome(totalIncome);
        summary.setPreviousPeriodIncome(previousPeriodIncome);
        summary.setIncomeDetails(incomeDetails);

        return summary;
    }

    @Override
    public BdLeaderHistorySummaryCO queryBdLeaderHistory(BdLeaderHistoryQryCmd cmd) {
        Long userId = cmd.getReqUserId();
        String sysOrigin = cmd.getReqSysOrigin().getOrigin();

        // 构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("bdLeaderUserId").is(userId));
        query.addCriteria(Criteria.where("sysOrigin").is(sysOrigin));
        
        // 如果指定了状态，添加状态过滤
        if (StringUtils.isNotBlank(cmd.getStatus())) {
            query.addCriteria(Criteria.where("status").is(BdSettlementStatus.valueOf(cmd.getStatus())));
        }
        
        // 按结算周期降序排序
        query.with(org.springframework.data.domain.Sort.by(
            org.springframework.data.domain.Sort.Direction.DESC, "billBelong"));

        // 查询记录
        List<BdLeaderSalarySettlementRecord> records = mongoTemplate.find(
            query, BdLeaderSalarySettlementRecord.class);

        // 构建返回结果
        BdLeaderHistorySummaryCO summary = new BdLeaderHistorySummaryCO();
        
        if (CollectionUtils.isEmpty(records)) {
            summary.setTotalIncome(BigDecimal.ZERO);
            summary.setPreviousPeriodIncome(BigDecimal.ZERO);
            summary.setIncomeDetails(new ArrayList<>());
            return summary;
        }

        // 计算总收入（SUCCESS状态的记录）
        BigDecimal totalIncome = records.stream()
            .filter(r -> BdSettlementStatus.SUCCESS.equals(r.getStatus()))
            .map(BdLeaderSalarySettlementRecord::getSettlementSalary)
            .filter(java.util.Objects::nonNull)
            .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 获取上个周期收入（最近的一条SUCCESS记录）
        BigDecimal previousPeriodIncome = records.stream()
            .filter(r -> BdSettlementStatus.SUCCESS.equals(r.getStatus()))
            .findFirst()
            .map(BdLeaderSalarySettlementRecord::getSettlementSalary)
            .orElse(BigDecimal.ZERO);

        // 转换为DTO列表
        List<BdLeaderHistoryCO> incomeDetails = records.stream()
            .map(this::convertToBdLeaderHistoryCO)
            .toList();

        summary.setTotalIncome(totalIncome);
        summary.setPreviousPeriodIncome(previousPeriodIncome);
        summary.setIncomeDetails(incomeDetails);

        return summary;
    }

    @Override
    public BdHistoryMoreCO queryBdHistoryMore(BdHistoryMoreQryCmd cmd) {
        Long userId = cmd.getReqUserId();
        String sysOrigin = cmd.getReqSysOrigin().getOrigin();
        Integer billBelong = cmd.getBillBelong();

        // 构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("bdUserId").is(userId));
        query.addCriteria(Criteria.where("sysOrigin").is(sysOrigin));
        query.addCriteria(Criteria.where("billBelong").is(billBelong));

        // 查询结算记录
        BdSalarySettlementRecord record = mongoTemplate.findOne(
            query, BdSalarySettlementRecord.class);

        // 构建返回结果
        BdHistoryMoreCO result = new BdHistoryMoreCO();
        result.setPeriod(formatPeriod(billBelong));

        if (record == null) {
            result.setTeamTotalRecharge(BigDecimal.ZERO);
            result.setTeamTotalSalary(BigDecimal.ZERO);
            result.setMemberDetails(new ArrayList<>());
            return result;
        }

        // 设置汇总数据
        result.setTeamTotalRecharge(record.getTeamRechargeAmount() != null ? 
            record.getTeamRechargeAmount() : BigDecimal.ZERO);
        result.setTeamTotalSalary(record.getTeamSalaryAmount() != null ? 
            record.getTeamSalaryAmount() : BigDecimal.ZERO);

        // 转换成员明细
        List<BdTeamMemberDetailCO> memberDetails = new ArrayList<>();
        if (!CollectionUtils.isEmpty(record.getMemberDetails())) {
            memberDetails = record.getMemberDetails().stream()
                .map(this::convertToBdTeamMemberDetailCO)
                .toList();
        }
        result.setMemberDetails(memberDetails);

        return result;
    }

    @Override
    public BdLeaderHistoryMoreCO queryBdLeaderHistoryMore(BdLeaderHistoryMoreQryCmd cmd) {
        Long userId = cmd.getReqUserId();
        String sysOrigin = cmd.getReqSysOrigin().getOrigin();
        Integer billBelong = cmd.getBillBelong();

        // 构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("bdLeaderUserId").is(userId));
        query.addCriteria(Criteria.where("sysOrigin").is(sysOrigin));
        query.addCriteria(Criteria.where("billBelong").is(billBelong));

        // 查询结算记录
        BdLeaderSalarySettlementRecord record = mongoTemplate.findOne(
            query, BdLeaderSalarySettlementRecord.class);

        // 构建返回结果
        BdLeaderHistoryMoreCO result = new BdLeaderHistoryMoreCO();
        result.setPeriod(formatPeriod(billBelong));

        if (record == null) {
            result.setTeamSalary(BigDecimal.ZERO);
            result.setBdNumber(0);
            result.setMemberDetails(new ArrayList<>());
            return result;
        }

        // 设置汇总数据
        result.setTeamSalary(record.getTeamSalaryAmount() != null ? 
            record.getTeamSalaryAmount() : BigDecimal.ZERO);
        result.setBdNumber(record.getBdNumber() != null ? record.getBdNumber() : 0);

        // 转换成员明细
        List<BdLeaderTeamMemberDetailCO> memberDetails = new ArrayList<>();
        if (!CollectionUtils.isEmpty(record.getMemberDetails())) {
            memberDetails = record.getMemberDetails().stream()
                .map(this::convertToBdLeaderTeamMemberDetailCO)
                .toList();
        }
        result.setMemberDetails(memberDetails);

        return result;
    }

    /**
     * 转换BD团队成员明细
     */
    private BdTeamMemberDetailCO convertToBdTeamMemberDetailCO(BdTeamMemberDetail detail) {
        BdTeamMemberDetailCO co = new BdTeamMemberDetailCO();
        co.setUserId(detail.getUserId());
        co.setUserName(detail.getUserName());
        co.setUserAvatar(detail.getUserAvatar());
        co.setAccount(detail.getUserAccount());
        co.setSalary(detail.getSalary() != null ? detail.getSalary() : BigDecimal.ZERO);
        co.setRecharge(detail.getRecharge() != null ? detail.getRecharge() : BigDecimal.ZERO);
        co.setHostCount(detail.getHostCount() != null ? detail.getHostCount() : 0);
        return co;
    }

    /**
     * 转换BD Leader团队成员明细
     */
    private BdLeaderTeamMemberDetailCO convertToBdLeaderTeamMemberDetailCO(BdLeaderTeamMemberDetail detail) {
        BdLeaderTeamMemberDetailCO co = new BdLeaderTeamMemberDetailCO();
        co.setBdUserId(detail.getBdUserId());
        co.setBdUserName(detail.getBdUserName());
        co.setAccount(detail.getBdUserAccount());
        co.setBdUserAvatar(detail.getBdUserAvatar());
        co.setSalary(detail.getSalary() != null ? detail.getSalary() : BigDecimal.ZERO);
        co.setAgencyCount(detail.getAgencyCount() != null ? detail.getAgencyCount() : 0);
        return co;
    }

    /**
     * 转换BD结算记录为DTO
     */
    private BdHistoryCO convertToBdHistoryCO(BdSalarySettlementRecord record) {
        BdHistoryCO co = new BdHistoryCO();
        co.setPeriod(formatPeriod(record.getBillBelong()));
        co.setBillTitle(record.getBillTitle());
        co.setBillBelong(record.getBillBelong());
        co.setAgencyNumber(record.getAgencyNumber());
        co.setTeamSalaryAmount(record.getTeamSalaryAmount());
        co.setTeamRechargeAmount(record.getTeamRechargeAmount());
        co.setSettlementSalary(record.getSettlementSalary());
        co.setStatus(record.getStatus() != null ? record.getStatus().name() : null);
        co.setStatusText(getStatusText(record.getStatus()));
        co.setHitPolicyType(record.getHitPolicyType() != null ? record.getHitPolicyType().name() : null);
        co.setHitLevel(record.getHitLevel());
        co.setCommissionRate(record.getCommissionRate());
        return co;
    }

    /**
     * 转换BD Leader结算记录为DTO
     */
    private BdLeaderHistoryCO convertToBdLeaderHistoryCO(BdLeaderSalarySettlementRecord record) {
        BdLeaderHistoryCO co = new BdLeaderHistoryCO();
        co.setPeriod(formatPeriod(record.getBillBelong()));
        co.setBillTitle(record.getBillTitle());
        co.setBillBelong(record.getBillBelong());
        co.setBdNumber(record.getBdNumber());
        co.setTeamSalaryAmount(record.getTeamSalaryAmount());
        co.setBasicSalary(record.getBasicSalary());
        co.setRewardAmount(record.getRewardAmount());
        co.setSettlementSalary(record.getSettlementSalary());
        co.setStatus(record.getStatus() != null ? record.getStatus().name() : null);
        co.setStatusText(getStatusText(record.getStatus()));
        co.setHitLevel(record.getHitLevel());
        co.setRewardEligible(record.getRewardEligible());
        co.setNewRechargeAgentCount(record.getNewRechargeAgentCount());
        return co;
    }

    /**
     * 格式化结算周期为日期范围
     * 例如: 20251101 -> 2025.11.01-2025.11.15
     *       20251116 -> 2025.11.16-2025.11.30
     */
    private String formatPeriod(Integer billBelong) {
        if (billBelong == null) {
            return "";
        }

        int year = billBelong / 10000;      // 2025
        int month = (billBelong / 100) % 100; // 11
        int day = billBelong % 100;          // 01 或 16

        LocalDate startDate, endDate;
        if (day == 1) {
            // 上半月: 1-15号
            startDate = LocalDate.of(year, month, 1);
            endDate = LocalDate.of(year, month, 15);
        } else {
            // 下半月: 16-月末
            startDate = LocalDate.of(year, month, 16);
            endDate = LocalDate.of(year, month, startDate.lengthOfMonth());
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
        return startDate.format(formatter) + "-" + endDate.format(formatter);
    }

    /**
     * 获取状态显示文本
     */
    private String getStatusText(BdSettlementStatus status) {
        if (status == null) {
            return "";
        }
        return switch (status) {
            case PENDING -> "In Progress";
            case SUCCESS -> "Completed";
            case FAILED -> "Failed";
        };
    }
}
