package com.qxgmat.service;

import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
import com.nuliji.tools.PageResult;
import com.nuliji.tools.Transform;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.exception.SystemException;
import com.nuliji.tools.mybatis.Example;
import com.qxgmat.data.constants.enums.SettingKey;
import com.qxgmat.data.constants.enums.logic.ExerciseLogic;
import com.qxgmat.data.dao.ExercisePaperMapper;
import com.qxgmat.data.dao.entity.ExercisePaper;
import com.qxgmat.data.dao.entity.Question;
import com.qxgmat.data.dao.entity.UserPaper;
import com.qxgmat.data.dao.entity.UserReport;
import com.qxgmat.data.relation.ExercisePaperRelationMapper;
import com.qxgmat.data.relation.UserPaperRelationMapper;
import com.qxgmat.data.relation.UserReportRelationMapper;
import com.qxgmat.data.relation.entity.QuestionNoRelation;
import com.qxgmat.data.relation.entity.UserExercisePaperRelation;
import com.qxgmat.service.inline.QuestionService;
import com.qxgmat.service.inline.UserReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

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

    @Resource
    private ExercisePaperMapper exercisePaperMapper;

    @Resource
    private ExercisePaperRelationMapper exercisePaperRelationMapper;

    @Resource
    private QuestionService questionService;

    @Resource
    private UserPaperRelationMapper userPaperRelationMapper;

    @Resource
    private UserPaperService userPaperService;

    @Resource
    private UserReportRelationMapper userReportRelationMapper;

    @Resource
    private UserReportService userReportService;

    public void initUserPaper(UserPaper userPaper, Integer id){
        ExercisePaper paper = get(id);
        userPaper.setTitle(paper.getTitle());
        userPaper.setQuestionNoIds(paper.getQuestionNoIds());
    }

    /**
     * 获取考点分组所有可用考点信息
     * @return
     */
    public List<String> groupPlace(){
        List<ExercisePaper> p = exercisePaperRelationMapper.groupPlace();

        Collection ids = Transform.getIds(p, ExercisePaper.class, "id");

        // 获取详细数据
        List<ExercisePaper> list = select(ids);

        List<String> places = new ArrayList<>();
        for(ExercisePaper paper : list){
            places.add(paper.getLogicExtend());
        }
        return places;
    }
    /**
     * 查找用户作业, 并关联用户最后一次作业
     * @param page
     * @param size
     * @param structId
     * @param userId
     * @param logic
     * @param logicExtend
     * @param times
     * @return
     */
    public PageResult<UserExercisePaperRelation> list(int page, int size, Number structId, Number userId, ExerciseLogic logic, String logicExtend, Integer times){
        String logicKey = logic != null ? logic.key : "";
        Page<UserPaper> p = page(()->{
            userPaperRelationMapper.listExercisePaper(structId, userId, logicKey, logicExtend, times);
        },page, size);

        Collection ids = Transform.getIds(p, UserPaper.class, "id");

        // 获取详细数据
        List<UserPaper> list = userPaperService.select(ids);
        List<UserExercisePaperRelation> pr = Transform.convert(list, UserExercisePaperRelation.class);

        // 获取最后一次作业结果
        List<UserReport> reportList = userReportRelationMapper.listLast(ids);
        Collection reportIds = Transform.getIds(reportList, UserReport.class, "id");
        Transform.replace(reportList, userReportService.select(reportIds), UserReport.class, "id");

        Transform.combine(p, reportList, UserExercisePaperRelation.class, "id", "report", UserReport.class, "paperId");

        return new PageResult<>(pr, p.getTotal());
    }

    public ExercisePaper add(ExercisePaper paper){
        int result = insert(exercisePaperMapper, paper);
        paper = one(exercisePaperMapper, paper.getId());
        if(paper == null){
            throw new SystemException("组卷添加失败");
        }
        return paper;
    }

    public ExercisePaper edit(ExercisePaper paper){
        ExercisePaper in = one(exercisePaperMapper, paper.getId());
        if(in == null){
            throw new ParameterException("组卷不存在");
        }
        int result = update(exercisePaperMapper, paper);
        return paper;
    }

    public boolean delete(Number id){
        ExercisePaper in = one(exercisePaperMapper, id);
        if(in == null){
            throw new ParameterException("组卷不存在");
        }
        int result = delete(exercisePaperMapper, id);
        return result > 0;
    }

    public ExercisePaper get(Number id){
        ExercisePaper in = one(exercisePaperMapper, id);

        if(in == null){
            throw new ParameterException("组卷不存在");
        }
        return in;
    }

    public Page<ExercisePaper> select(int page, int pageSize, String keyword){
        Example example = new Example(ExercisePaper.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("status", 1)
        );
        if (keyword != null)
            example.and(
                    example.createCriteria()
                            .andLike("title", keyword)
            );
        return select(exercisePaperMapper, example, page, pageSize);
    }

    public List<ExercisePaper> select(Collection ids){
        return select(exercisePaperMapper, ids);
    }

}
