package cn.sh.stc.sict.theme.hphy.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.sh.stc.sict.theme.hphy.model.HphyQuestionOption;
import cn.sh.stc.sict.theme.hphy.service.HphyQuestionOptionService;
import cn.sh.stc.sict.theme.hphy.vo.QuestionVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;

import cn.sh.stc.sict.theme.hphy.dao.HphyQuestionMapper;
import cn.sh.stc.sict.theme.hphy.model.HphyQuestion;
import cn.sh.stc.sict.theme.hphy.service.HphyQuestionService;

import java.util.ArrayList;
import java.util.List;


@Service("hphyQuestionService")
@AllArgsConstructor
public class HphyQuestionServiceImpl extends ServiceImpl<HphyQuestionMapper, HphyQuestion> implements HphyQuestionService {

    private final HphyQuestionMapper hphyQuestionMapper;
    private final HphyQuestionOptionService hphyQuestionOptionService;

    @Override
    public QuestionVO getVOById(Long nextQuestionId) {
        HphyQuestion question = this.getById(nextQuestionId);
        List<HphyQuestionOption> list = hphyQuestionOptionService.listByQuestionId(question.getId());
        List<QuestionVO> childList = this.getByParentId(nextQuestionId);
        return new QuestionVO(question, childList, list);
    }

    private List<QuestionVO> getByParentId(Long parentId) {
        List<QuestionVO> result = new ArrayList<>();;
        LambdaQueryWrapper<HphyQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HphyQuestion::getParentId, parentId);
        List<HphyQuestion> questionList = this.list(wrapper);
        if(CollUtil.isNotEmpty(questionList)){
            questionList.forEach(q->{
                List<HphyQuestionOption> list = hphyQuestionOptionService.listByQuestionId(q.getId());
                List<QuestionVO> childList = this.getByParentId(q.getId());
                result.add(new QuestionVO(q, childList, list));
            });
        }
        return result;
    }
}
