package com.fs.qw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.qw.domain.QwAssignRuleUser;
import com.fs.qw.mapper.QwAssignRuleUserMapper;
import com.fs.qw.service.IQwAssignRuleUserService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 微信分配规则用户关联表 服务实现类
 * </p>
 *
 * @author zhangqin
 * @since 2025-12-05
 */
@Service
public class QwAssignRuleUserServiceImpl extends ServiceImpl<QwAssignRuleUserMapper, QwAssignRuleUser> implements IQwAssignRuleUserService {

    @Override
    public QwAssignRuleUser getUserByAllocationRuleId(Long id, Integer assignType) {
        List<QwAssignRuleUser> list = list(new LambdaQueryWrapper<QwAssignRuleUser>()
                .eq(QwAssignRuleUser::getAssignId, id));
        int totalWeight = list.stream()
                .mapToInt(QwAssignRuleUser::getWeight)
                .sum();

        int random = ThreadLocalRandom.current().nextInt(totalWeight);

        AtomicInteger acc = new AtomicInteger();

        return list.stream()
                .filter(item -> {
                    acc.addAndGet(item.getWeight());
                    return acc.get() > random;
                })
                .findFirst()
                .orElse(null);
    }
}
