package cn.com.poc.writing.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.support.security.oauth.entity.UserBaseEntity;
import cn.com.poc.writing.aggregate.AiWritingService;
import cn.com.poc.writing.dto.*;
import cn.com.poc.writing.rest.AiWritingRest;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Component;

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

/**
 * @author alex.yao
 * @date 2025/6/20
 */
@Component
public class AiWritingRestImpl implements AiWritingRest {

    @Resource
    private AiWritingService aiWritingService;

    @Override
    public void call(AiWritingDto aiWritingDto) throws Exception {
        Assert.notNull(aiWritingDto, "aiWritingDto is null");
        Assert.notBlank(aiWritingDto.getInput(), "input is null");
        Assert.notBlank(aiWritingDto.getDialoguesId(), "dialogues id is null");

        UserBaseEntity userBaseEntity = BlContext.getCurrentUserNotException();
        if (userBaseEntity == null) {
            throw new BusinessException("用户未登录");
        }
        KnowledgeDefaultCache knowledgeDefaultCache = new KnowledgeDefaultCache();
        Integer[] knowledgeId;
        Integer[] defaultKnowledgeId = knowledgeDefaultCache.getDefaultKnowledgeId();
        if (ArrayUtils.isNotEmpty(aiWritingDto.getKnowledgeIds())) {
            knowledgeId = Arrays.stream(ArrayUtils.addAll(defaultKnowledgeId, aiWritingDto.getKnowledgeIds())).distinct()
                    .toArray(Integer[]::new);
        } else {
            knowledgeId = defaultKnowledgeId;
        }
        aiWritingService.call(aiWritingDto.getDialoguesId(), aiWritingDto.getFileUrl(),
                aiWritingDto.getInput(), knowledgeId, userBaseEntity.getUserId(),
                aiWritingDto.getEnableSearchEngine(), aiWritingDto.getEnableDeepThinking());

    }


    @Override
    public List<AiWritingExampleDto> example(String type) throws Exception {
        Assert.notNull(type, "type is null");
        return aiWritingService.example(type);
    }

    @Override
    public List<AiWritingExampleTypeDto> exampleType() throws Exception {
        return aiWritingService.exampleType();
    }

    @Override
    public AiWritingTitleGenerationDto titleGeneration(TitleGenerationDto titleGenerationDto) {
        Assert.notNull(titleGenerationDto, "titleGenerationDto is null");
        Assert.notBlank(titleGenerationDto.getInput(), "input is null");
        return aiWritingService.titleGeneration(titleGenerationDto.getInput());
    }

    @Override
    public List<AiWritingDialoguesContextDto> getDialogueContext(String dialogueId) throws Exception {
        Assert.notBlank(dialogueId, "dialogues id is null");
        return aiWritingService.getDialogueContext(dialogueId);
    }
}
