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.QuestionType;
import com.qxgmat.data.constants.enums.module.QuestionModule;
import com.qxgmat.data.constants.enums.status.DirectionStatus;
import com.qxgmat.data.dao.UserCollectQuestionMapper;
import com.qxgmat.data.dao.entity.Question;
import com.qxgmat.data.dao.entity.QuestionNo;
import com.qxgmat.data.dao.entity.UserCollectQuestion;
import com.qxgmat.data.relation.UserCollectQuestionRelationMapper;
import com.qxgmat.data.relation.entity.UserCollectQuestionRelation;
import com.qxgmat.service.inline.QuestionNoService;
import com.qxgmat.service.inline.QuestionService;
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.List;

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

    @Resource
    private UserCollectQuestionMapper userCollectQuestionMapper;

    @Resource
    private UserCollectQuestionRelationMapper userCollectQuestionRelationMapper;

    @Resource
    private QuestionNoService questionNoService;

    @Resource
    private QuestionService questionService;

    /**
     * 获取用户题目收藏列表
     * @param page
     * @param size
     * @param userId
     * @param type
     * @return
     */
    public PageResult<UserCollectQuestionRelation> listQuestion(int page, int size, Integer userId, QuestionModule module, QuestionType type, String startTime, String endTime, String order, DirectionStatus direction){
        String moduleKey = module == null ? null : module.key;
        String typeKey = type == null ? null : type.key;
        Page<UserCollectQuestion> p = page(()->{
            userCollectQuestionRelationMapper.list(userId, moduleKey, typeKey, startTime, endTime, order, direction.key);
        }, page, size);

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

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

        List<UserCollectQuestionRelation> pr = Transform.convert(list, UserCollectQuestionRelation.class);

        // 获取题目信息
        Collection questionIds = Transform.getIds(pr, UserCollectQuestionRelation.class, "questionId");
        List<Question> questionList = questionService.select(questionIds);
        Transform.combine(pr, questionList, UserCollectQuestionRelation.class, "questionId", "question", Question.class, "id");

        // 获取题目编号信息
        Collection questionNoIds = Transform.getIds(pr, UserCollectQuestionRelation.class, "questionNoId");
        List<QuestionNo> questionNoList = questionNoService.select(questionNoIds);
        Transform.combine(pr, questionNoList, UserCollectQuestionRelation.class, "questionNoId", "questionNo", Question.class, "id");

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

    /**
     * 查询用户收藏情况
     * @param userId
     * @param questionId
     * @return
     */
    public UserCollectQuestion getByUserAndQuestion(Integer userId, Integer questionId){

        Example example = new Example(UserCollectQuestion.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("userId", userId)
                        .andEqualTo("questionId", questionId)
        );
        UserCollectQuestion in = one(userCollectQuestionMapper, example);
        return in;
    }

    /**
     * 收藏题目编号：包含题目id
     * @param entity
     * @return
     */
    @Transactional
    public UserCollectQuestion addQuestion(UserCollectQuestion entity){
        Example example = new Example(UserCollectQuestion.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("userId", entity.getUserId())
                        .andEqualTo("questionNoId", entity.getQuestionNoId())
        );
        UserCollectQuestion in = one(userCollectQuestionMapper, example);
        if (in != null){
            return in;
        }
        int result = insert(userCollectQuestionMapper, entity);
        return entity;
    }

    /**
     * 取消收藏题目编号
     * @param userId
     * @param questionNoId
     * @return
     */
    @Transactional
    public boolean deleteQuestion(Integer userId, Integer questionNoId){
        Example example = new Example(UserCollectQuestion.class);
        example.and(
                example.createCriteria()
                .andEqualTo("userId", userId)
                .andEqualTo("questionNoId", questionNoId)
        );
        UserCollectQuestion in = one(userCollectQuestionMapper, example);
        if (in == null){
            return true;
        }
        int result = delete(userCollectQuestionMapper, example);
        return result > 0;
    }

    public UserCollectQuestion add(UserCollectQuestion collect){
        int result = insert(userCollectQuestionMapper, collect);
        collect = one(userCollectQuestionMapper, collect.getId());
        if(collect == null){
            throw new SystemException("收藏添加失败");
        }
        return collect;
    }

    public UserCollectQuestion edit(UserCollectQuestion collect){
        UserCollectQuestion in = one(userCollectQuestionMapper, collect.getId());
        if(in == null){
            throw new ParameterException("收藏不存在");
        }
        int result = update(userCollectQuestionMapper, collect);
        return collect;
    }

    public boolean delete(Number id){
        UserCollectQuestion in = one(userCollectQuestionMapper, id);
        if(in == null){
            throw new ParameterException("收藏不存在");
        }
        int result = delete(userCollectQuestionMapper, id);
        return result > 0;
    }

    public UserCollectQuestion get(Number id){
        UserCollectQuestion in = one(userCollectQuestionMapper, id);

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

    public Page<UserCollectQuestion> select(int page, int pageSize){
        return select(userCollectQuestionMapper, page, pageSize);
    }

    public List<UserCollectQuestion> select(Collection ids){
        return select(userCollectQuestionMapper, ids);
    }

}
