package com.qxgmat.service.extend;

import com.nuliji.tools.AbstractService;
import com.nuliji.tools.Transform;
import com.nuliji.tools.exception.ParameterException;
import com.qxgmat.data.constants.enums.module.*;
import com.qxgmat.data.dao.entity.*;
import com.qxgmat.data.relation.entity.UserPreviewPaperRelation;
import com.qxgmat.service.UserPaperService;
import com.qxgmat.service.inline.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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

@Service
public class PreviewService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(PreviewService.class);

    @Resource
    private PreviewPaperService previewPaperService;

    @Resource
    private UserReportService userReportService;

    @Resource
    private UserPaperService userPaperService;

    @Resource
    private UserOrderRecordService userOrderRecordService;

    @Resource
    private CourseService courseService;

    @Resource
    private CourseNoService courseNoService;

    @Resource
    private PreviewAssignService previewAssignService;

    @Resource
    private UserCourseAppointmentService userCourseAppointmentService;

    @Resource
    private UserCourseProgressService userCourseProgressService;

    @Resource
    private UserCourseService userCourseService;

    /**
     * 获取用户分组作业列表
     * @param userId
     * @param top
     * @return
     */
    public Map<Object, Collection<UserPreviewPaperRelation>> groupByCourseId(Integer userId, Collection recordIds, Integer top){
        Map<Object, Collection<UserPreviewPaperRelation>> relationMap = new HashMap<>();
        for(Object id : recordIds){
            Integer recordId = (Integer)id;
            relationMap.put(recordId, list(1, top, userId, recordId, null, 0));
        }
        return relationMap;
    }

    /**
     * 返回用户的预习作业列表
     * @param recordId
     * @param userId
     * @param endTime
     * @param times
     * @return
     */
    public List<UserPreviewPaperRelation> list(int page, int size, Integer recordId, Integer userId, String endTime, Integer times){
        // 根据不同的课程,执行不同的查询方案
        UserOrderRecord record = userOrderRecordService.get(recordId);
        if (record == null){
            throw new ParameterException("记录不存在");
        }
        if (!record.getUserId().equals(userId)){
            throw new ParameterException("记录不存在");
        }
        if (!record.getProductType().equals(ProductType.COURSE.key)){
            throw new ParameterException("记录不存在");
        }
        Course course = courseService.get(record.getProductId());
        CourseModule courseModule = CourseModule.ValueOf(course.getCourseModule());
        List<PreviewAssign> previewAssignList = new ArrayList<>(0);
        switch(courseModule){
            case VS:
                // 查询记录对应预约情况
                List<UserCourseAppointment> appointmentList = userCourseAppointmentService.listByRecord(recordId);
                Collection appointmentIds = Transform.getIds(appointmentList, UserCourseAppointment.class, "id");
                previewAssignList = previewAssignService.listByAppointment(page, size, course.getId(), appointmentIds, userId, endTime, times);
                break;
            case ONLINE:
                // 查询记录对应时间段内
                previewAssignList = previewAssignService.listByTime(page, size, course.getId(), record.getTimeId(), userId, endTime, times);
                replaceTitle(previewAssignList);
                break;
            case VIDEO:
                // 获取课时,并关联当前记录的paper
                if (endTime != null){
                    // 无论列表还是卡片,都只显示2条
                    size = 2;
                    page = 1;
                    List<CourseNo> courseNoList = courseNoService.allCourse(course.getId());
                    // 查询课时进度
                    List<UserCourseProgress> progressList =userCourseProgressService.listCourse(record.getId(), course.getId());
                    Map progressMap = Transform.getMap(progressList, UserCourseProgress.class, "courseNoId");

                    Collections.reverse(courseNoList);
                    int min = 1;
                    for(CourseNo no : courseNoList){
                        // 如果进度不过半,按当前课时+下一课时
                        // 如果进度过半,下2次课时
                        UserCourseProgress progress = (UserCourseProgress)progressMap.get(no.getId());
                        if(progress == null) continue;
                        if (progress.getProgress() > 50) {
                            min = no.getNo() + 1;
                        }else{
                            min = no.getNo();
                        }
                        break;
                    }
                    int max = min+size -1;
                    int finalMin = min;
                    List<CourseNo> select = courseNoList.stream().filter(row->row.getNo() >= finalMin && row.getNo()<=max).collect(Collectors.toList());
                    previewAssignList = previewAssignService.listByCourseNos(course.getId(), getIds(select, CourseNo.class, "id"));
                }else{
                    previewAssignList = previewAssignService.listByCourse(page, size, course.getId(), userId, times);
                }
                replaceTitle(previewAssignList);
                break;
        }
        Collection assignIds = Transform.getIds(previewAssignList, PreviewAssign.class, "id");
        // 获取详细数据
        List<UserPaper> list = userPaperService.listWithOrigin(userId, PaperOrigin.PREVIEW, assignIds, recordId);
        Collection ids = Transform.getIds(list, UserPaper.class, "id");
        List<UserPreviewPaperRelation> pr = Transform.convert(list, UserPreviewPaperRelation.class);

        // 获取最后一次作业结果
        List<UserReport> reportList = userReportService.listWithLater(ids);

        Transform.combine(pr, reportList, UserPreviewPaperRelation.class, "id", "report", UserReport.class, "paperId");

        return pr;
    }

    /**
     * 根据试卷,获取当前关联的学习记录
     * @param assignId
     * @return
     */
    public Integer getRecord(Integer userId, Integer assignId){
        PreviewAssign assign = previewAssignService.get(assignId);
        if (assign == null){
            throw new ParameterException("记录不存在");
        }
        Course course = courseService.get(assign.getCourseId());
        CourseModule courseModule = CourseModule.ValueOf(course.getCourseModule());
        switch(courseModule){
            case VS:
                UserCourseAppointment appointment = userCourseAppointmentService.get(assign.getCourseAppointment());
                return appointment.getRecordId();
            case ONLINE:
                UserOrderRecord timeRecord = userOrderRecordService.getByUserAndTime(userId, assign.getCourseId(), assign.getCourseTime());
                return timeRecord.getId();
            case VIDEO:
                // 获取当前该课程记录
                UserCourse record = userCourseService.getCourseBase(userId, assign.getCourseId());
                return record != null ? record.getRecordId() : 0;
            default:
                return 0;
        }

    }

    private void replaceTitle(List<PreviewAssign> previewAssignList){
        Collection previewIds = Transform.getIds(previewAssignList, PreviewAssign.class, "paperId");
        List<PreviewPaper> paperList = previewPaperService.select(previewIds);
        Map paperTitle = Transform.getMap(paperList, PreviewPaper.class, "id", "title");
        Transform.combine(previewAssignList, paperTitle, PreviewAssign.class, "paperId", "title");
    }
}