package com.ssyf.module.robot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssyf.common.core.util.EntityUtil;
import com.ssyf.common.security.domain.ClientInfo;
import com.ssyf.common.security.helper.ClientContextHelper;
import com.ssyf.common.web.apicode.ApiCodeUser;
import com.ssyf.common.web.error.ServiceRuntimeException;
import com.ssyf.module.auth.emuns.UserTypeEnum;
import com.ssyf.module.robot.domain.entity.*;
import com.ssyf.module.robot.domain.query.RRobotAccountQuery;
import com.ssyf.module.robot.domain.query.RRobotGroupQuery;
import com.ssyf.module.robot.service.*;
import com.ssyf.module.robot.mapper.RRobotAccountMapper;
import com.ssyf.plugs.cache.service.impl.RedisCacheService;
import com.ssyf.plugs.mysql.helper.MybatisPlusHelper;
import com.ssyf.third.bmiss.model.ApiResponse;
import com.ssyf.third.bmiss.model.LoginResponse;
import com.ssyf.third.bmiss.services.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ELSA
 * @description 针对表【r_robot_account(机器人账号表)】的数据库操作Service实现
 * @createDate 2025-12-12 10:19:24
 */
@Slf4j
@Service
public class RRobotAccountServiceImpl extends ServiceImpl<RRobotAccountMapper, RRobotAccount>
        implements RRobotAccountService {

    @Lazy
    @Autowired
    private RRobotGroupService robotGroupService;

    @Lazy
    @Autowired
    private RConfigRelationService configRelationService;

    @Autowired
    private RedisCacheService cacheService;

    @Lazy
    @Autowired
    private UserRobotRelationService userRobotRelationService;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private RedissonClient redissonClient;

    @Lazy
    @Autowired
    private RRobotRunningInfoService rbotoRunningInfoService;


    /**
     * Redis缓存键前缀
     */
    private static final String CACHE_KEY_PREFIX = "robot:account:";

    /**
     * 缓存过期时间（秒）
     */
    private static final long CACHE_EXPIRE_SECONDS = 3600;

    @Override
    public RRobotAccount addOne(RRobotAccountQuery query) {
        if (StrUtil.isBlank(query.getEmail())) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "账号不能为空");
        }
        if (this.count(createBaseWrapper(null).eq(RRobotAccount::getEmail, query.getEmail())) > 0) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "账号已存在");
        }

        // 如果存在分组，检查分组是否存在
        if (query.getGroupId() != null) {
            RRobotGroup group = robotGroupService.getOneByUid(query.getGroupId().toString());
            if (group == null) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "指定的分组不存在");
            }
            // 设置分组名称
            query.setGroupName(group.getGroupName());
        }

        ClientInfo clientInfo = ClientContextHelper.getClientInfo();
        RRobotAccount RRobotAccount = BeanUtil.toBean(query, RRobotAccount.class);
        RRobotAccount.setUuid(IdUtil.simpleUUID());
        RRobotAccount.setCreatorUuid(clientInfo.getId().toString()).setCreator(clientInfo.getNickname())
                .setCreateTime(LocalDateTime.now());
        this.save(RRobotAccount);

        // 清除缓存，确保下次查询时获取最新数据
        String cacheKey = CACHE_KEY_PREFIX + RRobotAccount.getUuid();
        cacheService.remove(cacheKey);

        return RRobotAccount;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByUid(String uid) {
        RRobotAccount oldAccount = checkedExistAndGet(uid);

        //todo 关联数据查询

        // 逻辑删除：设置deleted字段为1
        RRobotAccount update = new RRobotAccount();
        update.setDeleted(1);
        LambdaQueryWrapper<RRobotAccount> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RRobotAccount::getUuid, uid);
        this.update(update, wrapper);

        // 清除缓存
        String cacheKey = CACHE_KEY_PREFIX + uid;
        cacheService.remove(cacheKey);
    }

    @Override
    public void removeBatchByUids(List<String> uids) {
        //todo 关联数据查询
        // 逻辑删除：设置deleted字段为1
        RRobotAccount update = new RRobotAccount();
        update.setDeleted(1);
        LambdaQueryWrapper<RRobotAccount> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RRobotAccount::getUuid, uids);
        this.update(update, wrapper);

        // 清除缓存
        for (String uid : uids) {
            String cacheKey = CACHE_KEY_PREFIX + uid;
            cacheService.remove(cacheKey);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateByUid(String uid, RRobotAccountQuery query) {
        RRobotAccount oldAccount = this.checkedExistAndGet(uid);
        //昵称、头像、简介更新，同步第三方
        if(query.getNickname() != null || query.getHeaderIconUrl() != null || query.getNotes() != null){
            boolean updateThird = false;
            String nickname = null;
            if(!Objects.equals(oldAccount.getNickname(), query.getNickname())){
                nickname = query.getNickname();
                updateThird = true;
            }
            String headerIconUrl = null;
            if(!Objects.equals(oldAccount.getHeaderIconUrl(), query.getHeaderIconUrl())){
                headerIconUrl = query.getHeaderIconUrl();
                updateThird = true;
            }
            String notes = null;
            if(!Objects.equals(oldAccount.getNotes(), query.getNotes())){
                notes = query.getNotes();
                updateThird = true;
            }
            if(updateThird){
                //登录
                ApiResponse<LoginResponse> response = businessService.loginByEmail(oldAccount.getEmail(), oldAccount.getPassword());
                if(!response.isSuccess()){
                    ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "更新失败，三方服务调用异常");
                }
                ApiResponse response1 = businessService.updateUser(headerIconUrl, nickname, notes, response.getData().getToken());
                if(!response1.isSuccess()){
                    ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "更新失败，三方服务调用异常");
                }
            }
        }

        //不能更新uid，和id
        query.setUuid(null);
        RRobotAccount update = BeanUtil.toBean(query, RRobotAccount.class);
        LambdaQueryWrapper<RRobotAccount> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RRobotAccount::getUuid, uid);
        this.update(update, wrapper);

        // 如果分组发生变化，同步更新分组名称
        if (query.getGroupId() != null && !query.getGroupId().equals(oldAccount.getGroupId())) {
            RRobotGroup group = robotGroupService.getOneByUid(query.getGroupId().toString());
            if (group != null) {
                // 更新机器人账号表中的分组名称
                RRobotAccount accountUpdate = new RRobotAccount();
                accountUpdate.setGroupName(group.getGroupName());
                LambdaQueryWrapper<RRobotAccount> accountWrapper = new LambdaQueryWrapper<>();
                accountWrapper.eq(RRobotAccount::getUuid, uid);
                this.update(accountUpdate, accountWrapper);

                // 更新配置关联表中的分组名称
                RConfigRelation configRelationUpdate = new RConfigRelation();
                configRelationUpdate.setGroupName(group.getGroupName());
                LambdaQueryWrapper<RConfigRelation> configRelationWrapper = new LambdaQueryWrapper<>();
                configRelationWrapper.eq(RConfigRelation::getRobotUuid, uid);
                configRelationService.update(configRelationUpdate, configRelationWrapper);
            }
        }

        // 清除缓存，确保下次查询时获取最新数据
        String cacheKey = CACHE_KEY_PREFIX + uid;
        cacheService.remove(cacheKey);
    }

    @Override
    public RRobotAccount getOneByUid(String uid) {
        String cacheKey = CACHE_KEY_PREFIX + uid;

        // 先从缓存中获取
        RRobotAccount cachedAccount = (RRobotAccount) cacheService.get(cacheKey);
        if (cachedAccount != null) {
            return cachedAccount;
        }

        // 缓存中没有，从数据库查询
        RRobotAccount account = this.getOne(createBaseWrapper(null).eq(RRobotAccount::getUuid, uid));

        // 如果查询到数据，放入缓存
        if (account != null) {
            cacheService.put(CACHE_EXPIRE_SECONDS, cacheKey, account);
        }

        return account;
    }

    @Override
    public PageInfo<RRobotAccount> getPage(RRobotAccountQuery query) {
        if (ClientContextHelper.isLogin()) {
            ClientInfo clientInfo = ClientContextHelper.getClientInfo();
            if (UserTypeEnum.Yunying.getCode().equals(clientInfo.getType())) {
                List<Long> ids = userRobotRelationService.getRobotIdsByUserId(clientInfo.getIntId());
                query.setIds(ids);
            }
        }
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return PageInfo.of(this.list(createBaseWrapper(query)));
    }

    @Override
    public List<RRobotAccount> getList(RRobotAccountQuery query) {
        if (ClientContextHelper.isLogin()) {
            ClientInfo clientInfo = ClientContextHelper.getClientInfo();
            if (UserTypeEnum.Yunying.getCode().equals(clientInfo.getType())) {
                List<Long> ids = userRobotRelationService.getRobotIdsByUserId(clientInfo.getIntId());
                query.setIds(ids);
            }
        }
        return this.list(createBaseWrapper(query));
    }

    @Override
    public RRobotAccount checkedExistAndGet(String uid) {
        RRobotAccount old = this.getOne(createBaseWrapper(null).eq(RRobotAccount::getUuid, uid));
        if (old == null) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "数据不存在");
        }
        return old;
    }

    @Override
    public Integer countBy(RRobotAccountQuery query) {
        return this.count(createBaseWrapper(query));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized void addBatchByImport(List<RRobotAccount> rRobotAccountList) {
        //分组
        List<RRobotGroup> groupList = this.robotGroupService.getList(new RRobotGroupQuery().setStatus(1));
        Map<String,RRobotGroup> nameToGroupMap = groupList.stream().collect(Collectors.toMap(RRobotGroup::getGroupName, RRobotGroup -> RRobotGroup));

        //数据预处理
        for (int i = 0; i < rRobotAccountList.size(); i++) {
            RRobotAccount RRobotAccount = rRobotAccountList.get(i);
            //前置检查
            if (StrUtil.isBlank(RRobotAccount.getEmail())) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "邮箱不能为空," + RRobotAccount.getCode() + "请检查数据第" + (i + 1) + "行");
            }
            if (StrUtil.isBlank(RRobotAccount.getPassword())) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "密码不能为空," + RRobotAccount.getPassword() + "请检查数据第" + (i + 1) + "行");
            }

            if(StrUtil.isNotBlank(RRobotAccount.getGroupName())){
                RRobotGroup group = nameToGroupMap.get(RRobotAccount.getGroupName().trim());
                if(group == null){
                    ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "分组不存在," + RRobotAccount.getGroupName() + "请检查数据第" + (i + 1) + "行");
                }
                RRobotAccount.setGroupId(group.getUuid());
            }
        }

        //邮箱检查，去重
        List<String> emailList = rRobotAccountList.stream().map(RRobotAccount::getEmail).collect(Collectors.toList());
        List<RRobotAccount> oldList = this.list(createBaseWrapper(null).in(RRobotAccount::getEmail, emailList));
        if (!oldList.isEmpty()) {
            Map<String, RRobotAccount> oldMap = EntityUtil.toMap(oldList, RRobotAccount::getEmail);
            for (int i = 0; i < rRobotAccountList.size(); i++) {
                RRobotAccount RRobotAccount = rRobotAccountList.get(i);
                if (oldMap.containsKey(RRobotAccount.getEmail())) {
                    ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "邮箱已存在," + RRobotAccount.getEmail() + "请检查数据第" + (i + 1) + "行");
                }
            }
        }
        ClientInfo clientInfo = ClientContextHelper.getClientInfo();
        List<RRobotAccount> newList = new ArrayList<>();

        for (int i = 0; i < rRobotAccountList.size(); i++) {
            RRobotAccount RRobotAccount = rRobotAccountList.get(i);
            RRobotAccount.setUuid(IdUtil.simpleUUID());
            RRobotAccount.setCreatorUuid(clientInfo.getId().toString()).setCreator(clientInfo.getNickname())
                    .setCreateTime(LocalDateTime.now());
            RRobotAccount.setStatus(1).setDeleted(0).setUpdateTime(LocalDateTime.now());
            newList.add(RRobotAccount);
        }

        //分批次插入
        // 分批插入，避免一次性插入大量数据
        int batchSize = 1000;
        for (int i = 0; i < newList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, newList.size());
            List<RRobotAccount> batch = newList.subList(i, endIndex);
            try {
                this.baseMapper.insertBatch(batch);
            } catch (Exception e) {
                log.error("批量插入数据失败", e);
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "批量插入数据失败");
            }
        }

    }

    @Override
    public List<RRobotAccount> getEnabledRobotAccountsBy(Set<String> robotUuids, Set<String> robotGroupUuids) {
        //清理robotUuids中的空串数据，放置查询穿透
        final List<String> finalRobotUuids = robotUuids.stream().filter(StrUtil::isNotBlank).collect(Collectors.toList());
        final List<String> finalRobotGroupUuids = robotGroupUuids.stream().filter(StrUtil::isNotBlank).collect(Collectors.toList());

        LambdaQueryWrapper<RRobotAccount> wrapper = createBaseWrapper(null);
        wrapper.and(wrapper1 -> {
            if(CollectionUtil.isNotEmpty(finalRobotUuids)) {
                wrapper1.in(RRobotAccount::getUuid, finalRobotUuids);
                wrapper1.or();
            }
            wrapper1.in(CollectionUtil.isNotEmpty(finalRobotGroupUuids), RRobotAccount::getGroupId, finalRobotGroupUuids);
        });
        wrapper.eq(RRobotAccount::getStatus, 1)
                .eq(RRobotAccount::getDeleted, 0)
                .eq(RRobotAccount::getValid, 1);
        return this.list(wrapper);
    }

    @Override
    public void isValid(String uid) {
        RRobotAccount account = this.checkedExistAndGet(uid);
        validateRobotAccountAsync(account);
    }

    @Override
    public void isValidNot() {
        // 获取所有未验证的机器人账号并进行验证
        List<RRobotAccount> accounts = this.list(createBaseWrapper(null)
                .eq(RRobotAccount::getValid, 0)); // 假设0表示未验证状态

        for (RRobotAccount account : accounts) {
            validateRobotAccountAsync(account);
        }
    }

    @Override
    public void isValidAll() {
        // 获取所有机器人账号并进行验证
        List<RRobotAccount> accounts = this.list(createBaseWrapper(null));

        for (RRobotAccount account : accounts) {
            validateRobotAccountAsync(account);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized void batchUpdateByImport(List<RRobotAccount> rRobotAccountList) {
        // 分组信息映射
        List<RRobotGroup> groupList = this.robotGroupService.getList(new RRobotGroupQuery().setStatus(1));
        Map<String, RRobotGroup> nameToGroupMap = groupList.stream()
                .collect(Collectors.toMap(RRobotGroup::getGroupName, group -> group));

        // 数据预处理
        for (int i = 0; i < rRobotAccountList.size(); i++) {
            RRobotAccount robotAccount = rRobotAccountList.get(i);

            // 检查必要字段
            if (StrUtil.isBlank(robotAccount.getEmail())) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(),
                        "邮箱不能为空," + robotAccount.getEmail() + "请检查数据第" + (i + 1) + "行");
            }

            // 处理分组信息
            if (StrUtil.isNotBlank(robotAccount.getGroupName())) {
                RRobotGroup group = nameToGroupMap.get(robotAccount.getGroupName().trim());
                if (group == null) {
                    ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(),
                            "分组不存在," + robotAccount.getGroupName() + "请检查数据第" + (i + 1) + "行");
                }
                robotAccount.setGroupId(group.getUuid());
            }
        }

        // 检查账号是否存在
        List<String> emailList = rRobotAccountList.stream()
                .map(RRobotAccount::getEmail)
                .collect(Collectors.toList());

        List<RRobotAccount> existingAccounts = this.list(createBaseWrapper(null).in(RRobotAccount::getEmail, emailList));
        Map<String, RRobotAccount> emailToAccountMap = EntityUtil.toMap(existingAccounts, RRobotAccount::getEmail);

        // 执行批量更新
        ClientInfo clientInfo = ClientContextHelper.getClientInfo();
        List<RRobotAccount> updateList = new ArrayList<>();

        for (int i = 0; i < rRobotAccountList.size(); i++) {
            RRobotAccount uploadAccount = rRobotAccountList.get(i);

            // 检查账号是否存在
            RRobotAccount existingAccount = emailToAccountMap.get(uploadAccount.getEmail());
            if (existingAccount == null) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(),
                        "账号不存在," + uploadAccount.getEmail() + "请检查数据第" + (i + 1) + "行");
            }

            // 设置更新信息
            RRobotAccount updateAccount = new RRobotAccount();
            updateAccount.setId(existingAccount.getId());
            updateAccount.setUuid(existingAccount.getUuid());

            // 只更新非空字段
            if (StrUtil.isNotBlank(uploadAccount.getNickname())) {
                updateAccount.setNickname(uploadAccount.getNickname());
            }
            if (StrUtil.isNotBlank(uploadAccount.getUserNumber())) {
                updateAccount.setUserNumber(uploadAccount.getUserNumber());
            }
            if (StrUtil.isNotBlank(uploadAccount.getMobile())) {
                updateAccount.setMobile(uploadAccount.getMobile());
            }
            if (StrUtil.isNotBlank(uploadAccount.getPassword())) {
                updateAccount.setPassword(uploadAccount.getPassword());
            }
            if (StrUtil.isNotBlank(uploadAccount.getHeaderIconUrl())) {
                updateAccount.setHeaderIconUrl(uploadAccount.getHeaderIconUrl());
            }
            if (StrUtil.isNotBlank(uploadAccount.getNotes())) {
                updateAccount.setNotes(uploadAccount.getNotes());
            }
            if (uploadAccount.getGroupId() != null) {
                updateAccount.setGroupId(uploadAccount.getGroupId());
                updateAccount.setGroupName(uploadAccount.getGroupName());
            }
            if (uploadAccount.getStatus() != null) {
                updateAccount.setStatus(uploadAccount.getStatus());
            }

            updateAccount.setUpdateTime(LocalDateTime.now());
            updateList.add(updateAccount);
        }

        // 分批更新，避免一次性更新大量数据
        int batchSize = 1000;
        for (int i = 0; i < updateList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, updateList.size());
            List<RRobotAccount> batch = updateList.subList(i, endIndex);
            try {
                // 使用MyBatis Plus的批量更新方法
                for (RRobotAccount account : batch) {
                    LambdaQueryWrapper<RRobotAccount> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(RRobotAccount::getUuid, account.getUuid());
                    this.update(account, wrapper);

                    // 清除缓存
                    String cacheKey = CACHE_KEY_PREFIX + account.getUuid();
                    cacheService.remove(cacheKey);
                }
            } catch (Exception e) {
                log.error("批量更新数据失败", e);
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "批量更新数据失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateByUids(List<String> uids, RRobotAccountQuery query) {
        if (CollectionUtil.isEmpty(uids)) {
            return;
        }

        // 验证所有待更新的账号是否存在
        List<RRobotAccount> existingAccounts = this.list(createBaseWrapper(null).in(RRobotAccount::getUuid, uids));
        if (existingAccounts.size() != uids.size()) {
            // 检查是否有不存在的账号
            Set<String> existingUuids = existingAccounts.stream()
                    .map(RRobotAccount::getUuid)
                    .collect(Collectors.toSet());
            List<String> notFoundUuids = uids.stream()
                    .filter(uid -> !existingUuids.contains(uid))
                    .collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(notFoundUuids)) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(),
                        "以下账号不存在: " + String.join(",", notFoundUuids));
            }
        }

        // 准备更新对象
        RRobotAccount update = BeanUtil.toBean(query, RRobotAccount.class);
        // 不允许更新uuid字段
        update.setUuid(null).setId(null);
        update.setUpdateTime(LocalDateTime.now());

        // 批量更新
        LambdaQueryWrapper<RRobotAccount> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RRobotAccount::getUuid, uids);
        this.update(update, wrapper);

        // 如果分组发生变化，同步更新分组名称
        if (query.getGroupId() != null) {
            RRobotGroup group = robotGroupService.getOneByUid(query.getGroupId().toString());
            if (group != null) {
                // 更新机器人账号表中的分组名称
                RRobotAccount accountUpdate = new RRobotAccount();
                accountUpdate.setGroupName(group.getGroupName());
                LambdaQueryWrapper<RRobotAccount> accountWrapper = new LambdaQueryWrapper<>();
                accountWrapper.in(RRobotAccount::getUuid, uids);
                this.update(accountUpdate, accountWrapper);

                // 更新配置关联表中的分组名称
                RConfigRelation configRelationUpdate = new RConfigRelation();
                configRelationUpdate.setGroupName(group.getGroupName());
                LambdaQueryWrapper<RConfigRelation> configRelationWrapper = new LambdaQueryWrapper<>();
                configRelationWrapper.in(RConfigRelation::getRobotUuid, uids);
                configRelationService.update(configRelationUpdate, configRelationWrapper);
            }
        }

        // 清除缓存，确保下次查询时获取最新数据
        for (String uid : uids) {
            String cacheKey = CACHE_KEY_PREFIX + uid;
            cacheService.remove(cacheKey);
        }
    }



    /**
     * 异步验证机器人账号
     *
     * @param account 待验证的机器人账号
     */
    private void validateRobotAccountAsync(RRobotAccount account) {
        CompletableFuture.runAsync(() -> {
            RLock lock = redissonClient.getLock("robot:validation:" + account.getUuid());

            try {
                // 尝试获取锁，最多等待10秒，锁定后30秒自动释放
                if (lock.tryLock(10, 30, TimeUnit.SECONDS)) {
                    log.info("开始验证机器人账号: {}", account.getEmail());

                    // 调用邮箱登录方法验证账号
                    ApiResponse<LoginResponse> result = businessService.loginByEmail(
                            account.getEmail(),
                            account.getPassword()
                    );

                    // 根据验证结果更新账号状态
                    RRobotAccount update = new RRobotAccount();
                    update.setUuid(account.getUuid());

                    if (result != null && result.getCode() != null && result.getCode() == 200) {
                        // 验证成功
                        update.setValid(1); // 设置为有效状态
                        update.setLastValidationTime(LocalDateTime.now());

                        // 检查RRbotoRunningInfo表中是否存在该账号的记录
                        if (rbotoRunningInfoService.count(
                                new LambdaQueryWrapper<RRobotRunningInfo>()
                                        .eq(RRobotRunningInfo::getRobotUuid, account.getUuid())) == 0) {
                            // 如果不存在，则新增一条初始数据
                            RRobotRunningInfo runningInfo = new RRobotRunningInfo();
                            runningInfo.setUuid(IdUtil.simpleUUID());
                            runningInfo.setRobotAccount(account.getEmail());
                            runningInfo.setRobotNickName(account.getNickname());
                            runningInfo.setRobotGroupUuid(account.getGroupId());
                            runningInfo.setRobotGroupName(account.getGroupName());
                            runningInfo.setRobotUuid(account.getUuid());
                            runningInfo.setRunningStatus(0);
                            runningInfo.setCurrentBehavior(1);
                            runningInfo.setLoginTime(LocalDateTime.now());
                            runningInfo.setLastUpdateTime(LocalDateTime.now());


                            rbotoRunningInfoService.save(runningInfo);
                            log.info("为验证通过的机器人账号创建初始运行信息: {}", account.getEmail());
                        }
                    } else {
                        // 验证失败
                        update.setValid(0); // 保持无效状态或设置为2表示验证失败
                        update.setLastValidationTime(LocalDateTime.now());
                    }

                    // 更新数据库
                    LambdaQueryWrapper<RRobotAccount> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(RRobotAccount::getUuid, account.getUuid());
                    this.update(update, wrapper);

                    // 清除缓存
                    String cacheKey = CACHE_KEY_PREFIX + account.getUuid();
                    cacheService.remove(cacheKey);

                    log.info("完成验证机器人账号: {}, 结果: {}", account.getEmail(),
                            result != null && result.getCode() != null && result.getCode() == 200 ? "成功" : "失败");
                } else {
                    log.warn("无法获取验证锁，跳过验证: {}", account.getEmail());
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("验证过程中线程被中断: {}", account.getEmail(), e);
            } catch (Exception e) {
                log.error("验证机器人账号时发生异常: {}", account.getEmail(), e);
            } finally {
                // 无论如何都要释放锁
                if (lock.isHeldByCurrentThread()) {
                    try {
                        lock.unlock();
                    } catch (Exception e) {
                        log.error("解锁时发生异常", e);
                    }
                }
            }
        });
    }


    private LambdaQueryWrapper<RRobotAccount> createBaseWrapper(RRobotAccountQuery query) {
        LambdaQueryWrapper<RRobotAccount> wrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            // 默认只查询未删除的记录
            wrapper.eq(RRobotAccount::getDeleted, 0);
            return wrapper;
        }

        // 默认只查询未删除的记录，除非明确指定要查询已删除的记录
        if (query.getDeleted() == null) {
            wrapper.eq(RRobotAccount::getDeleted, 0);
        } else {
            wrapper.eq(RRobotAccount::getDeleted, query.getDeleted());
        }
        //ids
        wrapper.in(CollectionUtil.isNotEmpty(query.getIds()), RRobotAccount::getId, query.getIds());

        //uids
        wrapper.in(CollectionUtil.isNotEmpty(query.getUids()), RRobotAccount::getUuid, query.getUids());

        wrapper.like(StrUtil.isNotBlank(query.getNickname()), RRobotAccount::getNickname, query.getNickname());
        wrapper.like(StrUtil.isNotBlank(query.getUserNumber()), RRobotAccount::getUserNumber, query.getUserNumber());
        wrapper.like(StrUtil.isNotBlank(query.getMobile()), RRobotAccount::getMobile, query.getMobile());


        wrapper.like(StrUtil.isNotBlank(query.getEmail()), RRobotAccount::getEmail, query.getEmail());
        wrapper.eq(query.getStatus() != null, RRobotAccount::getStatus, query.getStatus());
        wrapper.like(StrUtil.isNotBlank(query.getUuid()), RRobotAccount::getUuid, query.getUuid());
        // 根据实际业务需求补充更多查询条件
        wrapper.like(StrUtil.isNotBlank(query.getCode()), RRobotAccount::getCode, query.getCode());
        wrapper.like(StrUtil.isNotBlank(query.getNotes()), RRobotAccount::getNotes, query.getNotes());
        wrapper.eq(query.getGroupId() != null, RRobotAccount::getGroupId, query.getGroupId());
        wrapper.eq(query.getManagerId() != null, RRobotAccount::getManagerId, query.getManagerId());
        wrapper.like(StrUtil.isNotBlank(query.getGroupName()), RRobotAccount::getGroupName, query.getGroupName());
        wrapper.like(StrUtil.isNotBlank(query.getManagerName()), RRobotAccount::getManagerName, query.getManagerName());
        // 示例排序逻辑
        if (CollectionUtil.isNotEmpty(query.getSorts())) {
            MybatisPlusHelper.orderAndIgnoreError(RRobotAccount.class, wrapper, query.getSorts());
        } else {
            wrapper.orderByDesc(RRobotAccount::getCreateTime);
        }
        return wrapper;
    }
}




