package com.diagbot.facade;

import com.diagbot.dto.RetrievalDTO;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.service.impl.RetrievalServiceImpl;
import com.diagbot.util.ListUtil;
import com.diagbot.vo.RetrievalVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: wangyu
 * @time: 2018/11/27 14:54
 */
@Component
public class RetrievalFacade extends RetrievalServiceImpl {

    @Autowired
    QuestionFacade questionFacade;

    /**
     * 获取标签信息
     *
     * @param retrievalVO
     * @return
     */
    public List<RetrievalDTO> getTagInfos(@Valid @RequestBody RetrievalVO retrievalVO) {
        if (retrievalVO.getInputStr() == null || retrievalVO.getInputStr() == "") {
            retrievalVO.setInputStr(" ");
        }
        //过滤传来的空值
        if(ListUtil.isNotEmpty(retrievalVO.getInputIds())){
            List<Long> questionIds = new ArrayList<>();
            for (Long questionId:retrievalVO.getInputIds()) {
                if (null != questionId){
                    questionIds.add(questionId);
                }
            }
            retrievalVO.setInputIds(questionIds);
        }
        //获取同义词标签信息
        List<RetrievalDTO> data = this.getSymptopInfo(retrievalVO);
        List<Long> selfIds = new ArrayList<>();
        for (RetrievalDTO bean : data) {//筛选本身的id
            if ((1 == bean.getShowType())
                    && !selfIds.contains(bean.getQuestionId())) {
                selfIds.add(bean.getQuestionId());
            }
        }
        List<RetrievalDTO> resultSubitemData = new ArrayList<>();
        for (RetrievalDTO bean : data) {//当出现本体和同义词时，不显示同义词
            if (1 == bean.getShowType()) {
                resultSubitemData.add(bean);
            } else {
                if (!selfIds.contains(bean.getQuestionId())) {
                    resultSubitemData.add(bean);
                }
            }
        }
        List<Long> questionIdList = resultSubitemData.stream()
                .map(r -> r.getQuestionId())
                .collect(Collectors.toList());
        //将标签名放入实体
        Map<Long, QuestionInfo> map = questionFacade.getQuestionInfos(questionIdList);
        for (RetrievalDTO retrievalDTO : resultSubitemData) {
            retrievalDTO.setName(map.get(retrievalDTO.getQuestionId()).getTagName());
        }
        return resultSubitemData;
    }
}
