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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.sh.stc.sict.cloud.common.core.constant.Constant;
import cn.sh.stc.sict.cloud.common.core.util.NumberUtil;
import cn.sh.stc.sict.theme.hphy.constant.PatientConstant;
import cn.sh.stc.sict.theme.hphy.dao.HphyGuideQuestionMapper;
import cn.sh.stc.sict.theme.hphy.model.HphyGuideQuestion;
import cn.sh.stc.sict.theme.hphy.model.HphyGuideQuestionOption;
import cn.sh.stc.sict.theme.hphy.model.HphyQuestion;
import cn.sh.stc.sict.theme.hphy.model.HphyQuestionOption;
import cn.sh.stc.sict.theme.hphy.service.HphyGuideQuestionOptionService;
import cn.sh.stc.sict.theme.hphy.service.HphyGuideQuestionService;
import cn.sh.stc.sict.theme.hphy.service.HphyQuestionOptionService;
import cn.sh.stc.sict.theme.hphy.service.HphyQuestionService;
import cn.sh.stc.sict.theme.hphy.vo.AnswerDTO;
import cn.sh.stc.sict.theme.hphy.vo.EvaParamDTO;
import cn.sh.stc.sict.theme.hphy.vo.EvaSaveResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Service("hphyGuideQuestionService")
@AllArgsConstructor
public class HphyGuideQuestionServiceImpl extends ServiceImpl<HphyGuideQuestionMapper, HphyGuideQuestion> implements HphyGuideQuestionService {

    private final HphyGuideQuestionMapper hphyGuideQuestionMapper;
    private final HphyQuestionService hphyQuestionService;
    private final HphyQuestionOptionService hphyQuestionOptionService;
    private final HphyGuideQuestionOptionService hphyGuideQuestionOptionService;

    /**
     * 保存用户问卷答案并返回下一题id
     * 获取题目
     * 获取答案
     * 保存题目
     * 保存答案
     * 计算下一题id
     *
     * @param dto
     * @return
     */
    @Override
    public EvaSaveResult saveRecord(EvaParamDTO dto) {
        EvaSaveResult result = new EvaSaveResult();
        if (CollUtil.isNotEmpty(dto.getAnswerList())) {
            dto.getAnswerList().forEach(answer -> {
                this.saveAnswer(result, dto.getGuideId(), dto.getPrevQuestionId(), answer);
            });
        }
        return result;
    }

    @Override
    public List<HphyGuideQuestionOption> getAnswerList(HphyGuideQuestion gq) {
        if (null == gq || NumberUtil.isNullOrZero(gq.getId())) {
            return new ArrayList<>();
        }
        if (NumberUtil.isNullOrZero(gq.getParentId())) {
            return hphyGuideQuestionOptionService.listByGqId(Arrays.asList(gq.getId()));
        } else {
            LambdaQueryWrapper<HphyGuideQuestion> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(HphyGuideQuestion::getParentId, gq.getParentId())
                    .eq(HphyGuideQuestion::getGuideId, gq.getGuideId());
            List<HphyGuideQuestion> list = this.list();
            if (CollUtil.isNotEmpty(list)) {
                return hphyGuideQuestionOptionService.listByGqId(list.stream().map(HphyGuideQuestion::getId).collect(Collectors.toList()));
            }
        }
        return new ArrayList<>();
    }

    /**
     * 吃药 且 无高血压 直接退出
     *
     * @param guideId
     * @param answer
     * @return
     */
    private void saveAnswer(EvaSaveResult result, Long guideId, Long prevId, AnswerDTO answer) {
        boolean isNull = NumberUtil.isNullOrZero(result.getNextQuestionId());
        HphyQuestion question = hphyQuestionService.getById(answer.getQuestionId());
        HphyGuideQuestion gq = new HphyGuideQuestion();
        gq.setId(this.deleteHistory(guideId, question.getId()));
        gq.setGuideId(guideId);
        gq.setTitle(question.getTitle());
        gq.setTag(question.getTag());
        gq.setPrevId(prevId);
        gq.setParentId(question.getParentId());
        gq.setQuestionId(question.getId());
        if(CollUtil.isNotEmpty(answer.getOptionIdList())){
            this.saveOrUpdate(gq);
            result.setPrevQuestionId(gq.getId());
            List<HphyGuideQuestionOption> gqoList = new ArrayList<>();
            if (CollUtil.isNotEmpty(answer.getOptionIdList())) {
                List<HphyQuestionOption> optionList = hphyQuestionOptionService.listByIds(answer.getOptionIdList());
                if (CollUtil.isNotEmpty(optionList)) {
                    optionList.forEach(op -> {
                        if (NumberUtil.isNotNullOrZero(op.getNextQuestionId()) && isNull) {
                            result.setNextQuestionId(op.getNextQuestionId());
                        }
                        HphyGuideQuestionOption gqo = new HphyGuideQuestionOption();
                        gqo.setGuideQuestionId(gq.getId());
                        gqo.setTitle(op.getTitle());
                        gqo.setTag(op.getTag());
                        gqoList.add(gqo);
                    });
                }
            }
            if (StrUtil.isNotBlank(answer.getExt())) {
                HphyGuideQuestionOption gqo = new HphyGuideQuestionOption();
                gqo.setGuideQuestionId(gq.getId());
                gqo.setTitle(answer.getExt());
                gqoList.add(gqo);
            }
            hphyGuideQuestionOptionService.saveBatch(gqoList);

            if (NumberUtil.isNotNullOrZero(question.getNextId()) && isNull) {
                result.setNextQuestionId(question.getNextId());
            }
        }else{
            if(NumberUtil.isNotNullOrZero(gq.getId())){
                this.removeById(gq.getId());
            }
        }
        // 血压值选项： 吃药 且 无高血压 直接退出
//        if (PatientConstant.QUESTION_DISEASECAL.equals(question.getTag())) {
//            // 判断是否吃药
//            HphyGuideQuestion drug = this.getDrugQuestion(guideId);
//            HphyGuideQuestionOption option = hphyGuideQuestionOptionService.getDrugOption(drug.getId());
//            Integer diseaseLevel = 1;// gqoList.stream().mapToInt(i -> Integer.valueOf(i.getTag())).sum();
//            if (Constant.STRING_NO.equals(option.getTag()) && PatientConstant.DISEASE_0.equals(diseaseLevel)) {
//                result.setNextQuestionId(0L);
//            }
//        }
    }

    private Long deleteHistory(Long guideId, Long questionId) {
        LambdaQueryWrapper<HphyGuideQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HphyGuideQuestion::getGuideId, guideId)
                .eq(HphyGuideQuestion::getQuestionId, questionId);
        HphyGuideQuestion one = this.getOne(wrapper);
        if (null != one && NumberUtil.isNotNullOrZero(one.getId())) {
            hphyGuideQuestionOptionService.deleteByQuestionId(one.getId());
            return one.getId();
        }
        return null;
    }

    /**
     * 获取吃药题目
     *
     * @param guideId
     * @return
     */
    private HphyGuideQuestion getDrugQuestion(Long guideId) {
        LambdaQueryWrapper<HphyGuideQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HphyGuideQuestion::getGuideId, guideId)
                .eq(HphyGuideQuestion::getTag, PatientConstant.QUESTION_DRUG)
                .last("limit 1");
        return this.getOne(wrapper);
    }
}
