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.entity.ExamPrintPlan;
import com.qmth.distributed.print.business.entity.ExamTask;
import com.qmth.distributed.print.business.mapper.BasicExamMapper;
import com.qmth.distributed.print.business.service.BasicExamService;
import com.qmth.distributed.print.business.service.BasicPrintConfigService;
import com.qmth.distributed.print.business.service.ExamPrintPlanService;
import com.qmth.distributed.print.business.service.ExamTaskService;
import com.qmth.distributed.print.business.util.CodeUtils;
import com.qmth.teachcloud.common.bean.dto.DataPermissionRule;
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.ExamModelEnum;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.BasicRoleDataPermissionService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    @Resource
    ExamTaskService examTaskService;
    @Resource
    ExamPrintPlanService examPrintPlanService;
    @Resource
    BasicRoleDataPermissionService basicRoleDataPermissionService;

    @Resource
    BasicPrintConfigService basicPrintConfigService;

    @Resource
    CodeUtils codeUtils;

    @Transactional
    @Override
    public BasicExam saveBasicExam(BasicExam basicExam) {
        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()));
        // 校验考试名称唯一性
        if (Objects.nonNull(checkName) && !checkName.getId().equals(id)) {
            throw ExceptionResultEnum.ERROR.exception("考试名称[" + basicExam.getName() + "]已使用");
        }
        if (SystemConstant.longNotNull(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::getUpdateId, sysUser.getId())
                    .set(BasicExam::getUpdateTime, System.currentTimeMillis()));
        } else {
            // 新增
            basicExam.setId(SystemConstant.getDbUuid());
            basicExam.setSchoolId(schoolId);
            basicExam.setOrgId(sysUser.getOrgId());
            basicExam.setCreateId(sysUser.getId());
            basicExam.setCreateTime(System.currentTimeMillis());
            // 生成简码
            String shortCode = codeUtils.createBasicExamShortCode(schoolId);
            basicExam.setShortCode(shortCode);
            this.save(basicExam);
        }
        return basicExam;
    }

    @Transactional
    @Override
    public boolean deleteBasicExamById(Long id) {
        BasicExam basicExam = this.getById(id);
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        int countExamTask = examTaskService.count(new QueryWrapper<ExamTask>().lambda().eq(ExamTask::getSchoolId, schoolId).eq(ExamTask::getExamId, id));
        if (countExamTask > 0) {
            throw ExceptionResultEnum.ERROR.exception("命题任务已使用考试[" + basicExam.getName() + "]，不能删除");
        }
        int countExamPrint = examPrintPlanService.count(new QueryWrapper<ExamPrintPlan>().lambda().eq(ExamPrintPlan::getSchoolId, schoolId).eq(ExamPrintPlan::getExamId, id));
        if (countExamPrint > 0) {
            throw ExceptionResultEnum.ERROR.exception("印刷计划已使用考试[" + basicExam.getName() + "]，不能删除");
        }
        // 删除设置印品
        basicPrintConfigService.removeByExamId(id);
        return this.removeById(id);
    }

    @Override
    public List<BasicExam> query(Long semesterId, List<ExamModelEnum> examModels) {
        Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(schoolId, requestUser.getId(), ServletUtil.getRequest().getServletPath());

        QueryWrapper<BasicExam> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicExam::getSchoolId, schoolId)
                .eq(BasicExam::getSemesterId, semesterId)
                .eq(BasicExam::getEnable, true);
        if (Objects.nonNull(examModels) && !examModels.isEmpty()) {
            queryWrapper.lambda().in(BasicExam::getExamModel, examModels);
        }
        if (SystemConstant.longNotNull(dpr.getRequestUserId())) {
            queryWrapper.lambda().eq(BasicExam::getCreateId, dpr.getRequestUserId());
        }
        if (dpr.getOrgIdSet() != null && dpr.getOrgIdSet().size() > 0) {
            queryWrapper.lambda().in(BasicExam::getOrgId, dpr.getOrgIdSet());
        }
        return this.list(queryWrapper);
    }

    @Override
    public IPage<BasicExam> basicExamPage(Long semesterId, Boolean enable, Integer pageNumber, Integer pageSize) {
        Long schoolId = SystemConstant.convertIdToLong(ServletUtil.getRequestHeaderSchoolId().toString());
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(schoolId, requestUser.getId(), ServletUtil.getRequest().getServletPath());
        return this.baseMapper.findBasicExamPage(new Page<>(pageNumber, pageSize), schoolId, semesterId, enable, dpr);
    }

    /**
     * 启用/禁用
     */
    @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);
    }

}
