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

import cn.com.qmth.examcloud.tool.cache.LoginSessionManager;
import cn.com.qmth.examcloud.tool.config.SysProperty;
import cn.com.qmth.examcloud.tool.entity.TaskEntity;
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.utils.HttpHelper;
import cn.com.qmth.examcloud.tool.utils.JsonMapper;
import cn.com.qmth.examcloud.tool.utils.StatusException;
import cn.com.qmth.examcloud.tool.vo.user.User;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class ConfigExamPaperTask {

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

    @Autowired
    private CommonService commonService;

    @Autowired
    private SysProperty sysProperty;

    public void start(TaskEntity task) {
        JsonNode jsonParams = new JsonMapper().getNode(task.getParams());
        if (jsonParams == null) {
            throw new StatusException("任务参数解析错误！");
        }

        User user = LoginSessionManager.getLoginSession(task.getUserToken());
        if (user == null) {
            throw new StatusException("用户未登录！");
        }

        this.execute(user, jsonParams);
    }

    private void execute(User user, JsonNode jsonParams) {
        Long examId = jsonParams.get("examId").asLong(0L);
        String courseCodes = jsonParams.get("courseCodes").asText("");
        log.info("examId = {}, courseCodes = {}", examId, courseCodes);

        // 待处理的课程列表（未指定课程则按考试的全部课程）
        List<CourseVO> todoCourses;
        List<CourseVO> courses = commonService.getExamCourseList(user, examId);
        if (StringUtils.isNotBlank(courseCodes)) {
            todoCourses = new ArrayList<>();
            String[] courseCodeList = StringUtils.split(courseCodes, ",");
            for (String courseCode : courseCodeList) {
                for (CourseVO vo : courses) {
                    if (vo.getCourseCode().equals(courseCode)) {
                        todoCourses.add(vo);
                    }
                }
            }
        } else {
            todoCourses = courses;
        }
        log.info("examId:{}, 待处理的课程数为:{}", examId, todoCourses.size());

        List<String> errors = new ArrayList<>();
        for (CourseVO course : todoCourses) {
            // 按考试课程逐个处理
            try {
                this.process(user, examId, course);
            } catch (Exception e) {
                errors.add(String.format("课程代码:%s  处理失败:%s", course.getCourseCode(), e.getMessage()));
            }
        }

        if (!errors.isEmpty()) {
            String err = StringUtils.join(errors, " \n");
            log.error(err);
            throw new RuntimeException(err);
        }
    }

    public void process(User user, Long examId, CourseVO course) {
        // 按课程逐个配置考试调卷规则
        Map<String, String> headers = new HashMap<>();
        headers.put("key", user.getKey());
        headers.put("token", user.getToken());

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

        final String url = user.getServerUrl() + "/api/ecs_ques/extract_config/randompaper/save";
        HttpHelper.post(url, headers, params);
        log.info("examId:{} courseId:{} courseCode:{} 已处理！", examId, course.getCourseId(), course.getCourseCode());
    }

}
