package com.emoon.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.emoon.common.core.utils.MapstructUtils;
import com.emoon.common.core.utils.StringUtils;
import com.emoon.common.mybatis.core.page.PageQuery;
import com.emoon.common.mybatis.core.page.TableDataInfo;
import com.emoon.knowledge.domain.AiAgent;
import com.emoon.knowledge.domain.bo.AiAgentBo;
import com.emoon.knowledge.domain.vo.AiAgentVo;
import com.emoon.knowledge.mapper.AiAgentMapper;
import com.emoon.knowledge.service.IAiAgentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 智能体Service业务层处理
 *
 * @author wangkang
 * @date 2026-01-27
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AiAgentServiceImpl implements IAiAgentService {

    private final AiAgentMapper baseMapper;

    /**
     * 查询智能体
     *
     * @param id 主键
     * @return 智能体
     */
    @Override
    public AiAgentVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 根据agentId查询智能体
     *
     * @param agentId 智能体唯一标识
     * @return 智能体
     */
    @Override
    public AiAgentVo queryByAgentId(String agentId) {
        LambdaQueryWrapper<AiAgent> lqw = Wrappers.lambdaQuery();
        lqw.eq(AiAgent::getAgentId, agentId);
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 分页查询智能体列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 智能体分页列表
     */
    @Override
    public TableDataInfo<AiAgentVo> queryPageList(AiAgentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AiAgent> lqw = buildQueryWrapper(bo);
        Page<AiAgentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的智能体列表
     *
     * @param bo 查询条件
     * @return 智能体列表
     */
    @Override
    public List<AiAgentVo> queryList(AiAgentBo bo) {
        LambdaQueryWrapper<AiAgent> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AiAgent> buildQueryWrapper(AiAgentBo bo) {
        LambdaQueryWrapper<AiAgent> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AiAgent::getClusterId).orderByAsc(AiAgent::getId);
        lqw.eq(bo.getClusterId() != null, AiAgent::getClusterId, bo.getClusterId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), AiAgent::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getSubType()), AiAgent::getSubType, bo.getSubType());
        lqw.like(StringUtils.isNotBlank(bo.getGoal()), AiAgent::getGoal, bo.getGoal());
        lqw.like(StringUtils.isNotBlank(bo.getScenario()), AiAgent::getScenario, bo.getScenario());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AiAgent::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getAgentId()), AiAgent::getAgentId, bo.getAgentId());
        return lqw;
    }

    /**
     * 新增智能体
     *
     * @param bo 智能体
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AiAgentBo bo) {
        AiAgent add = MapstructUtils.convert(bo, AiAgent.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改智能体
     *
     * @param bo 智能体
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AiAgentBo bo) {
        AiAgent update = MapstructUtils.convert(bo, AiAgent.class);
        
        // 确保配置字段从 BO 中正确获取，如果 BO 中有值则使用 BO 的值，否则设置为空列表
        // 这样 FastjsonTypeHandler 才能正确处理
        if (bo.getModelIds() != null) {
            update.setModelIds(bo.getModelIds());
        } else if (update.getModelIds() == null) {
            update.setModelIds(new ArrayList<>());
        }
        
        if (bo.getTemplateIds() != null) {
            update.setTemplateIds(bo.getTemplateIds());
        } else if (update.getTemplateIds() == null) {
            update.setTemplateIds(new ArrayList<>());
        }
        
        if (bo.getRagIds() != null) {
            update.setRagIds(bo.getRagIds());
        } else if (update.getRagIds() == null) {
            update.setRagIds(new ArrayList<>());
        }
        
        if (bo.getApiIds() != null) {
            update.setApiIds(bo.getApiIds());
        } else if (update.getApiIds() == null) {
            update.setApiIds(new ArrayList<>());
        }

        if (bo.getCardIds() != null) {
            update.setCardIds(bo.getCardIds());
        } else if (update.getCardIds() == null) {
            update.setCardIds(new ArrayList<>());
        }
        
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AiAgent entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除智能体信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}

