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.RConfigRelation;
import com.ssyf.module.robot.domain.entity.RRobotAccount;
import com.ssyf.module.robot.domain.entity.RRobotGroup;
import com.ssyf.module.robot.domain.query.RConfigRelationQuery;
import com.ssyf.module.robot.service.RConfigRelationService;
import com.ssyf.module.robot.service.RRobotAccountService;
import com.ssyf.module.robot.service.RRobotGroupService;
import com.ssyf.module.robot.mapper.RConfigRelationMapper;
import com.ssyf.plugs.mysql.helper.MybatisPlusHelper;
import com.ssyf.task.service.RobotAutomationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author ELSA
* @description 针对表【r_config_relation(配置关联表)】的数据库操作Service实现
* @createDate 2025-12-18 10:53:31
*/
@Service
public class RConfigRelationServiceImpl extends ServiceImpl<RConfigRelationMapper, RConfigRelation>
    implements RConfigRelationService{

    @Autowired
    private RRobotAccountService robotAccountService;

    @Autowired
    private RRobotGroupService robotGroupService;

    @Override
    public RConfigRelation addOne(RConfigRelationQuery query) {
        if(StrUtil.isBlank(query.getConfigUuid())){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() , "配置UUID不能为空");
        }

        // 检查机器人是否存在
        if(StrUtil.isNotBlank(query.getRobotUuid())) {
            RRobotAccount robotAccount = robotAccountService.getOneByUid(query.getRobotUuid());
            if (robotAccount == null) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "指定的机器人不存在");
            }
            // 设置机器人账号名称
            query.setRobotAccount(robotAccount.getEmail());
        }
        
        // 如果存在分组UUID，检查分组是否存在
        if (StrUtil.isNotBlank(query.getRobotGroupUuid())) {
            RRobotGroup robotGroup = robotGroupService.getOneByUid(query.getRobotGroupUuid());
            if (robotGroup == null) {
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "指定的分组不存在");
            }
            // 设置分组名称
            query.setGroupName(robotGroup.getGroupName());
        }

        if(StrUtil.isBlank(query.getRobotUuid()) && StrUtil.isBlank(query.getRobotGroupUuid())){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "请指定机器人或分组");
        }
        

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

        this.save(entity);

        return entity;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByUid(String uuid) {
        checkedExistAndGet(uuid);
        this.remove(createBaseWrapper(null).eq(RConfigRelation::getUuid, uuid));
    }

    @Override
    public void removeBatchByUids(List<String> uuids) {
        this.remove(createBaseWrapper(null).in(RConfigRelation::getUuid, uuids));
    }

    @Override
    public void updateByUid(String uuid, RConfigRelationQuery query) {
        this.checkedExistAndGet(uuid);
        if(StrUtil.isNotBlank(query.getRobotGroupUuid())){
            RRobotGroup robotGroup = this.robotGroupService.getOneByUid(query.getRobotGroupUuid());
            if(robotGroup == null){
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() , "机器人分组不存在");
            }
            query.setGroupName(robotGroup.getGroupName());
        }
        if (StrUtil.isBlank(query.getRobotUuid())){
            if(StrUtil.isBlank(query.getRobotGroupUuid())){
                ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() , "机器人和分组不能同时为空");
            }
            query.setRobotAccount("");
        }

        query.setUuid(null);
        RConfigRelation update = BeanUtil.toBean(query ,RConfigRelation.class);
        LambdaQueryWrapper<RConfigRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RConfigRelation::getUuid, uuid);
        this.update(update , wrapper);
    }

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

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

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

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

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

    @Override
    public List<RConfigRelation> getByGroupUuid(String groupUuid, String configType) {
        if (StrUtil.isBlank(groupUuid)) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "分组UUID不能为空");
        }
        
        RConfigRelationQuery query = new RConfigRelationQuery();
        query.setRobotGroupUuid(groupUuid);
        if (StrUtil.isNotBlank(configType)) {
            query.setConfigType(configType);
        }
        
        return this.getList(query);
    }

    @Override
    public List<RConfigRelation> getValidByGroupUuid(String groupUuid, String configType) {
        if (StrUtil.isBlank(groupUuid)) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "分组UUID不能为空");
        }
        
        RConfigRelationQuery query = new RConfigRelationQuery();
        query.setRobotGroupUuid(groupUuid);
        if (StrUtil.isNotBlank(configType)) {
            query.setConfigType(configType);
        }
        
        // 设置当前时间范围过滤条件
        LocalDateTime now = LocalDateTime.now();
        query.setStartTimeStart(now);
        query.setEndTimeEnd(now);
        
        return this.getList(query);
    }

    @Override
    public List<RConfigRelation> getByRobotUuid(String robotUuid, String configType) {
        if (StrUtil.isBlank(robotUuid)) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "机器人UUID不能为空");
        }
        
        RConfigRelationQuery query = new RConfigRelationQuery();
        query.setRobotUuid(robotUuid);
        if (StrUtil.isNotBlank(configType)) {
            query.setConfigType(configType);
        }
        
        return this.getList(query);
    }

    @Override
    public List<RConfigRelation> getValidByRobotUuid(String robotUuid, String configType) {
        if (StrUtil.isBlank(robotUuid)) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "机器人UUID不能为空");
        }
        
        RConfigRelationQuery query = new RConfigRelationQuery();
        query.setRobotUuid(robotUuid);
        if (StrUtil.isNotBlank(configType)) {
            query.setConfigType(configType);
        }
        
        // 设置当前时间范围过滤条件
        LocalDateTime now = LocalDateTime.now();
        query.setStartTimeStart(now);
        query.setEndTimeEnd(now);
        
        return this.getList(query);
    }

    @Override
    public List<RConfigRelation> getByConfigUuids(List<String> configUuids, String configType) {
        if (CollectionUtil.isEmpty(configUuids)) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "配置UUID列表不能为空");
        }
        
        RConfigRelationQuery query = new RConfigRelationQuery();
        query.setConfigUuids(configUuids);
        if (StrUtil.isNotBlank(configType)) {
            query.setConfigType(configType);
        }
        
        return this.getList(query);
    }

    @Override
    public List<RConfigRelation> getByRobotUuids(List<String> robotUuids, String configType) {
        if (CollectionUtil.isEmpty(robotUuids)) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "机器人UUID列表不能为空");
        }
        
        RConfigRelationQuery query = new RConfigRelationQuery();
        query.setRobotUuids(robotUuids);
        if (StrUtil.isNotBlank(configType)) {
            query.setConfigType(configType);
        }
        
        return this.getList(query);
    }

    @Override
    public List<RConfigRelation> getAvailableConfigs() {
        LambdaQueryWrapper<RConfigRelation> queryWrapper = createBaseWrapper(new RConfigRelationQuery());
         int now = LocalDateTime.now().getHour();
        queryWrapper.or(aa -> {
            aa.or(wrapper -> {
                wrapper.le(RConfigRelation::getStartTime, now);
                wrapper.ge(RConfigRelation::getEndTime, now);
            }).or(wrapper -> {
                wrapper.le(RConfigRelation::getStartTime1, now);
                wrapper.ge(RConfigRelation::getEndTime1, now);
            }).or(wrapper -> {
                wrapper.le(RConfigRelation::getStartTime2, now);
                wrapper.ge(RConfigRelation::getEndTime2, now);
            }).or(wrapper -> {
                wrapper.le(RConfigRelation::getStartTime3, now);
                wrapper.ge(RConfigRelation::getEndTime3, now);
            }).or(wrapper -> {
                wrapper.le(RConfigRelation::getStartTime4, now);
                wrapper.ge(RConfigRelation::getEndTime4, now);
            }).or(wrapper -> {
                wrapper.le(RConfigRelation::getStartTime5, now);
                wrapper.ge(RConfigRelation::getEndTime5, now);
            });
        });

        return this.list(queryWrapper);
    }

    private LambdaQueryWrapper<RConfigRelation> createBaseWrapper(RConfigRelationQuery query) {
        LambdaQueryWrapper<RConfigRelation> wrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            return wrapper;
        }
        wrapper.like(StrUtil.isNotBlank(query.getRobotAccount()), RConfigRelation::getRobotAccount, query.getRobotAccount());
        wrapper.like(StrUtil.isNotBlank(query.getUuid()), RConfigRelation::getUuid, query.getUuid());
        wrapper.eq(StrUtil.isNotBlank(query.getRobotGroupUuid()), RConfigRelation::getRobotGroupUuid, query.getRobotGroupUuid());
        wrapper.like(StrUtil.isNotBlank(query.getGroupName()), RConfigRelation::getGroupName, query.getGroupName());
        wrapper.eq(StrUtil.isNotBlank(query.getRobotUuid()), RConfigRelation::getRobotUuid, query.getRobotUuid());
        wrapper.eq(StrUtil.isNotBlank(query.getConfigType()), RConfigRelation::getConfigType, query.getConfigType());
        wrapper.eq(StrUtil.isNotBlank(query.getConfigUuid()), RConfigRelation::getConfigUuid, query.getConfigUuid());
        wrapper.like(StrUtil.isNotBlank(query.getConfigName()), RConfigRelation::getConfigName, query.getConfigName());
        wrapper.eq(query.getConfigPriority() != null, RConfigRelation::getConfigPriority, query.getConfigPriority());
        
        // 批量查询条件
        wrapper.in(CollectionUtil.isNotEmpty(query.getConfigUuids()), RConfigRelation::getConfigUuid, query.getConfigUuids());
        wrapper.in(CollectionUtil.isNotEmpty(query.getRobotUuids()), RConfigRelation::getRobotUuid, query.getRobotUuids());
        wrapper.ge(query.getStartTimeStart() != null, RConfigRelation::getStartTime, query.getStartTimeStart());
        wrapper.le(query.getStartTimeEnd() != null, RConfigRelation::getStartTime, query.getStartTimeEnd());
        wrapper.ge(query.getEndTimeStart() != null, RConfigRelation::getEndTime, query.getEndTimeStart());
        wrapper.le(query.getEndTimeEnd() != null, RConfigRelation::getEndTime, query.getEndTimeEnd());
        wrapper.ge(query.getCreateTimeStart() != null, RConfigRelation::getCreateTime, query.getCreateTimeStart());
        wrapper.le(query.getCreateTimeEnd() != null, RConfigRelation::getCreateTime, query.getCreateTimeEnd());
        wrapper.like(StrUtil.isNotBlank(query.getCreator()), RConfigRelation::getCreator, query.getCreator());
        wrapper.eq(StrUtil.isNotBlank(query.getCreatorUuid()), RConfigRelation::getCreatorUuid, query.getCreatorUuid());
        
        if (CollectionUtil.isNotEmpty(query.getSorts())) {
            MybatisPlusHelper.orderAndIgnoreError(RConfigRelation.class, wrapper, query.getSorts());
        } else {
            // 默认按配置优先级降序，创建时间降序排序
            wrapper.orderByDesc(RConfigRelation::getConfigPriority)
                   .orderByDesc(RConfigRelation::getCreateTime);
        }
        return wrapper;
    }
}




