package com.qxgmat.service;

import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
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.logic.SentenceLogic;
import com.qxgmat.data.dao.SentencePaperMapper;
import com.qxgmat.data.dao.entity.Question;
import com.qxgmat.data.dao.entity.SentencePaper;
import com.qxgmat.data.dao.entity.SentenceQuestion;
import com.qxgmat.data.dao.entity.UserPaper;
import com.qxgmat.data.relation.entity.SentenceQuestionRelation;
import com.qxgmat.service.inline.QuestionService;
import com.qxgmat.service.inline.SentenceQuestionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SentencePaperService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(SentencePaperService.class);
    @Value("${paper.sentenceLength}")
    private Integer paperLength;

    @Resource
    private SentencePaperMapper sentencePaperMapper;

    @Resource
    private QuestionService questionService;

    @Resource
    private SentenceQuestionService sentenceQuestionService;

    public void initUserPaper(UserPaper userPaper, Integer id){
        SentencePaper paper = get(id);
        userPaper.setTitle(paper.getTitle());
        userPaper.setQuestionNoIds(paper.getQuestionNoIds());
        userPaper.setTime(0);
    }
    /**
     * 添加长难句题目：加入题库，关联题目，并关联长难句paper
     * @param relation
     * @return
     */
    @Transactional
    public SentenceQuestion addQuestion(SentenceQuestionRelation relation){
        SentenceQuestion in = sentenceQuestionService.getByNo(relation.getNo());
        if (in != null){
            throw new ParameterException("序号已经存在");
        }
        Question question = relation.getQuestion();
        question = questionService.add(question);
        // 绑定关系
        relation.setQuestionId(question.getId());

        SentenceQuestion sentenceQuestion =  sentenceQuestionService.add(relation);

        // 绑定关系
        SentencePaper paper = addQuestionToPaper(sentenceQuestion);
        sentenceQuestion.setPaperId(paper.getId());

        sentenceQuestionService.edit(sentenceQuestion);
        return sentenceQuestion;
    }

    /**
     * 更新长难句题目：更新题库，，变更长难句paper
     * @param relation
     * @return
     */
    @Transactional
    public SentenceQuestion editQuestion(SentenceQuestionRelation relation){
        SentenceQuestion in = sentenceQuestionService.getByNo(relation.getNo());
        if (in != null && !in.getId().equals(relation.getId())){
            throw new ParameterException("序号已经存在");
        }

        Question question = relation.getQuestion();
        question = questionService.edit(question);

        if(in == null){
            in = sentenceQuestionService.get(relation.getId());
        }

        // 根据序号调整分组
        if (!in.getId().equals(relation.getId())){
            // 移出原有关系
            removeQuestionFromPaper(in);

            // 绑定关系
            SentencePaper paper = addQuestionToPaper(relation);
            relation.setPaperId(paper.getId());
        }

        SentenceQuestion sentenceQuestion = sentenceQuestionService.edit(relation);

        return sentenceQuestion;
    }

    /**
     * 获取可用的试卷列表：单个分组逻辑
     * @param logic
     * @return
     */
    public List<SentencePaper> listByLogic(SentenceLogic logic){
        Example example = new Example(SentencePaper.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("logic", logic.key)
                        .andEqualTo("status", 1)
        );
        example.orderBy("no").asc();
        return select(sentencePaperMapper, example);
    }

    private SentencePaper addQuestionToPaper(SentenceQuestion question){
        // 根据序号创建
        Integer paperNo = question.getNo() / paperLength + 1;
        SentencePaper paper = getByNo(paperNo, SentenceLogic.NO);
        if (paper == null){
            paper = add(SentencePaper.builder()
                    .logic(SentenceLogic.NO.key)
                    .questionNumber(1)
                    .questionNoIds(new Integer[]{question.getId()}).build()
            );
        }else{
            // 加入
            List<Integer> list = Arrays.stream(paper.getQuestionNoIds()).collect(Collectors.toList());
            list.add(question.getId());
            paper.setQuestionNumber(paper.getQuestionNumber() + 1);
            paper.setQuestionNoIds(list.toArray(new Integer[0]));
            paper = edit(paper);
        }
        return paper;
    }

    private Boolean removeQuestionFromPaper(SentenceQuestion question){
        SentencePaper paper = get(question.getPaperId());
        paper.setQuestionNumber(paper.getQuestionNumber() - 1);
        List<Integer> list = Arrays.stream(paper.getQuestionNoIds()).collect(Collectors.toList());
        list.remove(question.getId());
        paper.setQuestionNoIds(list.toArray(new Integer[0]));
        paper = edit(paper);
        return true;
    }

    private SentencePaper getByNo(Integer no, SentenceLogic logic){
        Example example = new Example(SentencePaper.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("no", no)
                        .andEqualTo("logic", logic.key)
        );
        return one(sentencePaperMapper, example);
    }

    public SentencePaper add(SentencePaper paper){
        int result = insert(sentencePaperMapper, paper);
        paper = one(sentencePaperMapper, paper.getId());
        if(paper == null){
            throw new SystemException("题目添加失败");
        }
        return paper;
    }

    public SentencePaper edit(SentencePaper paper){
        SentencePaper in = one(sentencePaperMapper, paper.getId());
        if(in == null){
            throw new ParameterException("题目不存在");
        }
        int result = update(sentencePaperMapper, paper);
        return paper;
    }

    public boolean delete(Number id){
        SentencePaper in = one(sentencePaperMapper, id);
        if(in == null){
            throw new ParameterException("题目不存在");
        }
        int result = delete(sentencePaperMapper, id);
        return result > 0;
    }

    public SentencePaper get(Number id){
        SentencePaper in = one(sentencePaperMapper, id);

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

    public Page<SentencePaper> select(int page, int pageSize){
        return select(sentencePaperMapper, page, pageSize);
    }

    public List<SentencePaper> select(Collection ids){
        return select(sentencePaperMapper, ids);
    }

}
