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

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.service.update_correct_answer_and_re_fix_score.vo.ExamStudentVO;
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.Pager;
import cn.com.qmth.examcloud.tool.vo.user.User;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.collections4.CollectionUtils;
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 UpdateCorrectAnswerAndReFixScoreTask {

    private final static Logger log = LoggerFactory.getLogger(UpdateCorrectAnswerAndReFixScoreTask.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());

        for (CourseVO course : todoCourses) {
            // 按考试课程逐个处理
            this.process(user, examId, course);
        }
    }

    public void process(User user, Long examId, CourseVO course) {
        List<ExamStudentVO> examStudents = this.getExamStudentList(user, examId, course.getCourseId());

        int index = 0, total = examStudents.size();
        for (ExamStudentVO examStudent : examStudents) {
            // 按考生逐个更新正确答案并重新算分
            this.fix(user, examId, course.getCourseId(), examStudent.getExamStudentId());

            index++;
            if (index % 100 == 0) {
                float rate = index * 100f / total;
                log.info("examId:{} courseId:{} courseCode:{} total:{} index:{} 进度:{}%", examId, course.getCourseId(),
                        course.getCourseCode(), total, index, rate);
            }
        }

        log.info("examId:{} courseId:{} courseCode:{} total:{} 已处理！", examId, course.getCourseId(),
                course.getCourseCode(), total);

        examStudents.clear();
    }

    private void fix(User user, Long examId, Long courseId, Long examStudentId) {
        Map<String, String> params = new HashMap<>();
        params.put("examId", String.valueOf(examId));
        params.put("courseId", String.valueOf(courseId));
        params.put("examStudentId", String.valueOf(examStudentId));

        Map<String, String> headers = new HashMap<>();
        headers.put("key", user.getKey());
        headers.put("token", user.getToken());

        String url = user.getServerUrl() + "/api/ecs_oe_admin/exam/score/updateCorrectAnswerAndReFixScore";
        HttpHelper.get(url, headers, params);
    }

    /**
     * 获取网考考生列表
     */
    private List<ExamStudentVO> getExamStudentList(User user, Long examId, Long courseId) {
        Map<String, Object> params = new HashMap<>();
        params.put("examId", examId);
        params.put("courseId", courseId);
        params.put("pageSize", 500);

        Map<String, String> headers = new HashMap<>();
        headers.put("key", user.getKey());
        headers.put("token", user.getToken());

        String url = user.getServerUrl() + "/api/ecs_oe_admin/exam/student/simple/list";
        List<ExamStudentVO> all = new ArrayList<>();
        JsonMapper jsonMapper = new JsonMapper();

        int sum = 0, pageNo = 0;
        while (true) {
            params.put("pageNo", ++pageNo);
            String json = HttpHelper.post(url, headers, params);

            Pager<ExamStudentVO> page = jsonMapper.parseJson(json, new TypeReference<Pager<ExamStudentVO>>() {

            });
            if (page == null || CollectionUtils.isEmpty(page.getContent())) {
                break;
            }
            all.addAll(page.getContent());

            sum += page.getContent().size();
            float rate = sum * 100f / page.getTotalElements();
            log.info("examId:{} courseId:{} 已获取考生数:{} 进度:{}%", examId, courseId, sum, rate);
        }

        return all;
    }

}
