package com.sundot.airport.exam.common.manager.impl;

import com.sundot.airport.exam.common.manager.TestPaperManager;
import com.sundot.airport.exam.common.model.result.QuesOptResult;
import com.sundot.airport.exam.common.model.result.TestPaperQuesAndQues;
import com.sundot.airport.exam.common.model.result.TestPaperQuesResult;
import com.sundot.airport.exam.common.service.QuesOptService;
import com.sundot.airport.exam.common.service.TestPaperQuesService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <b>功能名：TestPaperManagerImpl</b><br>
 * <b>说明：</b> 试卷通用业务处理层 <br>
 * <b>著作权：</b> Copyright (C) 2021 HUIFANEDU  CORPORATION<br>
 * <b>修改履历：</b><br>
 *
 * @author 2021-06-30 liangxiao
 */
@Service
public class TestPaperManagerImpl implements TestPaperManager {

    @Resource
    private TestPaperQuesService testPaperQuesService;
    @Resource
    private QuesOptService quesOptService;

    @Override
    public Map<String, List<TestPaperQuesResult>> byTpIdsFindAndBuildResult(List<String> tpIds) {
        // 查试卷题目计分列表和题干列表
        List<TestPaperQuesAndQues> tpQuesAndQues = testPaperQuesService.byTpIdFindAndQuesList(tpIds);

        // 试卷题目的quId列表
        List<String> quIds = tpQuesAndQues
                .stream()
                .map(TestPaperQuesAndQues::getQuId)
                .collect(Collectors.toList());

        // quIds对应的选项列表
        Map<String, List<QuesOptResult>> optionMap = quesOptService.byQuIdFindList(quIds)
                .stream()
                .map(i -> new QuesOptResult() {
                    {
                        BeanUtils.copyProperties(i, this);
                    }
                }).collect(Collectors.groupingBy(QuesOptResult::getQuId));

        // 转换结果。根据试卷业务id进行分组
        return tpQuesAndQues.stream()
                .map(i -> new TestPaperQuesResult() {
                    {
                        BeanUtils.copyProperties(i, this);
                        // 添加选项列表
                        this.setOption(optionMap.getOrDefault(i.getQuId(), Collections.emptyList()));
                    }
                })
                .collect(Collectors.groupingBy(TestPaperQuesResult::getTpId));
    }
}
