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.ChatInfo;
import com.ssyf.module.robot.domain.entity.RRobotGroup;
import com.ssyf.module.robot.domain.query.ChatInfoQuery;
import com.ssyf.module.robot.service.ChatInfoService;
import com.ssyf.module.robot.mapper.ChatInfoMapper;
import com.ssyf.module.robot.service.RRobotGroupService;
import com.ssyf.plugs.mysql.helper.MybatisPlusHelper;
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 针对表【chat_info(聊天信息表)】的数据库操作Service实现
* @createDate 2026-02-26 13:35:11
*/
@Service
public class ChatInfoServiceImpl extends ServiceImpl<ChatInfoMapper, ChatInfo>
    implements ChatInfoService{

    @Autowired
    private RRobotGroupService robotGroupService;


    @Override
    public ChatInfo addOne(ChatInfoQuery query) {

        // 处理分组和机器人名称
        handleGroupAndRobotNames(query);

        ClientInfo clientInfo = ClientContextHelper.getClientInfo();
        ChatInfo entity = BeanUtil.toBean(query ,ChatInfo.class);
        entity.setUuid(IdUtil.simpleUUID());
        entity.setChatTime(LocalDateTime.now());
        this.save(entity);

        return entity;
    }

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

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

    @Override
    public void updateByUid(String uuid, ChatInfoQuery query) {
        // 处理分组和机器人名称
        handleGroupAndRobotNames(query);

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

    @Override
    public ChatInfo getOneByUid(String uuid) {
        // 缓存未命中，查询数据库
        ChatInfo config = this.getOne(createBaseWrapper(null).eq(ChatInfo::getUuid, uuid));
        return config;
    }

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

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

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

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

    private LambdaQueryWrapper<ChatInfo> createBaseWrapper(ChatInfoQuery query) {
        LambdaQueryWrapper<ChatInfo> wrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            return wrapper;
        }
        wrapper.like(StrUtil.isNotBlank(query.getUuid()), ChatInfo::getUuid, query.getUuid());
        wrapper.like(StrUtil.isNotBlank(query.getRobotGroupUuid()), ChatInfo::getRobotGroupUuid, query.getRobotGroupUuid());
        wrapper.like(StrUtil.isNotBlank(query.getRobotGroupName()), ChatInfo::getRobotGroupName, query.getRobotGroupName());
        wrapper.like(StrUtil.isNotBlank(query.getRobotUuid()), ChatInfo::getRobotUuid, query.getRobotUuid());

        wrapper.like(StrUtil.isNotBlank(query.getChatContent()), ChatInfo::getChatContent, query.getChatContent());
        wrapper.like(query.getChatTime() != null, ChatInfo::getChatTime, query.getChatTime());
        wrapper.like(query.getChatType() != null, ChatInfo::getChatType, query.getChatType());
        wrapper.like(query.getChatConfigUuid() != null, ChatInfo::getChatConfigUuid, query.getChatConfigUuid());
        wrapper.like(query.getAnchorId() != null, ChatInfo::getAnchorId, query.getAnchorId());
        wrapper.like(query.getAnchorName() != null, ChatInfo::getAnchorName, query.getAnchorName());
        wrapper.like(query.getAnchorAvatar() != null, ChatInfo::getAnchorAvatar, query.getAnchorAvatar());
        wrapper.like(query.getRoomId() != null, ChatInfo::getRoomId, query.getRoomId());
        wrapper.like(query.getRoomName() != null, ChatInfo::getRoomName, query.getRoomName());
        wrapper.like(query.getRobotAccount() != null, ChatInfo::getRobotAccount, query.getRobotAccount());

        if (CollectionUtil.isNotEmpty(query.getSorts())) {
            MybatisPlusHelper.orderAndIgnoreError(ChatInfo.class, wrapper, query.getSorts());
        } else {
            wrapper.orderByDesc(ChatInfo::getChatTime);
        }
        return wrapper;
    }

    /**
     * 处理分组和机器人名称
     * 当uuid被更新或新增时确保name变更和有值
     */
    private void handleGroupAndRobotNames(ChatInfoQuery query) {
        // 处理机器人组名称
        if (StrUtil.isNotBlank(query.getRobotGroupUuid())) {
            if (StrUtil.isBlank(query.getRobotGroupName())) {
                // 根据robotGroupUuid查询对应的机器人组名称
                RRobotGroup robotGroup = robotGroupService.getOneByUid(query.getRobotGroupUuid());
                if (robotGroup != null) {
                    query.setRobotGroupName(robotGroup.getGroupName());
                } else {
                    // 如果分组不存在，抛出异常
                    ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "指定的机器人分组不存在");
                }
            }
        } else {
            // 如果uuid为空，则把name设置为空
            query.setRobotGroupName(null);
        }

    }
}




