package com.qmth.paper.library.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.paper.library.business.bean.result.SelectResult;
import com.qmth.paper.library.business.mapper.BasicExamMapper;
import com.qmth.paper.library.business.service.BasicExamService;
import com.qmth.paper.library.business.service.ExamStudentService;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.BasicExam;
import com.qmth.paper.library.common.entity.ExamStudent;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import com.qmth.paper.library.common.service.BasicSemesterService;
import com.qmth.paper.library.common.util.ServletUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 考试管理 服务实现类
 * </p>
 */
@Service
public class BasicExamServiceImpl extends ServiceImpl<BasicExamMapper, BasicExam> implements BasicExamService {

    @Resource
    private ExamStudentService examStudentService;
    @Resource
    private BasicSemesterService basicSemesterService;

    @Override
    public IPage<BasicExam> pageData(Long semesterId, Integer pageNumber, Integer pageSize) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        QueryWrapper<BasicExam> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<BasicExam> lambda = queryWrapper.lambda();
        if (semesterId != null) {
            lambda.eq(BasicExam::getSemesterId, semesterId);
        } else {
            lambda.eq(BasicExam::getSchoolId, schoolId);
        }
        lambda.orderByAsc(BasicExam::getCreateTime);
        Page<BasicExam> basicExamPage = this.baseMapper.selectPage(new Page<>(pageNumber, pageSize), queryWrapper);
        for (BasicExam record : basicExamPage.getRecords()) {
            record.setSemesterName(basicSemesterService.getById(record.getSemesterId()).getName());
        }
        return basicExamPage;
    }

    @Override
    public boolean saveData(BasicExam basicExam) {
        Long userId = Long.valueOf(ServletUtil.getRequestHeaderUserId().toString());
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());

        BasicExam basicExamExist = this.baseMapper.selectBySemesterIdAndName(basicExam.getSemesterId(), basicExam.getName());

        // 新增
        if (basicExam.getId() == null) {
            if (basicExamExist != null) {
                throw ExceptionResultEnum.ERROR.exception("考试名称已存在");
            }
            basicExam.setId(SystemConstant.getDbUuid());
            basicExam.setSchoolId(schoolId);
            basicExam.setCreateId(userId);
            basicExam.setCreateTime(System.currentTimeMillis());
            return this.save(basicExam);
        }
        // 修改
        else {
            if (basicExamExist != null && !basicExam.getId().equals(basicExamExist.getId())) {
                throw ExceptionResultEnum.ERROR.exception("考试名称已存在");
            }
            BasicExam exam = this.getById(basicExam.getId());

            exam.setName(basicExam.getName());
            exam.setUpdateId(userId);
            exam.setUpdateTime(System.currentTimeMillis());
            return this.updateById(exam);
        }
    }

    @Transactional
    @Override
    public boolean delete(String ids) {
        String[] idsArray = ids.split(",");
        for (String id : idsArray) {
            Long idLong = Long.valueOf(id);
            BasicExam basicExam = this.getById(idLong);
            if (basicExam == null) {
                throw ExceptionResultEnum.ERROR.exception("数据有误");
            }
            // 已使用不能删除
            QueryWrapper<ExamStudent> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ExamStudent::getExamId, id);
            int count = examStudentService.count(queryWrapper);
            if (count > 0) {
                throw ExceptionResultEnum.ERROR.exception("考试已上传考生，不允许删除");
            }
            this.removeById(idLong);
        }
        return true;
    }

    @Override
    public List<SelectResult> listBySemesterId(Long semesterId) {
        QueryWrapper<BasicExam> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicExam::getSemesterId, semesterId)
                .orderByDesc(BasicExam::getCreateTime);
        List<BasicExam> examList = this.list(queryWrapper);
        List<SelectResult> selectResults = new ArrayList<>();
        for (BasicExam basicExam : examList) {
            SelectResult selectResult = new SelectResult();
            selectResult.setId(String.valueOf(basicExam.getId()));
            selectResult.setName(basicExam.getName());
            selectResults.add(selectResult);
        }
        return selectResults;
    }
}
