package cn.com.poc.portal.rest.impl;

import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.BlContext;
import cn.com.poc.knowledge.cache.KnowledgeDefaultCache;
import cn.com.poc.portal.aggregate.PortalService;
import cn.com.poc.portal.convert.PortalConvert;
import cn.com.poc.portal.dto.PortalDialoguesDto;
import cn.com.poc.portal.entity.PortalDialoguesCallEntity;
import cn.com.poc.portal.rest.PortalRest;
import cn.com.poc.support.security.oauth.entity.UserBaseEntity;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author alex.yao
 * @date 2025/6/19
 */
@Component
public class PortalRestImpl implements PortalRest {

    @Resource
    private PortalService portalService;

    @Override
    public void call(PortalDialoguesDto dto) throws Exception {
        Assert.notNull(dto, "请求参数不能为空");
        Assert.notBlank(dto.getDialoguesId(), "会话ID不能为空");
        Assert.notBlank(dto.getInput(), "对话内容不能为空");
        UserBaseEntity userBaseEntity = BlContext.getCurrentUserNotException();
        if (ObjectUtil.isEmpty(userBaseEntity)) {
            throw new BusinessException("用户未登录");
        }
        KnowledgeDefaultCache knowledgeDefaultCache = new KnowledgeDefaultCache();
        Integer[] knowledgeId;
        Integer[] defaultKnowledgeId = knowledgeDefaultCache.getDefaultKnowledgeId();
        if (ArrayUtils.isNotEmpty(dto.getKnowledgeIds())) {
            knowledgeId = Arrays.stream(ArrayUtils.addAll(defaultKnowledgeId, dto.getKnowledgeIds())).distinct()
                    .toArray(Integer[]::new);
        } else {
            knowledgeId = defaultKnowledgeId;
        }
        PortalDialoguesCallEntity callEntity = PortalConvert.callDtoToEntity(dto);
        callEntity.setKnowledgeIds(knowledgeId);
        portalService.call(callEntity, userBaseEntity.getUserId());
    }
}
