package com.qmth.jkserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.jkserver.dao.ExamStudentAdditionalDao;
import com.qmth.jkserver.model.ExamStudentAdditional;
import com.qmth.jkserver.service.ExamStudentAdditionalService;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 考生附加信息
 *
 * @author tianjun
 */
@Service
@Scope(proxyMode = ScopedProxyMode.INTERFACES)
public class ExamStudentAdditionalServiceImpl extends ServiceImpl<ExamStudentAdditionalDao, ExamStudentAdditional> implements ExamStudentAdditionalService {

    @Resource
    private ExamStudentAdditionalDao examStudentAdditionalDao;

//    @Autowired
//    private MongoOperations mongoTemplate;

    @Resource
    @Lazy
    ExamStudentAdditionalService examStudentAdditionalService;

    @Override
    public List<ExamStudentAdditional> findByExamCode(String examCode) {
        List<ExamStudentAdditional> examStudentAdditionals = examStudentAdditionalDao.findByExamCode(examCode);
        return examStudentAdditionals;
    }

    //返回所有的科目code以及科目的名称
    @Override
    public Map<String, String> distinctCourse(String examCode) {
//        AggregationOptions aggregationOptions = new AggregationOptions.Builder().allowDiskUse(true).build();
        Map<String, String> map = new LinkedHashMap<String, String>();
        long skip = 0;
        long limit = 10000;
        boolean over = false;
        while (!over) {
//            TypedAggregation<ExamStudentAdditional> aggregation = Aggregation.newAggregation(ExamStudentAdditional.class,
//                    Aggregation.match(Criteria.where("examCode").is(examCode)),
//                    Aggregation.project("courseCode", "courseName"),
//                    Aggregation.group("courseCode", "courseName").count().as("count"),
//                    Aggregation.project("courseCode", "courseName"),
//                    Aggregation.sort(new Sort(Direction.ASC, "courseCode")),
//                    Aggregation.skip(skip),
//                    Aggregation.limit(limit)
//            ).withOptions(aggregationOptions);
//            AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(aggregation, BasicDBObject.class);
//            List<BasicDBObject> list = result.getMappedResults();
            IPage<Map> list = examStudentAdditionalDao.findByExamCodeByPage(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(skip, limit), examCode);
            if (list.getRecords().size() < limit) {
                over = true;
            }
            if (list.getRecords().size() > 0) {
                for (Map basicDBObject : list.getRecords()) {
                    map.put((String) basicDBObject.get("courseCode"), (String) basicDBObject.get("courseName"));
                }
            }
            skip = skip + limit;
        }
        return map;
    }

    @Override
    public ExamStudentAdditional saveService(ExamStudentAdditional examStudentAdditional) {
        this.saveOrUpdate(examStudentAdditional);
        return examStudentAdditional;
    }

    @Override
    public List<Map> findDistinctStudent(String examCode) {
//        AggregationOptions aggregationOptions = new AggregationOptions.Builder().allowDiskUse(true).build();
//        List<BasicDBObject> list = new ArrayList<BasicDBObject>();
        List<Map> list = new ArrayList<Map>();
        long skip = 0;
        long limit = 10000;
        boolean over = false;
        while (!over) {
//            TypedAggregation<ExamStudentAdditional> aggregation = Aggregation.newAggregation(
//                    ExamStudentAdditional.class,
//                    Aggregation.match(Criteria.where("examCode").is(examCode)),
//                    Aggregation.project("examCode", "studentId"),
//                    Aggregation.group("examCode", "studentId").count().as("count"),
//                    Aggregation.project("examCode", "studentId", "count"),
//                    Aggregation.sort(Direction.ASC, "studentId"),
//                    Aggregation.skip(skip),
//                    Aggregation.limit(limit)
//            ).withOptions(aggregationOptions);
//            AggregationResults<BasicDBObject> results = mongoTemplate.aggregate(aggregation, ExamStudentAdditional.class, BasicDBObject.class);
            IPage<Map> examStudentAdditionalMap = examStudentAdditionalDao.findDistinctStudent(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(skip, limit), examCode);
            if (examStudentAdditionalMap.getRecords().size() < limit) {
                over = true;
            }
            list.addAll(examStudentAdditionalMap.getRecords());
            skip = skip + limit;
        }
        return list;

    }

    @Override
    public ExamStudentAdditional findByExamCodeAndTicketNo(String examCode, String ticketNo) {
//        Query query = new Query();
//        query.addCriteria(Criteria.where("examCode").is(examCode));
//        query.addCriteria(Criteria.where("studentId").is(ticketNo));
//        List<ExamStudentAdditional> additionals = mongoTemplate.find(query, ExamStudentAdditional.class);
        QueryWrapper<ExamStudentAdditional> examStudentAdditionalQueryWrapper = new QueryWrapper<>();
        examStudentAdditionalQueryWrapper.lambda().eq(ExamStudentAdditional::getExamCode, examCode)
                .eq(ExamStudentAdditional::getStudentId, ticketNo);
        List<ExamStudentAdditional> additionals = examStudentAdditionalService.list(examStudentAdditionalQueryWrapper);
        return additionals.size() > 0 ? additionals.get(0) : null;
    }

    @Override
    public ExamStudentAdditional find(String examCode, String ticketNo, String courseCode) {
//        Query query = new Query();
//        query.addCriteria(Criteria.where("examCode").is(examCode));
//        query.addCriteria(Criteria.where("studentId").is(ticketNo));
//        query.addCriteria(Criteria.where("courseCode").is(courseCode));
//        List<ExamStudentAdditional> additionals = mongoTemplate.find(query, ExamStudentAdditional.class);
        QueryWrapper<ExamStudentAdditional> examStudentAdditionalQueryWrapper = new QueryWrapper<>();
        examStudentAdditionalQueryWrapper.lambda().eq(ExamStudentAdditional::getExamCode, examCode)
                .eq(ExamStudentAdditional::getStudentId, ticketNo)
                .eq(ExamStudentAdditional::getCourseCode, courseCode);
        List<ExamStudentAdditional> additionals = examStudentAdditionalService.list(examStudentAdditionalQueryWrapper);
        return additionals.size() > 0 ? additionals.get(0) : null;
    }

    @Override
    public Set<String> findUtestDistinctStudent(String examCode) {
        Set<String> studentIds = new LinkedHashSet<String>();
//        DBObject query = new BasicDBObject("exam_code", examCode);
//        DBObject projection = new BasicDBObject("student_id", 1);
//        DBCursor dbCursor = mongoTemplate.getCollection("jk_exam_student_additional").find(query, projection).sort(new BasicDBObject("student_id", 1));
        List<ExamStudentAdditional> examStudentAdditionalList = examStudentAdditionalDao.findByExamCodeAndStudentId(examCode);
//        while (dbCursor.hasNext()) {
//            DBObject dbObject = dbCursor.next();
//            if (dbObject.get("student_id") != null) {
//                studentIds.add(dbObject.get("student_id").toString());
//            }
//        }
        for (ExamStudentAdditional examStudentAdditional : examStudentAdditionalList) {
            studentIds.add(examStudentAdditional.getStudentId().toString());
        }
        return studentIds;
    }

    @Override
    public Map<String, String> findUtestDistinctCourse(String examCode) {
        Map<String, String> courses = new LinkedHashMap<String, String>();
//        DBObject query = new BasicDBObject("exam_code", examCode);
//        DBObject projection = new BasicDBObject("course_code", 1);
//        projection.put("course_name", 1);
//        DBCursor dbCursor = mongoTemplate.getCollection("jk_exam_student_additional").find(query, projection).sort(new BasicDBObject("course_code", 1));
        List<ExamStudentAdditional> examStudentAdditionalList = examStudentAdditionalDao.findByExamCodeAndCourseCodeAndName(examCode);
//        while (dbCursor.hasNext()) {
//            DBObject dbObject = dbCursor.next();
//            if (dbObject.get("course_code") != null) {
//                String courseCode = dbObject.get("course_code").toString();
//                String courseName = dbObject.get("course_name").toString();
//                courses.put(courseCode, courseName);
//            }
//        }
        for (ExamStudentAdditional examStudentAdditional : examStudentAdditionalList) {
            courses.put(examStudentAdditional.getCourseCode(), examStudentAdditional.getCourseName());
        }
        return courses;
    }
}
