package com.cmeeting.util;

import com.cmeeting.mapper.primary.WeComUserMapper;
import com.cmeeting.pojo.WeComUser;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import java.util.*;
import java.util.stream.Collectors;

public class WeComUserService {
    
    // 假设这是你的MyBatis Mapper
    private final WeComUserMapper weComUserMapper;
    
    public WeComUserService(WeComUserMapper weComUserMapper) {
        this.weComUserMapper = weComUserMapper;
    }

    /**
     * 将企业微信返回的JSON转换为WeComUser列表
     */
    private List<WeComUser> convertJsonToWeComUsers(JsonObject json) {
        List<WeComUser> users = new ArrayList<>();
        
        if (json.has("userlist") && json.get("userlist").isJsonArray()) {
            JsonArray userList = json.getAsJsonArray("userlist");
            Gson gson = new Gson();
            
            for (JsonElement element : userList) {
                JsonObject userJson = element.getAsJsonObject();
                WeComUser user = new WeComUser();
                
                // 根据企业微信API实际返回字段调整
                user.setUserId(userJson.get("userid").getAsString());
                user.setUserName(userJson.get("name").getAsString());
                
                // 其他字段设置...
                users.add(user);
            }
        }
        
        return users;
    }

    /**
     * 标记重名用户
     */
    private void markDuplicateNames(List<WeComUser> users) {
        // 按姓名分组，统计每个名字出现的次数
        Map<String, Long> nameCountMap = users.stream()
            .collect(Collectors.groupingBy(WeComUser::getUserName, Collectors.counting()));
        
        // 设置是否重名标志
        users.forEach(user -> {
            if (nameCountMap.get(user.getUserName()) > 1) {
                user.setIsrepeatName("1"); // 重名
            } else {
                user.setIsrepeatName("0"); // 不重名
            }
        });
    }
}