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

import cn.com.poc.common.utils.BlContext;
import cn.com.poc.expose.dto.AiDialoguesKnowledgeDto;
import cn.com.poc.expose.rest.AiDialoguesKnowledgeRest;
import cn.com.poc.knowledge.constant.KnowledgeConstant;
import cn.com.poc.knowledge.dto.BizKnowledgeInfoDto;
import cn.com.poc.knowledge.query.KnowledgeInfosQueryCondition;
import cn.com.poc.knowledge.query.KnowledgeInfosQueryItem;
import cn.com.poc.knowledge.service.BizKnowledgeInfoService;
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.collections.CollectionUtils;
import org.springframework.stereotype.Component;

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

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

    List<String> organization = new ArrayList<String>() {{
        add("集团");
        add("企业");
        add("个人");
    }};

    @Resource
    private BizKnowledgeInfoService bizKnowledgeInfoService;

    @Override
    public Map<String, List<AiDialoguesKnowledgeDto>> knowledgeList() throws Exception {
        UserBaseEntity userBaseEntity = BlContext.getCurrentUserNotException();
        if (ObjectUtil.isEmpty(userBaseEntity)) {
            throw new BusinessException("用户未登录");
        }
        Map<String, List<AiDialoguesKnowledgeDto>> result = new LinkedHashMap<>();


        KnowledgeInfosQueryCondition condition = new KnowledgeInfosQueryCondition();
        condition.setMemberId(userBaseEntity.getUserId().toString());
        condition.setTrainStatus(KnowledgeConstant.TrainStatus.COMPLETE);
        condition.setKnowledgeType(KnowledgeConstant.KnowledgeType.BASE);

        List<KnowledgeInfosQueryItem> items = bizKnowledgeInfoService.knowledgeInfos(condition, null);
        if (CollectionUtils.isNotEmpty(items)) {
            int i = 1;
            int org = 0;
            for (KnowledgeInfosQueryItem item : items) {
                AiDialoguesKnowledgeDto aiDialoguesKnowledgeDto = new AiDialoguesKnowledgeDto();
                aiDialoguesKnowledgeDto.setKnowledgeName(item.getKnowledgeName());
                aiDialoguesKnowledgeDto.setKnowledgeId(item.getId());
                aiDialoguesKnowledgeDto.setKnowledgeType(item.getKnowledgeType());
                String orgName = organization.get(org);
                List<AiDialoguesKnowledgeDto> dtos = result.getOrDefault(orgName, new ArrayList<>());
                dtos.add(aiDialoguesKnowledgeDto);
                result.put(orgName, dtos);
                i++;
                if (i == 4) {
                    i = 1;
                    if (org < organization.size() - 1) {
                        org++;
                    }
                }
            }
        }
        return result;
    }
}
