package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.client.NLPServiceClient;
import com.diagbot.client.bean.Response;
import com.diagbot.dto.SymptomFeatureDTO;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.QuestionTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.util.ListUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author:zhaops
 * @time: 2019/2/26 13:27
 */
@Component
public class FeatureFacade {
    @Autowired
    private NLPServiceClient NLPServiceClient;
    @Autowired
    private QuestionFacade questionFacade;

    /**
     * 症状关键词提取
     *
     * @param text
     * @return
     */
    public List<SymptomFeatureDTO> getSymptomFeature(String text) {
        List<SymptomFeatureDTO> symptomFeatureDTOList = Lists.newLinkedList();
        Response<List<Map<String, Object>>> res = NLPServiceClient.symptomFeaturePageData(text);
        if (null == res || null == res.getData()) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "AI没有返回结果");
        }
        List<Map<String, Object>> symptomFeatureList = res.getData();
        List<String> symptomNameList = Lists.newLinkedList();
        for (Map<String, Object> symptomFeature : symptomFeatureList) {
            if (symptomFeature != null) {
                symptomNameList.add(symptomFeature.get("feature_name").toString());
            }
        }
        if (!ListUtil.isNotEmpty(symptomFeatureList)) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "未提取到特征词");
        }
        QueryWrapper<QuestionInfo> questionInfoQueryWrapper = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                in("tag_name", symptomNameList).
                eq("type", QuestionTypeEnum.Symptom.getKey()).
                eq("item_type", 0);
        List<QuestionInfo> questionInfoList = questionFacade.list(questionInfoQueryWrapper);
        for (QuestionInfo questionInfo : questionInfoList) {
            SymptomFeatureDTO symptomFeatureDTO = new SymptomFeatureDTO();
            symptomFeatureDTO.setId(questionInfo.getId());
            symptomFeatureDTO.setTagName(questionInfo.getTagName());
            symptomFeatureDTO.setName(questionInfo.getName());
            symptomFeatureDTOList.add(symptomFeatureDTO);
        }
        return symptomFeatureDTOList;
    }
}