package com.ruoyi.project.training.elearn.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.exception.BaseException;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.training.elearn.domain.TElQuAnswer;
import com.ruoyi.project.training.elearn.domain.TElQuRepo;
import com.ruoyi.project.training.elearn.mapper.TElQuAnswerMapper;
import com.ruoyi.project.training.elearn.mapper.TElQuRepoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.training.elearn.mapper.TElQuMapper;
import com.ruoyi.project.training.elearn.domain.TElQu;
import com.ruoyi.project.training.elearn.service.ITElQuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 试题Service业务层处理
 *
 * @author ssy
 * @date 2024-05-28
 */
@Service
public class TElQuServiceImpl implements ITElQuService {
    @Resource
    private TElQuMapper tElQuMapper;
    @Resource
    private TElQuAnswerMapper tElQuAnswerMapper;
    @Resource
    private TElQuRepoMapper tElQuRepoMapper;
    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 查询试题
     *
     * @param quId 试题ID
     * @return 试题
     */
    @Override
    public TElQu selectTElQuById(Long quId) {
        TElQu tElQu = tElQuMapper.selectTElQuById(quId);

        //答案
        TElQuAnswer queyAs = new TElQuAnswer();
        queyAs.setQuId(tElQu.getQuId());
        List<TElQuAnswer> asList = tElQuAnswerMapper.selectTElQuAnswerList(queyAs);
        tElQu.setAnswerList(asList);

        //题库
        TElQuRepo queyRepo = new TElQuRepo();
        queyRepo.setQuId(tElQu.getQuId());
        List<TElQuRepo> repoList = tElQuRepoMapper.selectTElQuRepoList(queyRepo);
        List<String> ids = new ArrayList<>();
        for (TElQuRepo t : repoList
        ) {
            ids.add(String.valueOf(t.getRepoId()));
        }
        tElQu.setRepoIds(ids);

        return tElQu;
    }

    /**
     * 查询试题列表
     *
     * @param tElQu 试题
     * @return 试题
     */
    @Override
    public List<TElQu> selectTElQuList(TElQu tElQu) {
        return tElQuMapper.selectTElQuList(tElQu);
    }

    /**
     * 新增试题
     *
     * @param tElQu 试题
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTElQu(TElQu tElQu) {
        checkData(tElQu, "");
            //更新答案
            tElQuMapper.insertTElQu(tElQu);
            for (TElQuAnswer as : tElQu.getAnswerList()
            ) {
                as.setQuId(tElQu.getQuId());
                tElQuAnswerMapper.insertTElQuAnswer(as);
            }
            //更新题库
            for (String repoId : tElQu.getRepoIds()) {
                TElQuRepo ref = new TElQuRepo();
                ref.setQuId(tElQu.getQuId());
                ref.setRepoId(Long.parseLong(repoId));
                ref.setQuType(tElQu.getQuType());
                tElQuRepoMapper.insertTElQuRepo(ref);
            }
        return 1;
    }

    /**
     * 新增试题
     *
     * @param tElQu 试题
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTElQuBatch(TElQu tElQu , int i) {
        checkData(tElQu, "");
        new Thread(() -> {
            try {
                //更新答案
                tElQuMapper.insertTElQu(tElQu);
                for (TElQuAnswer as : tElQu.getAnswerList()
                ) {
                    as.setQuId(tElQu.getQuId());
                    tElQuAnswerMapper.insertTElQuAnswer(as);
                }
                //更新题库
                for (String repoId : tElQu.getRepoIds()) {
                    TElQuRepo ref = new TElQuRepo();
                    ref.setQuId(tElQu.getQuId());
                    ref.setRepoId(Long.parseLong(repoId));
                    ref.setQuType(tElQu.getQuType());
                    tElQuRepoMapper.insertTElQuRepo(ref);
                }
            }catch (Exception e) {
                logger.error("错误行数：" + i+1);
            }

        }, "新增试题").start();

        return 1;
    }


    /**
     * 修改试题
     *
     * @param tElQu 试题
     * @return 结果
     */
    @Override
    public int updateTElQu(TElQu tElQu) {
        checkData(tElQu, "");
        tElQuMapper.updateTElQu(tElQu);
        //更新答案
        TElQuAnswer queyAs = new TElQuAnswer();
        queyAs.setQuId(tElQu.getQuId());
        List<TElQuAnswer> oldList = tElQuAnswerMapper.selectTElQuAnswerList(queyAs);

        List<Long> ids = new ArrayList<>();
        if (oldList.size() > 0) {
            for (TElQuAnswer old : oldList
            ) {
                ids.add(old.getAnswerId());
            }
        }

        for (TElQuAnswer as : tElQu.getAnswerList()
        ) {
            //补全ID避免新增
            if (ids.contains(as.getAnswerId())) {
                ids.remove(as.getAnswerId());
            }
            as.setQuId(tElQu.getQuId());
            if (as.getAnswerId() == null) {
                tElQuAnswerMapper.insertTElQuAnswer(as);
            } else {
                tElQuAnswerMapper.updateTElQuAnswer(as);
            }

        }
        //删除答案
        for (Long id : ids
        ) {
            tElQuAnswerMapper.deleteTElQuAnswerById(id);
        }

        //先删除题库
        TElQuRepo queyRepo = new TElQuRepo();
        queyRepo.setQuId(tElQu.getQuId());
        List<TElQuRepo> repoList = tElQuRepoMapper.selectTElQuRepoList(queyRepo);
        for (TElQuRepo t : repoList
        ) {
            tElQuRepoMapper.deleteTElQuRepoById(t.getId());
        }

        //更新题库
        for (String repoId : tElQu.getRepoIds()) {
            TElQuRepo ref = new TElQuRepo();
            ref.setQuId(tElQu.getQuId());
            ref.setRepoId(Long.parseLong(repoId));
            ref.setQuType(tElQu.getQuType());
            tElQuRepoMapper.insertTElQuRepo(ref);
        }

        return 1;
    }

    /**
     * 批量删除试题
     *
     * @param quIds 需要删除的试题ID
     * @return 结果
     */
    @Override
    public int deleteTElQuByIds(Long[] quIds) {
        int i = tElQuMapper.deleteTElQuByIds(quIds);
        tElQuRepoMapper.deleteQu();
        return i;
    }

    /**
     * 删除试题信息
     *
     * @param quId 试题ID
     * @return 结果
     */
    @Override
    public int deleteTElQuById(Long quId) {
        return tElQuMapper.deleteTElQuById(quId);
    }

    /**
     * 校验题目信息
     *
     * @param qu
     * @param no
     * @throws Exception
     */
    public void checkData(TElQu qu, String no) {


        if (StringUtils.isEmpty(qu.getContent())) {
            throw new BaseException("1", no + "题目内容不能为空！");
        }


        if (CollectionUtils.isEmpty(qu.getRepoIds())) {
            throw new BaseException("1", no + "至少要选择一个题库！");
        }

        List<TElQuAnswer> answers = qu.getAnswerList();


        if (CollectionUtils.isEmpty(answers)) {
            throw new BaseException("1", no + "客观题至少要包含一个备选答案！");
        }


        int trueCount = 0;
        for (TElQuAnswer a : answers) {

            if (a.getIsRight() == null) {
                throw new BaseException("1", no + "必须定义选项是否正确项！");
            }

            if (StringUtils.isEmpty(a.getContent())) {
                throw new BaseException("1", no + "选项内容不为空！");
            }

            if (a.getIsRight() == 1) {
                trueCount += 1;
            }
        }

        if (trueCount == 0) {
            throw new BaseException("1", no + "至少要包含一个正确项！");
        }


        //单选题
        if (qu.getQuType().equals("1") && trueCount > 1) {
            throw new BaseException("1", no + "单选题不能包含多个正确项！");
        }

    }
}
