package bank;

import com.red.circle.OtherServiceApplication;
import com.red.circle.other.app.inner.service.user.user.UserBaseInfoClientService;
import com.red.circle.other.inner.model.cmd.count.SysOriginUserQryCmd;
import com.red.circle.other.inner.model.dto.user.SysUserBaseInfoDTO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
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.test.context.junit4.SpringRunner;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SpringBootTest(classes = OtherServiceApplication.class)
@RunWith(SpringRunner.class)
public class UserBankQueryTest {


    @Autowired
    private UserBaseInfoClientService userBaseInfoClientService;
    @Autowired
    private MongoTemplate mongoTemplate;


    @Test
    public void test(){
        // 1. 从 MySQL 查询 BD 国家的用户
        SysOriginUserQryCmd qryCmd = new SysOriginUserQryCmd();
        qryCmd.setCountryCode("BD");
        List<SysUserBaseInfoDTO> userAll = userBaseInfoClientService.getUserAll(qryCmd);
        
        System.out.println("查询到 BD 国家用户总数: " + userAll.size());
        
        if (userAll.isEmpty()) {
            System.out.println("未找到任何 BD 国家的用户");
            return;
        }
        
        // 2. 提取用户 ID 列表
        List<Long> userIds = userAll.stream()
                .map(SysUserBaseInfoDTO::getId)
                .collect(Collectors.toList());
        
        // 3. 从 MongoDB 查询银行账户数据
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").in(userIds));
        
        List<Map> bankBalances = mongoTemplate.find(query, Map.class, "user_bank_balance");
        
        System.out.println("查询到银行账户数据总数: " + bankBalances.size());
        System.out.println();
        
        if (bankBalances.isEmpty()) {
            System.out.println("未找到任何银行账户数据");
            return;
        }
        
        // 4. 按余额倒序排序并打印
        bankBalances.stream()
                .sorted(Comparator.comparing(
                        (Map map) -> getLongValue(map.get("balance")),
                        Comparator.reverseOrder()
                ))
                .forEach(bankBalance -> {
                    Long userId = getLongValue(bankBalance.get("_id"));
                    Long balance = getLongValue(bankBalance.get("balance"));
                    BigDecimal balanceDecimal = new BigDecimal(balance)
                            .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                    
                    System.out.printf("用户ID: %-15s | 余额: %s%n", userId, balanceDecimal);
                });
        
        // 5. 统计汇总数据
        long totalBalance = 0L;
        int countAbove1000 = 0;
        int countAbove500 = 0;
        int countAbove100 = 0;
        int countBelow100 = 0;
        
        for (Map bankBalance : bankBalances) {
            Long balance = getLongValue(bankBalance.get("balance"));
            totalBalance += balance;
            
            BigDecimal balanceDecimal = new BigDecimal(balance)
                    .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
            
            if (balanceDecimal.compareTo(new BigDecimal("1000")) >= 0) {
                countAbove1000++;
            } else if (balanceDecimal.compareTo(new BigDecimal("500")) >= 0) {
                countAbove500++;
            } else if (balanceDecimal.compareTo(new BigDecimal("100")) >= 0) {
                countAbove100++;
            } else if (balanceDecimal.compareTo(new BigDecimal("0")) > 0) {
                countBelow100++;
            }
        }
        
        BigDecimal totalBalanceDecimal = new BigDecimal(totalBalance)
                .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
        
        // 6. 打印汇总
        System.out.println();
        System.out.println("========================================");
        System.out.println("数据汇总:");
        System.out.println("========================================");
        System.out.println("总数量:           " + bankBalances.size() + " 人");
        System.out.println("总余额:           " + totalBalanceDecimal);
        System.out.println("----------------------------------------");
        System.out.println("1000以上用户数:   " + countAbove1000 + " 人");
        System.out.println("500以上用户数:    " + countAbove500 + " 人");
        System.out.println("100以上用户数:    " + countAbove100 + " 人");
        System.out.println("100以下用户数:    " + countBelow100 + " 人");
        System.out.println("========================================");
    }
    
    /**
     * 获取 Long 值，处理 null 和类型转换
     */
    private Long getLongValue(Object value) {
        if (value == null) {
            return 0L;
        }
        if (value instanceof Long) {
            return (Long) value;
        }
        if (value instanceof Integer) {
            return ((Integer) value).longValue();
        }
        if (value instanceof String) {
            try {
                return Long.parseLong((String) value);
            } catch (NumberFormatException e) {
                return 0L;
            }
        }
        return 0L;
    }

}
