package yangtz.cs.liu.campus.service.impl.exam;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.exam.*;
import yangtz.cs.liu.campus.mapper.exam.*;
import yangtz.cs.liu.campus.service.exam.IExamMainService;
import yangtz.cs.liu.campus.vo.exam.ExamDetailVo;
import yangtz.cs.liu.campus.vo.exam.ExamMainVo;
import yangtz.cs.liu.campus.vo.exam.ScoreVo;

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

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.*;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.common.utils.SecurityUtils.getUsername;


/**
 * 问卷调查业务层
 */
@Service
public class ExamMainServiceImpl extends ServiceImpl<ExamMainMapper, ExamMain> implements IExamMainService {


    @Autowired
    private ExamMainMapper examMainMapper;

    @Autowired
    private ExamDetailMapper examDetailMapper;

    @Autowired
    private ExamUserMapper examUserMapper;

    @Autowired
    private ExamUserScoreMapper examUserScoreMapper;

    @Autowired
    private ExamUserScoreDetailMapper examUserScoreDetailMapper;

    public static final String NoIssued = "0";//未发布
    public static final String Issued = "1";//已发布
    public static final String End = "2";//已结束

    /**
     * 查询问卷调查列表
     *
     * @param examMain
     * @return
     */
    @Override
    public List<ExamMain> queryList(ExamMain examMain) {
        LambdaQueryWrapper<ExamMain> lqw = new LambdaQueryWrapper<>();
        lqw
                .like(isNotBlank(examMain.getExamName()), ExamMain::getExamName, examMain.getExamName())
                .eq(isNotBlank(examMain.getState()), ExamMain::getState, examMain.getState())
                .orderByDesc(ExamMain::getCreateTime)
        ;
        return examMainMapper.selectList(lqw);
    }


    /**
     * 查询参与情况
     *
     * @param exam
     * @return
     */
    @Override
    public List<ExamMainVo> selectTakeExamPeoNumList(ExamMainVo exam) {
        return examMainMapper.selectTakeExamPeoNumList(exam);
    }

    /**
     * 查询代办任务
     *
     * @param examMainVo
     * @return
     */
    @Override
    public List<ExamMainVo> selectExamTasks(ExamMainVo examMainVo) {
        //只有已启动,用户未参加过得才能显示到代办任务中
        return examMainMapper.selectExamTasks(examMainVo);
    }

    /**
     * 删除问卷调查表
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteByIds(List<Integer> ids) {
        //删除exam_user表
        LambdaQueryWrapper<ExamUser> examUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        examUserLambdaQueryWrapper.in(ExamUser::getExamId, ids);
        LambdaQueryWrapper<ExamUserScore> examUserScoreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        examUserScoreLambdaQueryWrapper.in(ExamUserScore::getExamId, ids);
        //删除exam_user_score_detail表
        for (Integer id : ids) {
            examUserScoreDetailMapper.deleteByExamIds(id);
        }


        //删除exam_user_score表
        examUserScoreMapper.delete(examUserScoreLambdaQueryWrapper);
        //删除exam_user表
        examUserMapper.delete(examUserLambdaQueryWrapper);
        //删除exam_Detail表
        LambdaQueryWrapper<ExamDetail> examDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        examDetailLambdaQueryWrapper.in(ExamDetail::getExamId, ids);
        examDetailMapper.delete(examDetailLambdaQueryWrapper);
        //删除主表exam_main
        return examMainMapper.deleteBatchIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void join(Long examId, ScoreVo score) {
        // 获取 用户提交的回答情况
        List<ExamUserScoreDetail> examUserScoreDetailList = score.getExamUserScoreDetailList();
        //拿到当前登录用户Id和userName
        Long userId = getUserId();
        String username = getUsername();
        String examName = examMainMapper.selectExamName(examId);//查询问卷活动名称

        ExamUserScore examUserScore = new ExamUserScore();
        examUserScore.setUserId(userId);
        examUserScore.setExamId(examId);
        examUserScore.setAnswerTime(new Date());
        examUserScore.setExamName(examName);
        examUserScore.setScore(score.getScore());
        //   1 .新增ExamUserScore表
        examUserScoreMapper.insert(examUserScore);
        Long examUserScoreId = examUserScore.getId();
        //   2 .新增ExamUserScoreDetail表
        for (ExamUserScoreDetail examUserScoreDetail : examUserScoreDetailList) {
            examUserScoreDetail.setUserScoreId(examUserScoreId);
        }
        examUserScoreDetailMapper.insertExamUserScoreDetail(examUserScoreDetailList);
        LambdaUpdateWrapper<ExamUser> luw = new LambdaUpdateWrapper<>();
        luw.eq(ExamUser::getExamId,examId).eq(ExamUser::getUserId,userId).set(ExamUser::getIsJoin,"1");
        examUserMapper.update(new ExamUser(),luw);
    }

    /**
     * 检查是否可以发布
     *
     * @param id
     */
    @Override
    public void checkExam(Long id) {
        if (0 >= examMainMapper.selectDetails(id)) {
            throw new ServiceException("问卷活动没有内容");
        } else if (0 >= examUserMapper.selectAllUserIdByExamId(id).size()) {
            throw new ServiceException("问卷活动下没有用户");
        }
    }

    /**
     * 更改问卷状态
     * @param examState
     * @param id
     * @return
     */
    @Override
    public int editExamState(Character examState, Long id) {
        ExamMain exam = examMainMapper.selectExamByExamId(id);
        //进行撤回操作时，进行校验
        if (examState.compareTo('0') == 0){
            if (NoIssued.equals(exam.getState())){
                throw new ServiceException("撤回失败，当前问卷已撤回");
            }
            if (End.equals(exam.getState())){
                throw new ServiceException("撤回失败，当前问卷已结束");
            }
            //将所有用户参加状态重置为0未参加，将用户分，用户分细节清除
            //查询所分派的所有用户‘
            LambdaQueryWrapper<ExamUser> eu = new LambdaQueryWrapper<>();
            eu.eq(ExamUser::getExamId,id);
            List<ExamUser> userList = examUserMapper.selectList(eu);
            if(StringUtils.isNotNull(userList) || userList.size() > 0){
                for(ExamUser user : userList){
                    //先删再改
                    //用户分数表,要么有一条，要么没有
                    LambdaQueryWrapper<ExamUserScore> s = new LambdaQueryWrapper<>();
                    s.eq(ExamUserScore::getExamId,id).eq(ExamUserScore::getUserId,user.getUserId());
                    ExamUserScore score = examUserScoreMapper.selectOne(s);
                    //不为空时，删除分数细节表数据
                    if(StringUtils.isNotNull(score)){
                        LambdaQueryWrapper<ExamUserScoreDetail> sd = new LambdaQueryWrapper<>();
                        sd.eq(ExamUserScoreDetail::getUserScoreId,score.getId());
                        examUserScoreDetailMapper.delete(sd);
                    }
                    //删用户分数表
                    examUserScoreMapper.deleteById(score.getId());
                    //重置为0未参加
                    LambdaUpdateWrapper<ExamUser> luw = new LambdaUpdateWrapper<>();
                    luw.eq(ExamUser::getExamId,id).eq(ExamUser::getUserId,user.getUserId()).set(ExamUser::getIsJoin,"0");
                    examUserMapper.update(new ExamUser(),luw);
                }
            }

        }
        //进行发布操作时，进行校验
        if (examState.compareTo('1') == 0) {
            if (Issued.equals(exam.getState())) {
                throw new ServiceException("发布失败，当前问卷已发布");
            }
            if (End.equals(exam.getState())) {
                throw new ServiceException("发布失败，当前问卷已结束");
            }
        }
        //进行结束操作时，进行校验
        if (examState.compareTo('2') == 0) {
            if (NoIssued.equals(exam.getState())) {
                throw new ServiceException("结束失败，当前问卷未发布");
            }
            if (End.equals(exam.getState())) {
                throw new ServiceException("结束失败，当前问卷已结束");
            }
        }
        //根据问卷id更改状态
        return examMainMapper.editExamState(examState,id);
    }

    /**
     * 问卷列表
     */
    @Override
    public List<ExamMainVo> getExam(Long userId,ExamMainVo examMainVo) {
       return examMainMapper.getExam(userId,examMainVo);
    }


}
