package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.distributed.print.business.bean.dto.BasicExamDto;
import com.qmth.distributed.print.business.entity.ExamPrintPlan;
import com.qmth.distributed.print.business.mapper.BasicExamMapper;
import com.qmth.distributed.print.business.service.BasicExamService;
import com.qmth.distributed.print.business.service.ExamPrintPlanService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicExam;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

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

    @Transactional
    @Override
    public BasicExam saveBasicExam(BasicExam basicExam) throws IllegalAccessException {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Long id = basicExam.getId();
        Long schoolId = sysUser.getSchoolId();

        BasicExam checkName = this.getOne(new QueryWrapper<BasicExam>().lambda()
                .eq(BasicExam::getSchoolId, schoolId)
                .eq(BasicExam::getSemesterId, basicExam.getSemesterId())
                .eq(BasicExam::getName, basicExam.getName())
                .eq(BasicExam::getEnable, true));
        // 校验考试名称唯一性
        if (Objects.nonNull(checkName) && !checkName.getId().equals(id)) {
            throw ExceptionResultEnum.ERROR.exception("考试名称【" + basicExam.getName() + "】已存在");
        }
        if (SystemConstant.longNotNull(id)) {
            // 编辑
            BasicExam old = this.getById(id);
            this.update(new UpdateWrapper<BasicExam>().lambda()
                    .eq(BasicExam::getId, id)
                    .set(BasicExam::getSemesterId, basicExam.getSemesterId())
                    .set(BasicExam::getName, basicExam.getName())
                    .set(BasicExam::getCategory, basicExam.getCategory())
                    .set(BasicExam::getExamModel, basicExam.getExamModel())
                    .set(BasicExam::getCreateId, sysUser.getId())
                    .set(BasicExam::getCreateTime, System.currentTimeMillis()));
        } else {
            // 新增
            basicExam.setId(SystemConstant.getDbUuid());
            basicExam.setSchoolId(schoolId);
            basicExam.setUpdateId(sysUser.getId());
            basicExam.setUpdateTime(System.currentTimeMillis());
            this.save(basicExam);
        }
        return basicExam;
    }

    @Transactional
    @Override
    public boolean deleteBasicExamById(Long id) {
        List<ExamPrintPlan> examPrintPlanList = examPrintPlanService.list(new QueryWrapper<ExamPrintPlan>().lambda().eq(ExamPrintPlan::getExamId, id));
        if (examPrintPlanList.size() > 0) {
            throw ExceptionResultEnum.ERROR.exception("考试已被绑定，不能删除");
        }
        return this.removeById(id);
    }

    @Override
    public List<BasicExam> query(Long semesterId, Boolean inUsed) {
        Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
        QueryWrapper<BasicExam> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicExam::getSchoolId, schoolId)
                .eq(BasicExam::getSemesterId, semesterId)
                .eq(BasicExam::getEnable, true);
        if (Objects.nonNull(inUsed)) {
            queryWrapper.lambda().eq(BasicExam::getInUsed, inUsed);
        }
        return this.list(queryWrapper);
    }

    @Transactional
    @Override
    public boolean setInUsed(Long id) {
        BasicExam exam = this.getById(id);
        // 只能设置一个当前使用考试
        if (!exam.getInUsed()) {
            QueryWrapper<BasicExam> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(BasicExam::getSchoolId, exam.getSchoolId())
                    .eq(BasicExam::getSemesterId, exam.getSemesterId());
            List<BasicExam> list = this.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                list = list.stream().map(m -> {
                    m.setInUsed(false);
                    return m;
                }).collect(Collectors.toList());
                this.updateBatchById(list);
            }
        }
        exam.setInUsed(!exam.getInUsed());
        return this.updateById(exam);
    }

    @Override
    public IPage<BasicExamDto> basicExamPage(Long semesterId, Boolean enable, Integer pageNumber, Integer pageSize) {
        Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
        return this.baseMapper.findBasicExamPage(new Page<>(pageNumber, pageSize), schoolId, semesterId, enable, null);
    }

    /**
     * 启用/禁用
     *
     */
    @Override
    public boolean enable(Long id, Boolean enable) {
        UpdateWrapper<BasicExam> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(BasicExam::getEnable, enable).eq(BasicExam::getId, id);
        return this.update(updateWrapper);
    }
}
