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.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.robot.domain.entity.RRobotGroup;
import com.ssyf.module.robot.domain.entity.RRobotAccount;
import com.ssyf.module.robot.domain.entity.RConfigRelation;
import com.ssyf.module.robot.domain.query.RRobotAccountQuery;
import com.ssyf.module.robot.domain.query.RRobotGroupQuery;
import com.ssyf.module.robot.service.RRobotAccountService;
import com.ssyf.module.robot.service.RRobotGroupService;
import com.ssyf.module.robot.mapper.RRobotGroupMapper;
import com.ssyf.plugs.mysql.helper.MybatisPlusHelper;
import com.ssyf.module.robot.service.RConfigRelationService;
import com.ssyf.module.robot.domain.query.RConfigRelationQuery;
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.Collections;
import java.util.List;

/**
* @author ELSA
* @description 针对表【r_robot_group(机器人分组表)】的数据库操作Service实现
* @createDate 2025-12-12 10:19:24
*/
@Service
public class RRobotGroupServiceImpl extends ServiceImpl<RRobotGroupMapper, RRobotGroup>
    implements RRobotGroupService{

    @Lazy
    @Autowired
    private RRobotAccountService robotAccountService;

    @Lazy
    @Autowired
    private RConfigRelationService configRelationService;

    @Override
    public synchronized RRobotGroup addOne(RRobotGroupQuery query) {
        if(StrUtil.isBlank(query.getGroupName())){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() , "分组名称不能为空");
        }
        if(this.count(createBaseWrapper(null).eq(RRobotGroup::getGroupName, query.getGroupName())) > 0){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() , "分组名称已存在");
        }
        ClientInfo clientInfo = ClientContextHelper.getClientInfo();
        RRobotGroup RRobotGroup = BeanUtil.toBean(query ,RRobotGroup.class);
        RRobotGroup.setUuid(IdUtil.simpleUUID());
        RRobotGroup.setCreatorUuid(clientInfo.getId().toString()).setCreator(clientInfo.getNickname())
                .setCreateTime(LocalDateTime.now());
        this.save(RRobotGroup);
        return RRobotGroup;
    }

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

        // 检查机器人是否存在关联
        if (robotAccountService.countBy(new RRobotAccountQuery().setGroupId(group.getUuid())) > 0) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "该分组下存在机器人账号，无法删除");
        }

        // 检查配置关联是否存在关联
        if (configRelationService.countBy(new RConfigRelationQuery().setRobotGroupUuid(uid)) > 0) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "该分组存在配置关联，无法删除");
        }

        this.remove(createBaseWrapper(null).eq(RRobotGroup::getUuid, uid));
    }

    @Override
    public void removeBatchByUids(List<String> uids) {
        // 检查每个分组是否存在关联
        for (String uid : uids) {
            RRobotGroup group = checkedExistAndGet(uid);
            
            // 检查机器人是否存在关联
            if (robotAccountService.countBy(new RRobotAccountQuery().setGroupId(group.getUuid())) > 0) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "分组" + group.getGroupName() + "下存在机器人账号，无法删除");
            }

            // 检查配置关联是否存在关联
            if (configRelationService.countBy(new RConfigRelationQuery().setRobotGroupUuid(uid)) > 0) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "分组" + group.getGroupName() + "存在配置关联，无法删除");
            }
        }
        
        this.remove(createBaseWrapper(null).in(RRobotGroup::getUuid, uids));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateByUid(String uid, RRobotGroupQuery query) {
        RRobotGroup oldGroup = this.checkedExistAndGet(uid);
        //不能更新uid，和id
        query.setUuid(null);
        RRobotGroup update = BeanUtil.toBean(query ,RRobotGroup.class);
        LambdaQueryWrapper<RRobotGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RRobotGroup::getUuid, uid);
        this.update(update , wrapper);
        
        // 如果分组名称发生变化，同步更新关联表中的分组名称
        if (StrUtil.isNotBlank(query.getGroupName()) && !query.getGroupName().equals(oldGroup.getGroupName())) {
            // 更新机器人账号表中的分组名称
            RRobotAccount robotAccountUpdate = new RRobotAccount();
            robotAccountUpdate.setGroupName(query.getGroupName());
            LambdaQueryWrapper<RRobotAccount> robotAccountWrapper = new LambdaQueryWrapper<>();
            robotAccountWrapper.eq(RRobotAccount::getGroupId, oldGroup.getId());
            robotAccountService.update(robotAccountUpdate, robotAccountWrapper);
            
            // 更新配置关联表中的分组名称
            RConfigRelation configRelationUpdate = new RConfigRelation();
            configRelationUpdate.setGroupName(query.getGroupName());
            LambdaQueryWrapper<RConfigRelation> configRelationWrapper = new LambdaQueryWrapper<>();
            configRelationWrapper.eq(RConfigRelation::getRobotGroupUuid, uid);
            configRelationService.update(configRelationUpdate, configRelationWrapper);
        }
    }

    @Override
    public RRobotGroup getOneByUid(String uid) {
        return this.getOne(createBaseWrapper(null).eq(RRobotGroup::getUuid, uid));
    }

    @Override
    public PageInfo<RRobotGroup> getPage(RRobotGroupQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return PageInfo.of(this.list(createBaseWrapper(query)));
    }

    @Override
    public List<RRobotGroup> getList(RRobotGroupQuery query) {
        return this.list(createBaseWrapper(query));
    }

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

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

    private LambdaQueryWrapper<RRobotGroup> createBaseWrapper(RRobotGroupQuery query) {
        LambdaQueryWrapper<RRobotGroup> wrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            return wrapper;
        }
        wrapper.like(StrUtil.isNotBlank(query.getGroupName()), RRobotGroup::getGroupName, query.getGroupName());
        wrapper.eq(query.getStatus() != null ,RRobotGroup::getStatus, query.getStatus());
        wrapper.like(StrUtil.isNotBlank(query.getUuid()) , RRobotGroup::getUuid, query.getUuid());
        // 根据实际业务需求补充更多查询条件
        wrapper.like(StrUtil.isNotBlank(query.getGroupCode()), RRobotGroup::getGroupCode, query.getGroupCode());
        wrapper.like(StrUtil.isNotBlank(query.getNotes()), RRobotGroup::getNotes, query.getNotes());
        // 示例排序逻辑
        if (CollectionUtil.isNotEmpty(query.getSorts())) {
            MybatisPlusHelper.orderAndIgnoreError(RRobotGroup.class, wrapper, query.getSorts());
        } else {
            wrapper.orderByDesc(RRobotGroup::getCreateTime);
        }
        return wrapper;
    }
}




