package com.qxgmat.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
import com.nuliji.tools.PageResult;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.exception.SystemException;
import com.nuliji.tools.mybatis.Example;
import com.qxgmat.data.constants.enums.QuestionType;
import com.qxgmat.data.constants.enums.module.PaperModule;
import com.qxgmat.data.constants.enums.status.DirectionStatus;
import com.qxgmat.data.dao.UserPaperMapper;
import com.qxgmat.data.dao.entity.UserPaper;
import com.qxgmat.data.dao.entity.UserReport;
import com.qxgmat.data.relation.UserPaperRelationMapper;
import com.qxgmat.service.annotation.InitPaper;
import com.qxgmat.service.inline.UserReportService;
import com.qxgmat.util.annotation.Callback;
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.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserPaperService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(UserPaperService.class);
    protected boolean SOFT_FLAG = true;

    @Resource
    private UserPaperMapper userPaperMapper;

    @Resource
    private UserPaperRelationMapper userPaperRelationMapper;

    @Resource
    private UserReportService userReportService;

    /**
     * 获取报告列表：以paper进行分组
     * @param page
     * @param size
     * @param userId
     * @param module
     * @param type
     * @param startTime
     * @param endTime
     * @param order
     * @param direction
     * @return
     */
    public PageResult<UserPaper> list(int page, int size, Integer userId, PaperModule module, QuestionType type, String startTime, String endTime, String order, DirectionStatus direction){

        return new PageResult<>(null, 0);
    }

    public UserPaper getByPaper(Integer userId, PaperModule module, Integer paperId, InitPaper IInitPaper){
        // 查找对应的paper是否有，没有则添加
        Example example = new Example(UserPaper.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("userId", userId)
                        .andEqualTo("module", module.key)
                        .andEqualTo("module_id", paperId)
        );
        UserPaper paper = one(userPaperMapper, example);
        if (paper == null){
            paper = UserPaper.builder().userId(userId).module(module.key).moduleId(paperId).build();
            // 回调，根据模块更新设置
            IInitPaper.callback(paper, paperId);
            paper = add(paper);
        }
        return paper;
    }

    /**
     * 重置做题信息：不自动关联最后次做题记录
     * @param id
     * @return
     */
    public Boolean reset(Integer id, Integer userId){
        Example example = new Example(UserPaper.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("id", id)
                        .andEqualTo("userId", userId)
        );
        return update(userPaperMapper, example, UserPaper.builder().isReset(1).build()) > 0;
    }

    /**
     * 累加做题记录到paper
     * @param report
     */
    public void accumulation(UserReport report){
        userPaperRelationMapper.accumulation(report.getPaperId(), report.getUserNumber(), report.getUserTime(), report.getUserCorrect(), 1);
    }

    /**
     * 批量删除用户记录：homework切换可用学生
     * @param userIds
     * @param module
     * @param paperId
     * @return
     */
    public Boolean removeByUsersAndPaper(Collection<Integer> userIds, PaperModule module, Integer paperId){
        if(userIds.size() == 0) return false;
        Example example = new Example(UserPaper.class);
        example.and(
                example.createCriteria()
                        .andIn("userId", userIds)
                        .andEqualTo("module", module.key)
                        .andEqualTo("moduleId", paperId)
        );
        return delete(userPaperMapper, example, SOFT_FLAG) > 0;
    }

    /**
     * 批量修改用户记录：homework更新内容
     * @param userIds
     * @param module
     * @param paperId
     * @return
     */
    public Boolean editByUsersAndPaper(UserPaper userPaper, Collection<Integer> userIds, PaperModule module, Integer paperId){
        if(userIds.size() == 0) return false;
        Example example = new Example(UserPaper.class);
        example.and(
                example.createCriteria()
                        .andIn("userId", userIds)
                        .andEqualTo("module", module.key)
                        .andEqualTo("moduleId", paperId)
        );
        return update(userPaperMapper, example, userPaper) > 0;
    }

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

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

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

    public UserPaper get(Number id){
        UserPaper in = one(userPaperMapper, id);

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

    public Page<UserPaper> select(int page, int pageSize){
        return select(userPaperMapper, page, pageSize);
    }

    public List<UserPaper> select(Collection ids){
        return select(userPaperMapper, ids);
    }

}
