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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.epidemic.*;
import yangtz.cs.liu.campus.mapper.epidemic.*;
import yangtz.cs.liu.campus.service.epidemic.IEpidemicMainService;
import yangtz.cs.liu.campus.vo.epidemic.EpidemicMainVo;
import yangtz.cs.liu.campus.vo.epidemic.IScoreVo;

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

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 EpidemicMainServiceImpl extends ServiceImpl<EpidemicMainMapper, EpidemicMain> implements IEpidemicMainService {


    @Autowired
    private EpidemicMainMapper epidemicMainMapper;

    @Autowired
    private EpidemicDetailMapper epidemicDetailMapper;

    @Autowired
    private EpidemicUserMapper epidemicUserMapper;

    @Autowired
    private EpidemicUserScoreMapper epidemicUserScoreMapper;

    @Autowired
    private EpidemicUserScoreDetailMapper epidemicUserScoreDetailMapper;

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

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


    /**
     * 查询参与情况
     *
     * @param epidemic
     * @return
     */
    @Override
    public List<EpidemicMainVo> selectTakeEpidemicPeoNumList(EpidemicMainVo epidemic) {
        return epidemicMainMapper.selectTakeEpidemicPeoNumList(epidemic);
    }

    /**
     * 查询代办任务
     *
     * @param epidemicMainVo
     * @return
     */
    @Override
    public List<EpidemicMainVo> selectEpidemicTasks(EpidemicMainVo epidemicMainVo) {
        //只有已启动才能显示到代办任务中
        return epidemicMainMapper.selectEpidemicTasks(epidemicMainVo);
    }

    /**
     * 删除问卷调查表
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteByIds(List<Integer> ids) {
        //删除exam_user表
        LambdaQueryWrapper<EpidemicUser> epidemicUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        epidemicUserLambdaQueryWrapper.in(EpidemicUser::getEpidemicId, ids);
        LambdaQueryWrapper<EpidemicUserScore> epidemicUserScoreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        epidemicUserScoreLambdaQueryWrapper.in(EpidemicUserScore::getEpidemicId, ids);
        //删除exam_user_score_detail表
        for (Integer id : ids) {
            epidemicUserScoreDetailMapper.deleteByExamIds(id);
        }


        //删除exam_user_score表
        epidemicUserScoreMapper.delete(epidemicUserScoreLambdaQueryWrapper);
        //删除exam_user表
        epidemicUserMapper.delete(epidemicUserLambdaQueryWrapper);
        //删除exam_Detail表
        LambdaQueryWrapper<EpidemicDetail> epidemicDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        epidemicDetailLambdaQueryWrapper.in(EpidemicDetail::getEpidemicId, ids);
        epidemicDetailMapper.delete(epidemicDetailLambdaQueryWrapper);
        //删除主表exam_main
        return epidemicMainMapper.deleteBatchIds(ids);
    }

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

        EpidemicUserScore epidemicUserScore = new EpidemicUserScore();
        epidemicUserScore.setUserId(userId);
        epidemicUserScore.setEpidemicId(epidemicId);
        epidemicUserScore.setName(username);
        epidemicUserScore.setAnswerTime(new Date());
        epidemicUserScore.setEpidemicName(examName);
        epidemicUserScore.setScore(score.getScore());
        //   1 .新增ExamUserScore表
        epidemicUserScoreMapper.insert(epidemicUserScore);
        Long epidemicUserScoreId = epidemicUserScore.getId();
        //   2 .新增ExamUserScoreDetail表
        for (EpidemicUserScoreDetail epidemicUserScoreDetail : epidemicUserScoreDetailList) {
            epidemicUserScoreDetail.setUserScoreId(epidemicUserScoreId);
        }
        epidemicUserScoreDetailMapper.insertEpidemicUserScoreDetail(epidemicUserScoreDetailList);
    }

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

    /**
     * 更改问卷状态
     * @param examState
     * @param id
     * @return
     */
    @Override
    public int editEpidemicState(Character examState, Long id) {
        EpidemicMain epidemic = epidemicMainMapper.selectEpidemicByExamId(id);
        //进行撤回操作时，进行校验
        if (examState.compareTo('0') == 0){
            if (NoIssued.equals(epidemic.getState())){
                throw new ServiceException("撤回失败，当前问卷已撤回");
            }
            if (End.equals(epidemic.getState())){
                throw new ServiceException("撤回失败，当前问卷已结束");
            }
        }
        //进行发布操作时，进行校验
        if (examState.compareTo('1') == 0) {
            if (Issued.equals(epidemic.getState())) {
                throw new ServiceException("发布失败，当前问卷已发布");
            }
            if (End.equals(epidemic.getState())) {
                throw new ServiceException("发布失败，当前问卷已结束");
            }
        }
        //进行结束操作时，进行校验
        if (examState.compareTo('2') == 0) {
            if (NoIssued.equals(epidemic.getState())) {
                throw new ServiceException("结束失败，当前问卷未发布");
            }
            if (End.equals(epidemic.getState())) {
                throw new ServiceException("结束失败，当前问卷已结束");
            }
        }
        //根据问卷id更改状态
        return epidemicMainMapper.editEpidemicState(examState,id);
    }


}
