package com.yd.csf.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yd.csf.service.model.EvaluateRank;
import com.yd.csf.service.dao.EvaluateRankMapper;
import com.yd.csf.service.service.IEvaluateRankService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 评定职级表 服务实现类
 * </p>
 *
 * @author zxm
 * @since 2026-04-20
 */
@Service
public class EvaluateRankServiceImpl extends ServiceImpl<EvaluateRankMapper, EvaluateRank> implements IEvaluateRankService {

    /**
     * 根据转介人业务ID列表统计每个转介人的评定记录数量
     *
     * @param brokerBizIdList 转介人业务ID列表
     * @return Map，key=brokerBizId，value=记录数量
     */
    @Override
    public Map<String, Long> countGroupByBrokerBizId(List<String> brokerBizIdList) {
        if (CollectionUtils.isEmpty(brokerBizIdList)) {
            return Collections.emptyMap();
        }

        QueryWrapper<EvaluateRank> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("broker_biz_id", "count(1) as count")
                .in("broker_biz_id", brokerBizIdList)
                .eq("is_deleted", 0)          // 只统计未删除的记录
                .groupBy("broker_biz_id");

        List<Map<String, Object>> list = this.listMaps(queryWrapper);
        return list.stream().collect(Collectors.toMap(
                map -> (String) map.get("broker_biz_id"),
                map -> (Long) map.get("count")
        ));
    }

    /**
     * 根据业务员ID列表，获取每个业务员最新一条评定记录（按创建时间倒序）
     * @param brokerBizIdList 业务员ID列表
     * @return Map<brokerBizId, EvaluateRank> 最新评定记录
     */
    @Override
    public Map<String, EvaluateRank> getLatestByBrokerBizIds(List<String> brokerBizIdList) {
        if (CollectionUtils.isEmpty(brokerBizIdList)) {
            return Collections.emptyMap();
        }
        // 使用子查询或窗口函数取每个业务员最新一条
        QueryWrapper<EvaluateRank> wrapper = new QueryWrapper<>();
        wrapper.in("broker_biz_id", brokerBizIdList)
                .eq("is_deleted", 0)
                .orderByDesc("create_time");  // 按创建时间倒序

        List<EvaluateRank> allList = this.list(wrapper);
        // 按 brokerBizId 分组，每组取第一条即为最新
        return allList.stream().collect(Collectors.toMap(
                EvaluateRank::getBrokerBizId,
                Function.identity(),
                (existing, replacement) -> existing  // 遇到重复 key 保留第一个（即最新的）
        ));
    }

}
