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

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.TaskService;
import cn.com.qmth.examcloud.tool.service.batch_import_exam_student.vo.ExamStudentInfo;
import cn.com.qmth.examcloud.tool.service.batch_import_exam_student.vo.ExamStudentInfoListener;
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.alibaba.excel.EasyExcel;
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 BatchImportExamStudentTask implements TaskService {

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

    @Autowired
    private SysProperty sysProperty;

    @Autowired
    private CommonService commonService;

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

        this.execute(user, task);
    }

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

        Long examId = jsonParams.get("examId").asLong();
        String dataFilePath = jsonParams.get("dataFilePath").asText();
        if (StringUtils.isBlank(dataFilePath)) {
            throw new StatusException("参数dataFilePath不能为空！");
        }

        ExamStudentInfoListener dataListener = new ExamStudentInfoListener();
        EasyExcel.read(dataFilePath, ExamStudentInfo.class, dataListener).sheet().doRead();
        List<ExamStudentInfo> dataList = dataListener.getList();

        int total = dataList.size();
        log.info("共{}条数据！examId:{}", total, examId);
        long start = System.currentTimeMillis();

        // 检验数据
        Map<String, Long> orgMaps = new HashMap<>();
        Map<String, Long> courseMaps = new HashMap<>();
        List<String> errMessages = new ArrayList<>();
        for (int i = 0; i < total; i++) {
            ExamStudentInfo examStudent = dataList.get(i);
            examStudent.setExamId(examId);

            if (StringUtils.isBlank(examStudent.getStudentName())) {
                errMessages.add("第" + (i + 1) + "条 姓名不能为空！");
            } else {
                examStudent.setStudentName(examStudent.getStudentName().trim());
            }

            if (StringUtils.isBlank(examStudent.getStudentCode())) {
                errMessages.add("第" + (i + 1) + "条 学号不能为空！");
            } else {
                examStudent.setStudentCode(examStudent.getStudentCode().trim());
            }

            if (StringUtils.isBlank(examStudent.getIdentityNumber())) {
                errMessages.add("第" + (i + 1) + "条 身份证号不能为空！");
            } else {
                examStudent.setIdentityNumber(examStudent.getIdentityNumber().trim());
            }

            if (StringUtils.isBlank(examStudent.getOrgCode())) {
                errMessages.add("第" + (i + 1) + "条 机构代码不能为空！");
            } else {
                examStudent.setOrgCode(examStudent.getOrgCode().trim());
            }

            if (StringUtils.isBlank(examStudent.getCourseCode())) {
                errMessages.add("第" + (i + 1) + "条 课程代码不能为空！");
            } else {
                examStudent.setCourseCode(examStudent.getCourseCode().trim());
            }

            Long orgId = orgMaps.get(examStudent.getOrgCode());
            if (orgId == null) {
                orgId = commonService.queryOrgIdByCode(loginUser, examStudent.getOrgCode());
                if (orgId == null) {
                    errMessages.add("第" + (i + 1) + "条 机构代码不正确！" + examStudent.getOrgCode());
                } else {
                    orgMaps.put(examStudent.getOrgCode(), orgId);
                }
            }
            examStudent.setOrgId(orgId);

            Long courseId = courseMaps.get(examStudent.getCourseCode());
            if (courseId == null) {
                courseId = commonService.queryCourseIdByCode(loginUser, examStudent.getCourseCode());
                if (courseId == null) {
                    errMessages.add("第" + (i + 1) + "条 课程代码不正确！" + examStudent.getCourseCode());
                } else {
                    courseMaps.put(examStudent.getCourseCode(), courseId);
                }
            }
            examStudent.setCourseId(courseId);
        }

        if (!errMessages.isEmpty()) {
            throw new StatusException(StringUtils.join(errMessages, "\n"));
        }

        int failCount = 0;
        for (int i = 0; i < total; i++) {
            ExamStudentInfo examStudent = dataList.get(i);

            try {
                this.saveStudent(loginUser, examStudent);
                log.info("共{}条 第{}条 已执行！{}", total, i + 1, examStudent.getStudentCode());
            } catch (Exception e) {
                failCount++;
                log.error("共{}条 第{}条 执行失败！{} err:{}", total, i + 1, examStudent.getStudentCode(), e.getMessage());
            }
        }

        long cost = (System.currentTimeMillis() - start) / 1000;
        String msg = String.format("共%s条 成功%s条 失败%s条 耗时{}秒", total, total - failCount, failCount, cost);
        log.info(msg);
        task.setDescription(msg);
    }

    private void saveStudent(User loginUser, ExamStudentInfo examStudent) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

        Map<String, Object> params = new HashMap<>();
        params.put("examId", examStudent.getExamId());
        params.put("courseId", examStudent.getCourseId());
        params.put("orgId", examStudent.getOrgId());
        params.put("studentName", examStudent.getStudentName());
        params.put("studentCode", examStudent.getStudentCode());
        params.put("identityNumber", examStudent.getIdentityNumber());
        params.put("specialtyName", examStudent.getSpecialtyName());
        // 其它字段 暂略...

        String url = loginUser.getServerUrl() + "/api/ecs_exam_work/exam_student";
        String result = HttpHelper.put(url, headers, params);
        // log.info(result);

        JsonNode value = new JsonMapper().getNode(result);
        if (value == null || !value.has("id")) {
            // 创建成功会返回ID，否则失败
            throw new StatusException(result);
        }
    }

}
