package org.jeecg.modules.okki.site.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.common.util.ThreadPoolUtil;
import org.jeecg.modules.okki.account.dto.OkkiUserInfoDto;
import org.jeecg.modules.okki.site.dto.FeiShuRecordSheetDto;
import org.jeecg.modules.okki.site.dto.XiaoManSiteDto;
import org.jeecg.modules.okki.site.entity.OkkiSite;
import org.jeecg.modules.okki.site.entity.OkkiSiteStatusChangeLog;
import org.jeecg.modules.okki.site.mapper.OkkiSiteMapper;
import org.jeecg.modules.okki.site.param.ChangeSiteStatusParam;
import org.jeecg.modules.okki.site.param.OkkiSiteParam;
import org.jeecg.modules.okki.site.service.*;
import org.jeecg.modules.okki.siteuser.entity.OkkiSiteUser;
import org.jeecg.modules.okki.siteuser.service.IOkkiSiteUserService;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 站点
 * @Author: jeecg-boot
 * @Date: 2024-04-29
 * @Version: V1.0
 */
@Slf4j
@Service
public class OkkiSiteServiceImpl extends ServiceImpl<OkkiSiteMapper, OkkiSite> implements IOkkiSiteService {

    @Value("${OKKI.BASE_URL}")
    private String URL;

    @Value("${OKKI.CLIENT_SECRET}")
    private String CLIENT_SECRET;

    @Resource
    private OkkiSiteMapper okkiSiteMapper;

    @Resource
    private IOkkiSiteStatusChangeLogService okkiSiteStatusChangeLogService;

    @Autowired
    private IFeiShuCommonService feiShuCommonService;

    @Autowired
    private IOkkiSiteUserService okkiSiteUserService;

    @Autowired
    private IFeiShuMsgService feiShuMsgService;

    @Autowired
    private IFeiShuGroupService feiShuGroupService;

    @Override
    public boolean updateBySiteId(OkkiSiteParam okkiSiteParam) {
        QueryWrapper<OkkiSite> okkiSiteQueryWrapper = new QueryWrapper<>();
        okkiSiteQueryWrapper.eq("site_id", okkiSiteParam.getSite_id());
        okkiSiteQueryWrapper.last("limit 1");
        OkkiSite okkiSite = okkiSiteMapper.selectOne(okkiSiteQueryWrapper);
        okkiSite.setCompanyName(okkiSiteParam.getCompany_name());
        okkiSite.setDomain(okkiSiteParam.getDomain());
        okkiSite.setTel(okkiSiteParam.getTel());
        okkiSite.setContact(okkiSiteParam.getContact());
        okkiSite.setEmail(okkiSiteParam.getEmail());
        okkiSite.setEnname(okkiSiteParam.getEnname());
        okkiSite.setTcName(okkiSiteParam.getTc_name());
        okkiSite.setTcPeriod(okkiSiteParam.getTc_period());
        okkiSite.setTcLanguage(okkiSiteParam.getTc_language());
        okkiSite.setRemark(okkiSiteParam.getRemark());
        int result = okkiSiteMapper.updateById(okkiSite);
        if (result == 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean changeStatus(OkkiSite okkiSite) {
        OkkiSite okkiSite1 = okkiSiteMapper.selectById(okkiSite.getId());
        // 请求okki平台接口
        Map<String, String> query = new TreeMap<>();
        query.put("sign_method", "hmac-md5");
        query.put("timestamp", String.valueOf(System.currentTimeMillis()));
        query.put("site_id", String.valueOf(okkiSite1.getSiteId()));
        query.put("method", "update_service_node");
        // 通过site_id获取当前站点数据status的值 +1

        okkiSite1.setStatus(okkiSite1.getStatus() + 1);
        Map<String, Object> postData = new HashMap<>();
        postData.put("status", okkiSite1.getStatus());
        try {
            String queryStr = HttpClientUtils.buildQueryString(query);
            String body = HttpClientUtils.toJsonString(postData);
            String signStr = queryStr + body;
            query.put("signature", HttpClientUtils.generateHmacMD5(signStr, CLIENT_SECRET));
            String okkiUrl = URL + "?" + HttpClientUtils.buildQueryString(query);
            log.info("url:" + okkiUrl + ",body:" + body);
            String res = HttpClientUtils.doPost(okkiUrl, body);
            log.info(res);
            // {"code":0,"msg":"success","now":"2024-05-06 15:34:54","data":[]}
            JSONObject jsonObject = JSONObject.parseObject(res);
            if (jsonObject.get("code").equals(0)) {
                int result = okkiSiteMapper.updateById(okkiSite1);
                if (result == 0) {
                    return false;
                } else {
                    OkkiSiteStatusChangeLog okkiSiteStatusChangeLog = new OkkiSiteStatusChangeLog();
                    okkiSiteStatusChangeLog.setOkkiSiteId(okkiSite.getSiteId());
                    okkiSiteStatusChangeLog.setOldStatus(okkiSite1.getStatus() - 1);
                    okkiSiteStatusChangeLog.setNewStatus(okkiSite1.getStatus());
                    okkiSiteStatusChangeLogService.save(okkiSiteStatusChangeLog);
                    return true;
                }
            } else {
                throw new RuntimeException(jsonObject.get("msg").toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean okkiChangeStatus(ChangeSiteStatusParam param) {
        OkkiSite okkiSite = new OkkiSite();
        QueryWrapper<OkkiSite> okkiSiteQueryWrapper = new QueryWrapper<>();
        okkiSiteQueryWrapper.eq("site_id", param.getSite_id());
        okkiSiteQueryWrapper.last("limit 1");
        OkkiSite okkiSite1 = okkiSiteMapper.selectOne(okkiSiteQueryWrapper);
        okkiSite.setId(okkiSite1.getId());
        okkiSite.setStatus(param.getStatus());
        int result = okkiSiteMapper.updateById(okkiSite);
        if (result == 0) {
            return false;
        } else {
            OkkiSiteStatusChangeLog okkiSiteStatusChangeLog = new OkkiSiteStatusChangeLog();
            okkiSiteStatusChangeLog.setOkkiSiteId(param.getSite_id());
            okkiSiteStatusChangeLog.setOldStatus(okkiSite1.getStatus());
            okkiSiteStatusChangeLog.setNewStatus(param.getStatus());
            okkiSiteStatusChangeLogService.save(okkiSiteStatusChangeLog);
            return true;
        }
    }

    @Override
    public boolean insertSite(OkkiSiteParam okkiSiteParam) {
        OkkiSite okkiSite1 = okkiSiteMapper.selectOne(new LambdaQueryWrapper<OkkiSite>().eq(OkkiSite::getSiteId, okkiSiteParam.getSite_id()));
        if (okkiSite1 != null) {
            throw new RuntimeException("site_id already exist");
        } else {
            OkkiSite okkiSite = new OkkiSite();
            okkiSite.setSiteId(okkiSiteParam.getSite_id());
            okkiSite.setCompanyName(okkiSiteParam.getCompany_name());
            okkiSite.setDomain(okkiSiteParam.getDomain());
            okkiSite.setTel(okkiSiteParam.getTel());
            okkiSite.setContact(okkiSiteParam.getContact());
            okkiSite.setEmail(okkiSiteParam.getEmail());
            okkiSite.setEnname(okkiSiteParam.getEnname());
            okkiSite.setTcName(okkiSiteParam.getTc_name());
            okkiSite.setTcPeriod(okkiSiteParam.getTc_period());
            okkiSite.setTcLanguage(okkiSiteParam.getTc_language());
            okkiSite.setRemark(okkiSiteParam.getRemark());
            boolean result = super.save(okkiSite);
            if (result) {
                ThreadPoolUtil.execute(() -> {
                    feiShuMsgService.sendSyncFeiShuSheetMsg(okkiSite.getCompanyName(), okkiSite.getSiteId(), okkiSite.getTcName(), "成功");
                });
            }
            return result;
        }
    }

    /**
     * 根据 key 获取用户列表并拼接昵称
     *
     * @param item
     * @param mergedList
     * @param key
     */
    public void setApiOkkiSiteUserStr(OkkiSite item, Map<String, Object> mergedList, String key) {
//        String init = "{\"1\":[],\"2\":[],\"3\":[],\"4\":[],\"5\":[],\"6\":[],\"7\":[],\"8\":[],\"9\":[],\"10\":[],\"11\":[],\"12\":[]}";
//        mergedList = FastJsonUtil.parseObject(init,Map.class);
        Object object = mergedList.get(key);
        if (object != null) {
//            log.info("serviceManageUsers (key={}): {}", key, FastJsonUtil.toJSONString(object));

            List<OkkiUserInfoDto> userInfoList = new ArrayList<>();
            JSONArray jsonArray = JSONArray.parseArray(object.toString());

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                OkkiUserInfoDto userInfo = jsonObject.toJavaObject(OkkiUserInfoDto.class);
                userInfoList.add(userInfo);
            }

            // 拼接昵称
            String nickNames = userInfoList.stream()
                    .map(OkkiUserInfoDto::getNickname)
                    .collect(Collectors.joining(","));

            // 拼接userId
            List<Integer> userIds = userInfoList.stream()
                    .map(OkkiUserInfoDto::getUserId)
                    .collect(Collectors.toList());

            //默认人员
            Map<String, List<Integer>> defaultUserIds = new HashMap<>();
            defaultUserIds.put("1", Arrays.asList(1294, 1297));
            defaultUserIds.put("2", Collections.singletonList(1230));
            defaultUserIds.put("7", Arrays.asList(1293, 1412, 1511, 1541));
            defaultUserIds.put("9", Collections.singletonList(1415));
            defaultUserIds.put("10", Collections.singletonList(1543));
            defaultUserIds.put("4", Collections.singletonList(1290));
            defaultUserIds.put("8", Collections.singletonList(1593));
            defaultUserIds.put("12", Arrays.asList(1364, 1409));
            if (userIds.isEmpty() && defaultUserIds.containsKey(key)) {
                userIds.addAll(defaultUserIds.get(key));
            }

            // 根据 key 设置不同的字段
            switch (key) {
                case "1":
                    item.setServiceManageUserStr(nickNames);
                    item.setServiceManageUser(userIds);
                    break;
                case "5":
                    item.setDataUserStr(nickNames);
                    item.setDataUser(userIds);
                    break;
                case "2":
                    item.setKefuUserStr(nickNames);
                    item.setKefuUser(userIds);
                    break;
                case "7":
                    item.setSeoUserStr(nickNames);
                    item.setSeoUser(userIds);
                    break;
                case "9":
                    item.setSemManageUserStr(nickNames);
                    item.setSemManageUser(userIds);
                    break;
                case "10":
                    item.setSemUserStr(nickNames);
                    item.setSemUser(userIds);
                    break;
                case "4":
                    item.setUiUserStr(nickNames);
                    item.setUiUser(userIds);
                    break;
                case "11":
                    item.setWebsiteUserStr(nickNames);
                    item.setWebsiteUser(userIds);
                    break;
                case "8":
                    item.setSocialUserStr(nickNames);
                    item.setSocialUser(userIds);
                    break;
                case "12":
                    item.setRdUserStr(nickNames);
                    item.setRdUser(userIds);
                    break;
            }
        }
    }

    public void setOkkiSiteUserStr(OkkiSite item, Map<String, List<OkkiSiteUser>> okkiSiteUsers, String key) {
        log.info("okkiSiteUsers:{}", FastJsonUtil.toJSONString(okkiSiteUsers));
        if (!okkiSiteUsers.containsKey(key)) {
            return;
        }
        List<OkkiSiteUser> okkiSiteUsers1 = FastJsonUtil.parseList(FastJsonUtil.toJSONString(okkiSiteUsers.get(key)), OkkiSiteUser.class);
        if (!okkiSiteUsers1.isEmpty()) {
//            log.info("serviceManageUsers (key={}): {}", key, FastJsonUtil.toJSONString(okkiSiteUsers.get(key)));
            List<OkkiUserInfoDto> userInfoList = new ArrayList<>();
            for (int i = 0; i < okkiSiteUsers1.size(); i++) {
                OkkiSiteUser okkiSiteUser = okkiSiteUsers1.get(i);

                OkkiUserInfoDto userInfoDto = new OkkiUserInfoDto();
                userInfoDto.setUserId(okkiSiteUser.getUserId());
                userInfoDto.setNickname(okkiSiteUser.getNickname());
                userInfoDto.setAccount(okkiSiteUser.getAccount());
                userInfoList.add(userInfoDto);
            }

            // 拼接昵称
            String nickNames = userInfoList.stream()
                    .map(OkkiUserInfoDto::getNickname)
                    .collect(Collectors.joining(","));

            // 拼接userId
            List<Integer> userIds = userInfoList.stream()
                    .map(OkkiUserInfoDto::getUserId)
                    .collect(Collectors.toList());

            // 根据 key 设置不同的字段
            switch (key) {
                case "serviceManageUser":
                    item.setServiceManageUserStr(nickNames);
                    item.setServiceManageUser(userIds);
                    break;
                case "dataUser":
                    item.setDataUserStr(nickNames);
                    item.setDataUser(userIds);
                    break;
                case "kefuUser":
                    item.setKefuUserStr(nickNames);
                    item.setKefuUser(userIds);
                    break;
                case "seoUser":
                    item.setSeoUserStr(nickNames);
                    item.setSeoUser(userIds);
                    break;
                case "semManageUser":
                    item.setSemManageUserStr(nickNames);
                    item.setSemManageUser(userIds);
                    break;
                case "semUser":
                    item.setSemUserStr(nickNames);
                    item.setSemUser(userIds);
                    break;
                case "uiUser":
                    item.setUiUserStr(nickNames);
                    item.setUiUser(userIds);
                    break;
                case "websiteUser":
                    item.setWebsiteUserStr(nickNames);
                    item.setWebsiteUser(userIds);
                    break;
                case "socialUser":
                    item.setSocialUserStr(nickNames);
                    item.setSocialUser(userIds);
                    break;
                case "rdUser":
                    item.setRdUserStr(nickNames);
                    item.setRdUser(userIds);
                    break;
            }
        }
    }

    /**
     * 保存或更新飞书客户信息
     *
     * @param siteId
     */
    @Override
    public void saveOrUpdateFeishuSheetFields(String siteId) {
        // 获取飞书的团队信息
        List<String> targetGroups = new ArrayList<>();
        Map<String, List<JSONObject>> teamSheetMap = feiShuCommonService.getFeiShuTeamSheet(targetGroups);
//        log.info("teamSheetMap: {}", FastJsonUtil.toJSONString(teamSheetMap));

        // 获取站点用户信息并按类型分组
        List<OkkiSiteUser> okkiSiteUsers = okkiSiteUserService.getSiteUserInfoBySiteId(Integer.valueOf(siteId));
        Map<String, List<OkkiSiteUser>> okkiSiteUserMap = okkiSiteUsers.stream()
                .collect(Collectors.groupingBy(OkkiSiteUser::getType));
//        log.info("okkiSiteUserMap: {}", FastJsonUtil.toJSONString(okkiSiteUserMap));

        // 获取站点信息
        List<Map<String, Object>> customerInfo = feiShuCommonService.getCustomerInfoKfSheetBySiteId(siteId);
//        log.info("customerInfo: {}", FastJsonUtil.toJSONString(customerInfo));

        // 判断信息
        if (!customerInfo.isEmpty()) {
            handleCustomerInfoUpdate(customerInfo, siteId, okkiSiteUserMap, teamSheetMap);
        } else {
            handleSiteSync(siteId, okkiSiteUserMap, teamSheetMap);
        }
    }

    /**
     * 处理客服团队信息的更新逻辑
     */
    private void handleCustomerInfoUpdate(List<Map<String, Object>> customerInfo,
                                          String siteId, Map<String,
            List<OkkiSiteUser>> okkiSiteUserMap, Map<String, List<JSONObject>> teamSheetMap) {
        if (customerInfo.size() == 1) {
            // 初始化飞书更新 DTO
            String recordId = (String) customerInfo.get(0).get("record_id");
            FeiShuRecordSheetDto recordSheetDto = new FeiShuRecordSheetDto();
            recordSheetDto.setRecordId(recordId);
            recordSheetDto.setOkTablePage("Y");
            recordSheetDto.setOkTableName("客服团队");

            // 获取更新字段映射
            Map<String, Object> updateGroupFieldMap = getStringObjectMap(siteId, okkiSiteUserMap, teamSheetMap);
//            log.info("updateGroupFieldMap: {}", updateGroupFieldMap);

            // 发送更新请求到飞书
            feiShuCommonService.sendUpdateRequestFeiShuSheet(updateGroupFieldMap, recordSheetDto);
        } else {
            log.warn("Multiple customer records found for siteId: {}", siteId);
        }
    }

    /**
     * 处理站点信息同步逻辑
     */
    private void handleSiteSync(String siteId,
                                Map<String, List<OkkiSiteUser>> okkiSiteUserMap,
                                Map<String, List<JSONObject>> teamSheetMap) {
        // 查询站点信息
        List<OkkiSite> okkiSites = list(new QueryWrapper<OkkiSite>().eq("site_id", siteId));
        if (okkiSites.isEmpty()) {
            log.warn("No site found for siteId: {}", siteId);
            return;
        }
        OkkiSite okkiSite = okkiSites.get(0);

        // 获取更新字段映射
        Map<String, Object> updateGroupFieldMap = getStringObjectMap(siteId, okkiSiteUserMap, teamSheetMap);

        // 获取服务管理员并过滤特定昵称
        List<OkkiSiteUser> serviceManageUsers = okkiSiteUserMap.getOrDefault("serviceManageUser", Collections.emptyList());
        OkkiSiteUser feishuGroupOwner = serviceManageUsers.stream()
                .filter(user -> "孙跃".equals(user.getNickname()))
                .findFirst()
                .orElse(null);

        // 获取群主ID
        String ownerId = getFirstPersonnelId(feishuGroupOwner, teamSheetMap);
        log.info("ownerId:{}", ownerId);

        // 获取网站用户的OpenIds和对应组名
        List<String> websiteOpenIds = getPersonnelIds(okkiSiteUserMap.get("websiteUser"), teamSheetMap);
        String groupName = getGroupName(websiteOpenIds, teamSheetMap);

        // 获取资料用户的OpenIds
        List<String> dataUserOpenIds = getPersonnelIds(okkiSiteUserMap.get("dataUser"), teamSheetMap);

        // 构建更新字段
        updateGroupFieldMap.put("组建站专员", buildIdMapList(websiteOpenIds));
        updateGroupFieldMap.put("组资料员", buildIdMapList(dataUserOpenIds));
        updateGroupFieldMap.put("建站小组", groupName);

        log.info("updateGroupFieldMap: {}", FastJsonUtil.toJSONString(updateGroupFieldMap));

        // 同步网站信息到飞书
        String recordId = feiShuCommonService.syncWebsiteToFeiShuSheet(okkiSite, updateGroupFieldMap);

        // 创建飞书群
        feiShuGroupService.createFeiShuGroupOms(updateGroupFieldMap, okkiSite.getCompanyName(), siteId,
                okkiSite.getTcName(), recordId, ownerId);
    }

    private String getGroupName(List<String> omsIds, Map<String, List<JSONObject>> teamSheetMap) {
        if (omsIds.isEmpty()) {
            return "";
        }
        String omsId = omsIds.get(0);
        List<JSONObject> teamSheetUserInfos = teamSheetMap.get(omsId);
        if (teamSheetUserInfos != null) {
            for (JSONObject jsonObject : teamSheetUserInfos) {
                String groupName = jsonObject.getString("组名");
                if (StringUtils.isNotBlank(groupName)) {
                    return groupName;
                }
            }
        }
        return "";
    }

    private List<Map<String, Object>> buildIdMapList(List<String> ids) {
        return ids.stream()
                .filter(StringUtils::isNotBlank)
                .map(id -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", id);
                    return map;
                })
                .collect(Collectors.toList());
    }

    private String getFirstPersonnelId(OkkiSiteUser user, Map<String, List<JSONObject>> teamSheetMap) {
        if (user == null) {
            return "";
        }
        List<JSONObject> teamSheetUserInfos = teamSheetMap.get(user.getId());
        if (teamSheetUserInfos == null || teamSheetUserInfos.isEmpty()) {
            return "";
        }
        return teamSheetUserInfos.stream()
                .map(jsonObject -> jsonObject.getJSONArray("人员"))
                .filter(Objects::nonNull)
                .flatMap(personnelArray -> personnelArray.stream().map(obj -> ((JSONObject) obj).getString("id")))
                .findFirst()
                .orElse("");
    }

    private List<String> getPersonnelIds(List<OkkiSiteUser> users, Map<String, List<JSONObject>> teamSheetMap) {
        if (users == null || users.isEmpty()) {
            return Collections.emptyList();
        }
        return users.stream()
                .map(user -> teamSheetMap.getOrDefault(user.getId(), Collections.emptyList()))
                .flatMap(Collection::stream)
                .map(jsonObject -> jsonObject.getJSONArray("人员"))
                .filter(Objects::nonNull)
                .flatMap(personnelArray -> personnelArray.stream().map(obj -> ((JSONObject) obj).getString("id")))
                .distinct()
                .collect(Collectors.toList());
    }

    /**
     * 获取需要更新的用户类型与对应的飞书字段
     *
     * @param siteId
     * @param okkiSiteUserMap
     * @param teamSheetMap
     * @return
     */
    private Map<String, Object> getStringObjectMap(String siteId, Map<String, List<OkkiSiteUser>> okkiSiteUserMap, Map<String, List<JSONObject>> teamSheetMap) {
        Map<String, String> userTypeToFieldMap = new HashMap<>();
        userTypeToFieldMap.put("serviceManageUser", "OMS-服务主管");
        userTypeToFieldMap.put("dataUser", "OMS-资料专员");
        userTypeToFieldMap.put("kefuUser", "OMS-建站顾问");
        userTypeToFieldMap.put("seoUser", "OMS-SEO专员");
        userTypeToFieldMap.put("semManageUser", "OMS-SEM主管");
        userTypeToFieldMap.put("semUser", "OMS-SEM专员");
        userTypeToFieldMap.put("uiUser", "OMS-设计师");
        userTypeToFieldMap.put("websiteUser", "OMS-建站专员");
        userTypeToFieldMap.put("socialUser", "OMS-社媒专员");
        userTypeToFieldMap.put("rdUser", "OMS-技术");

        Map<String, Object> updateGroupFieldMap = new HashMap<>();

        // 按用户类型处理用户信息并提取 OpenID
        userTypeToFieldMap.forEach((userType, fieldName) -> {
            List<OkkiSiteUser> users = okkiSiteUserMap.getOrDefault(userType, Collections.emptyList());
            if (users.isEmpty()) {
                log.warn("No users found for type: {} and siteId: {}", userType, siteId);
                return;
            }

            // 按 OMS ID 分组
            Map<String, List<OkkiSiteUser>> usersOmsIdMap = users.stream()
                    .collect(Collectors.groupingBy(OkkiSiteUser::getId));
//            log.info("{}OmsIdMap: {}", userType, FastJsonUtil.toJSONString(usersOmsIdMap));

            // 提取并更新 OpenID
            List<Map<String, Object>> openIds = extractAndUpdateOpenIds(teamSheetMap, usersOmsIdMap);
//            log.info("Updated OpenIDs for {}: {}", userType, FastJsonUtil.toJSONString(openIds));

            // 添加到更新字段映射
            updateGroupFieldMap.put(fieldName, openIds);
        });
        return updateGroupFieldMap;
    }

    /**
     * 提取并更新用户的 OpenID
     *
     * @param teamSheetMap  飞书团队信息
     * @param usersOmsIdMap 用户 OMS ID 分组
     * @return 更新后的 OpenID 列表
     */
    private List<Map<String, Object>> extractAndUpdateOpenIds(Map<String, List<JSONObject>> teamSheetMap,
                                                              Map<String, List<OkkiSiteUser>> usersOmsIdMap) {
        List<Map<String, Object>> openIds = new ArrayList<>();
        for (Map.Entry<String, List<JSONObject>> teamEntry : teamSheetMap.entrySet()) {
            String omsId = teamEntry.getKey();
            if (!usersOmsIdMap.containsKey(omsId)) {
                continue;
            }

            String openId = extractOpenIdFromTeamDetails(teamEntry.getValue());
            if (StringUtils.isNotBlank(openId)) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", openId);
                openIds.add(map);
            }
        }
        return openIds;
    }

    /**
     * 从团队详情中提取 OpenID
     *
     * @param teamDetails 团队详情列表
     * @return 提取的 OpenID
     */
    private String extractOpenIdFromTeamDetails(List<JSONObject> teamDetails) {
        for (JSONObject group : teamDetails) {
            JSONArray personnelArray = group.getJSONArray("人员");
            if (personnelArray != null) {
                for (int i = 0; i < personnelArray.size(); i++) {
                    JSONObject person = personnelArray.getJSONObject(i);
                    String id = person.getString("id");
                    if (StringUtils.isNotBlank(id)) {
                        return id;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 处理站点信息
     */
    @Override
    public boolean dealSiteInfoByJsonData(String jsonPath) {
        boolean result = false;

        // 读取 JSON 数据
        String jsonDataStr = FileUtil.readString(jsonPath, "UTF-8");

        // 解析 JSON 数据并清理 siteId
        List<XiaoManSiteDto> xiaoManSiteDtoOrigins = FastJsonUtil.parseList(jsonDataStr, XiaoManSiteDto.class);
        xiaoManSiteDtoOrigins.forEach(c -> {
            String siteId = c.getSiteId();
            if (siteId.contains("网站ID: ")) {
                c.setSiteId(siteId.replace("网站ID: ", ""));
            }
        });

        Map<String, XiaoManSiteDto> xiaoManSiteDtoMap = new HashMap<>();
        xiaoManSiteDtoOrigins.forEach(c -> {
            xiaoManSiteDtoMap.put(c.getSiteId(), c);
        });
        log.info("xiaoManSiteDtoMap: {}", FastJsonUtil.toJSONString(xiaoManSiteDtoMap));

        // 获取所有客户信息
        List<Map<String, Object>> allCustomerInfos = feiShuCommonService.getCustomerInfoKfSheet();
        if (allCustomerInfos.isEmpty()) {
            return result;
        }

        // 遍历客户信息并处理更新
        for (Map<String, Object> item : allCustomerInfos) {
            String siteIdStr = String.valueOf(item.get("网站ID"));
            String[] parts = siteIdStr.split("\\.");
            String siteId = parts[0];
//            log.info("siteId:{}", siteId);
            if (xiaoManSiteDtoMap.containsKey(siteId)) {
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        dealUpdateCustomerInfo(item, xiaoManSiteDtoMap.get(siteId));
                    }
                });
            }
        }

        // 发送消息
//        feiShuMsgService.syncXiaoManDashboardData();
        return true;
    }

    /**
     * 处理客服团队信息的更新逻辑
     */
    private void dealUpdateCustomerInfo(Map<String, Object> customerInfo, XiaoManSiteDto xiaoManSiteDto) {
//        log.info("customerInfo:{},xiaoManSiteDto:{}", FastJsonUtil.toJSONString(customerInfo), FastJsonUtil.toJSONString(xiaoManSiteDto));
        // 初始化飞书更新 DTO
        String recordId = (String) customerInfo.get("record_id");
        FeiShuRecordSheetDto recordSheetDto = new FeiShuRecordSheetDto();
        recordSheetDto.setRecordId(recordId);
        recordSheetDto.setOkTablePage("Y");
        recordSheetDto.setOkTableName("客服团队");

        // 获取更新字段映射
        Map<String, Object> updateGroupFieldMap = getOkkiSiteInfoMap(xiaoManSiteDto);
        log.info("updateGroupFieldMap: {}", updateGroupFieldMap);

        // 发送更新请求到飞书
        feiShuCommonService.sendUpdateRequestFeiShuSheet(updateGroupFieldMap, recordSheetDto);
    }

    /**
     * 获取需要更新的用户类型与对应的飞书字段
     *
     * @param xiaoManSiteDto
     * @return
     */
    private Map<String, Object> getOkkiSiteInfoMap(XiaoManSiteDto xiaoManSiteDto) {
        Map<String, Object> updateGroupFieldMap = new HashMap<>();
        updateGroupFieldMap.put("小满-服务阶段", xiaoManSiteDto.getServicePhase());
        updateGroupFieldMap.put("小满-阶段状态", xiaoManSiteDto.getServiceStatus());
        updateGroupFieldMap.put("小满-阶段停留时长", xiaoManSiteDto.getServiceHour());
        updateGroupFieldMap.put("小满-阶段节点", xiaoManSiteDto.getPhaseName());
        updateGroupFieldMap.put("小满-阶段节点状态", xiaoManSiteDto.getPhaseStatus());
        updateGroupFieldMap.put("小满-节点停留时长", xiaoManSiteDto.getPhaseHour());
        return updateGroupFieldMap;
    }
}
