package cn.com.qmth.examcloud.core.questions.api.provider;

import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.base.CommonUtils;
import cn.com.qmth.examcloud.core.questions.dao.ExtractConfigRepo;
import cn.com.qmth.examcloud.core.questions.dao.PaperRepo;
import cn.com.qmth.examcloud.core.questions.dao.QuesRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.Course;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExtractConfig;
import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
import cn.com.qmth.examcloud.global.api.HandleSyncCloudService;
import cn.com.qmth.examcloud.global.api.request.*;
import cn.com.qmth.examcloud.global.api.response.*;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author weiwenhai
 * @date 2018.10.11
 * @company qmth
 * @description 同步课程
 * @code 018
 */
@Transactional
@RestController
@RequestMapping("${$rmp.cloud.questions}" + "dataSync")
public class HandleSyncCloudServiceProvider extends ControllerSupport implements HandleSyncCloudService {

    private static final long serialVersionUID = -2121791220624238299L;

    @Autowired
    ExtractConfigRepo extractConfigRepo;

    @Autowired
    QuesRepo quesRepo;

    @Autowired
    PaperRepo paperRepo;

    @Autowired
    MongoTemplate mongoTemplate;

    @ApiOperation(value = "同步课程")
    @PostMapping("syncCourse")
    @Override
    public SyncCourseResp syncCourse(@RequestBody SyncCourseReq req) {
        String courseCode = req.getCode();
        Long rootOrgId = req.getRootOrgId();
        String courseName = req.getName();
        String courseLevel = req.getLevel();
        Boolean enable = req.getEnable();
        Long courseId = req.getId();
        if (StringUtils.isBlank(courseName)) {
            throw new StatusException("Q-018073", "courseName is null");
        }
        if (null == courseId) {
            throw new StatusException("Q-018076", "courseId is null");
        }
        if (StringUtils.isBlank(courseLevel)) {
            throw new StatusException("Q-018079", "courseLevel is null");
        }
        if (null == rootOrgId) {
            throw new StatusException("Q-018082", "rootOrgId is null");
        }
        //同步调卷规则
        List<ExtractConfig> extractConfigs = extractConfigRepo.findByCourseCodeAndOrgId(courseCode, rootOrgId.toString());
        if (extractConfigs != null && extractConfigs.size() > 0) {
            int i = 0;
            for (ExtractConfig extractConfig : extractConfigs) {
                extractConfig.setCourseName(courseName);
                Course course = extractConfig.getCourse();
                if (course != null) {
                    course.setName(courseName);
                    course.setLevel(courseLevel);
                    course.setEnable(enable.toString());
                    course.setUpdateTime(CommonUtils.getCurDateTime());
                    extractConfig.setCourse(course);
                } else {
                    Course tempCourse = new Course();
                    tempCourse.setCode(courseCode);
                    tempCourse.setName(courseName);
                    tempCourse.setLevel(courseLevel);
                    tempCourse.setEnable(enable.toString());
                    tempCourse.setOrgId(rootOrgId.toString());
                    tempCourse.setCreateTime(CommonUtils.getCurDateTime());
                    extractConfig.setCourse(tempCourse);
                }
                i++;
            }
            extractConfigRepo.saveAll(extractConfigs);
            LOGGER.debug("调卷规则同步完成，已经同步数量：" + i);
        }
        //同步试卷
        List<Paper> papers = paperRepo.findByCourseNoAndOrgId(courseCode, rootOrgId.toString());
        if (papers != null && papers.size() > 0) {
            int i = 0;
            for (Paper paper : papers) {
                Course course = paper.getCourse();
                if (course != null) {
                    course.setName(courseName);
                    course.setLevel(courseLevel);
                    course.setEnable(enable.toString());
                    course.setUpdateTime(CommonUtils.getCurDateTime());
                    paper.setCourse(course);
                } else {
                    Course tempCourse = new Course();
                    tempCourse.setCode(courseCode);
                    tempCourse.setName(courseName);
                    tempCourse.setLevel(courseLevel);
                    tempCourse.setEnable(enable.toString());
                    tempCourse.setOrgId(rootOrgId.toString());
                    tempCourse.setCreateTime(CommonUtils.getCurDateTime());
                    paper.setCourse(tempCourse);
                }
                i++;
            }
            paperRepo.saveAll(papers);
            LOGGER.debug("试卷同步完成，已经同步数量：" + i);
        }
        //同步试题
        Query query = new Query();
        query.addCriteria(Criteria.where("orgId").is(rootOrgId.toString()));
        query.addCriteria(Criteria.where("course.code").is(courseCode));
        List<Question> questions = this.mongoTemplate.find(query, Question.class);
        if (questions != null && questions.size() > 0) {
            int i = 0;
            for (Question question : questions) {
                Course course = question.getCourse();
                if (course != null) {
                    course.setName(courseName);
                    course.setLevel(courseLevel);
                    course.setEnable(enable.toString());
                    course.setUpdateTime(CommonUtils.getCurDateTime());
                    question.setCourse(course);
                } else {
                    Course tempCourse = new Course();
                    tempCourse.setCode(courseCode);
                    tempCourse.setName(courseName);
                    tempCourse.setLevel(courseLevel);
                    tempCourse.setEnable(enable.toString());
                    tempCourse.setOrgId(rootOrgId.toString());
                    tempCourse.setCreateTime(CommonUtils.getCurDateTime());
                    question.setCourse(tempCourse);
                }
                i++;
            }
            quesRepo.saveAll(questions);
            LOGGER.debug("试题同步完成，已经同步数量：" + i);
        }
        SyncCourseResp resp = new SyncCourseResp();
        return resp;
    }

    @Override
    public SyncOrgResp syncOrg(SyncOrgReq req) {
        return null;
    }

    @Override
    public SyncStudentResp syncStudent(SyncStudentReq req) {
        return null;
    }

    @Override
    public SyncExamStudentResp syncExamStudent(SyncExamStudentReq req) {
        return null;
    }

    @Override
    public SyncSpecialtyResp syncSpecialty(SyncSpecialtyReq req) {
        return null;
    }

    @ApiOperation(value = "同步考试")
    @PostMapping("syncExam")
    @Override
    public SyncExamResp syncExam(@RequestBody SyncExamReq req) {
        Long rootOrgId = req.getRootOrgId();
        Long id = req.getId();
        String name = req.getName();
        String examType = req.getExamType();
        if (StringUtils.isBlank(name)) {
            throw new StatusException("Q-018213", "name is null");
        }
        if (null == id) {
            throw new StatusException("Q-018216", "id is null");
        }
        if (null == rootOrgId) {
            throw new StatusException("Q-018219", "rootOrgId is null");
        }
        if (StringUtils.isBlank(examType)) {
            throw new StatusException("Q-018223", "examType is null");
        }
        //同步调卷规则
        Query query = new Query();
        query.addCriteria(Criteria.where("orgId").is(rootOrgId.toString()));
        query.addCriteria(Criteria.where("examId").is(id));
        List<ExtractConfig> extractConfigs = this.mongoTemplate.find(query, ExtractConfig.class);
        LOGGER.debug("调卷规则总数量：" + extractConfigs.size());
        if (extractConfigs != null && extractConfigs.size() > 0) {
            int i = 0;
            for (ExtractConfig extractConfig : extractConfigs) {
                i++;
                extractConfig.setExamName(name);
                extractConfig.setExamType(examType);
                extractConfig.setExamType(examType);
            }
            extractConfigRepo.saveAll(extractConfigs);
            LOGGER.debug("调卷规则同步完成，已经同步数量：" + i);
        }
        SyncExamResp resp = new SyncExamResp();
        return resp;
    }

    @Override
    public SyncUserResp syncUser(SyncUserReq req) {
        return null;
    }

}
