package cn.com.qmth.examcloud.tool.service.query_paper_struct;

import cn.com.qmth.examcloud.tool.config.SysProperty;
import cn.com.qmth.examcloud.tool.service.CommonService;
import cn.com.qmth.examcloud.tool.service.export_student_answer_and_score_detail.vo.CourseVO;
import cn.com.qmth.examcloud.tool.service.query_paper_struct.vo.ExamPaperVO;
import cn.com.qmth.examcloud.tool.service.query_paper_struct.vo.ExtractConfigVO;
import cn.com.qmth.examcloud.tool.service.query_paper_struct.vo.GetPaperStructResp;
import cn.com.qmth.examcloud.tool.utils.HttpHelper;
import cn.com.qmth.examcloud.tool.utils.JsonMapper;
import cn.com.qmth.examcloud.tool.utils.SignUtils;
import cn.com.qmth.examcloud.tool.vo.Pager;
import cn.com.qmth.examcloud.tool.vo.paper.DefaultQuestionGroup;
import cn.com.qmth.examcloud.tool.vo.paper.DefaultQuestionStructureWrapper;
import cn.com.qmth.examcloud.tool.vo.paper.DefaultQuestionUnitWrapper;
import cn.com.qmth.examcloud.tool.vo.user.User;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class QueryPaperStructTask {

    private final static Logger log = LoggerFactory.getLogger(QueryPaperStructTask.class);

    @Autowired
    private SysProperty sysProperty;

    @Autowired
    private CommonService commonService;

    public void start(User user, Long examId) {
        this.execute(user, examId);
    }

    private void execute(User user, Long examId) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", user.getKey());
        headers.put("token", user.getToken());

        List<CourseVO> courses = commonService.getExamCourseList(user, examId);
        log.info("examId:{}, 课程数为:{}", examId, courses.size());

        for (CourseVO course : courses) {
            List<ExtractConfigVO> extractConfigs = this.getExtractConfig(user, examId, course.getCourseCode());
            if (CollectionUtils.isEmpty(extractConfigs)) {
                // 若当前账号未配相关数据权限，则会取不到调卷规则数据，请更换账号！！
                log.info("examId:{}, courseId:{}, courseCode:{}, 未配置调卷规则！", examId, course.getCourseId(),
                        course.getCourseCode());
                continue;
            }

            for (ExtractConfigVO extractConfig : extractConfigs) {
                for (ExamPaperVO examPaper : extractConfig.getExamPaperList()) {
                    String basePaperId = examPaper.getPaper().getId();
                    GetPaperStructResp resp = this.getPaperStruct(examId, course.getCourseCode(),
                            examPaper.getGroupCode(), basePaperId);
                    System.out.println("\n========== ========== ==========");
                    System.out.println(
                            String.format("examId:%s courseId:%s courseCode:%s paperType:%s basePaperId:%s 试卷名称:%s",
                                    examId, course.getCourseId(), course.getCourseCode(), examPaper.getGroupCode(),
                                    basePaperId, resp.getDefaultPaper().getName()));
                    System.out.println("========== ========== ==========");
                    List<DefaultQuestionGroup> questionGroupList = resp.getDefaultPaper().getQuestionGroupList();

                    int index = 0;
                    for (int i = 0; i < questionGroupList.size(); i++) {
                        DefaultQuestionGroup questionGroup = questionGroupList.get(i);
                        List<DefaultQuestionStructureWrapper> questionWrapperList = questionGroup.getQuestionWrapperList();

                        for (int j = 0; j < questionWrapperList.size(); j++) {
                            DefaultQuestionStructureWrapper questionStructure = questionWrapperList.get(j);
                            List<DefaultQuestionUnitWrapper> questionUnitWrapperList = questionStructure.getQuestionUnitWrapperList();

                            for (int k = 0; k < questionUnitWrapperList.size(); k++) {
                                DefaultQuestionUnitWrapper questionUnit = questionUnitWrapperList.get(k);

                                System.out.println(String.format("试题ID:%s %s%s-%s", questionStructure.getQuestionId(),
                                        questionUnit.getQuestionType().getDesc(), i + 1, ++index));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询某个考试课程的调卷规则配置
     */
    private List<ExtractConfigVO> getExtractConfig(User user, Long examId, String courseCode) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", user.getKey());
        headers.put("token", user.getToken());

        Map<String, String> params = new HashMap<>();
        params.put("examId", String.valueOf(examId));
        params.put("courseNo", courseCode);

        String url = user.getServerUrl() + "/api/ecs_ques/findPageExtractConfig/1/10";
        String json = HttpHelper.get(url, headers, params);

        Pager<ExtractConfigVO> page = new JsonMapper().parseJson(json, new TypeReference<Pager<ExtractConfigVO>>() {

        });
        return page.getContent();
    }

    /**
     * 获取某个考试课程原卷的试卷结构
     */
    private GetPaperStructResp getPaperStruct(Long examId, String courseCode, String paperType, String basePaperId) {
        long rootOrgId = sysProperty.getServerRootOrgId();
        String appId = sysProperty.getServerAppId();
        String secretKey = sysProperty.getServerSecretKey();
        long timestamp = System.currentTimeMillis();
        String accessToken = SignUtils.accessToken(rootOrgId, appId, secretKey, timestamp);

        Map<String, String> headers = new HashMap<>();
        headers.put("rootOrgId", String.valueOf(rootOrgId));
        headers.put("appId", appId);
        headers.put("access_token", accessToken);
        headers.put("timestamp", String.valueOf(timestamp));

        Map<String, Object> params = new HashMap<>();
        params.put("examId", examId);
        params.put("courseCode", courseCode);
        params.put("paperType", paperType);
        params.put("basePaperId", basePaperId);

        String httpUrl = "https://" + sysProperty.getServerUrl();
        String url = httpUrl + "/api/exchange/outer/question/getPaperStruct";
        String json = HttpHelper.post(url, headers, params);
        // System.out.println(json);

        return new JsonMapper().parseJson(json, GetPaperStructResp.class);
    }

}
