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

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.distributed.print.business.bean.dto.CardRuleDto;
import com.qmth.distributed.print.business.entity.BasicCardRule;
import com.qmth.distributed.print.business.entity.ExamCard;
import com.qmth.distributed.print.business.entity.ExamTask;
import com.qmth.distributed.print.business.mapper.BasicCardRuleMapper;
import com.qmth.distributed.print.business.service.BasicCardRuleService;
import com.qmth.distributed.print.business.service.BasicPrintConfigService;
import com.qmth.distributed.print.business.service.ExamCardService;
import com.qmth.distributed.print.business.service.ExamTaskService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicPrintConfig;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
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;
import java.util.Set;

/**
 * <p>
 * 题卡规则 服务实现类
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Service
public class BasicCardRuleServiceImpl extends ServiceImpl<BasicCardRuleMapper, BasicCardRule> implements BasicCardRuleService {

    @Resource
    TeachcloudCommonService teachcloudCommonService;

    @Resource
    BasicPrintConfigService basicPrintConfigService;

    @Resource
    ExamCardService examCardService;

    @Resource
    ExamTaskService examTaskService;

    @Override
    public IPage<CardRuleDto> list(Boolean enable, String name, Long createStartTime, Long createEndTime, Integer pageNumber, Integer pageSize) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        return this.baseMapper.listPage(new Page<>(pageNumber, pageSize), schoolId, enable, SystemConstant.translateSpecificSign(name), createStartTime, createEndTime);
    }

    @Override
    public List<BasicCardRule> list(String param) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        Set<Long> orgIds = teachcloudCommonService.listSubOrgIds(null);
        return this.baseMapper.list(schoolId, param, orgIds);
    }

    @Override
    public boolean enable(BasicCardRule cardRule) {
        QueryWrapper<BasicPrintConfig> basicPrintConfigQueryWrapper = new QueryWrapper<>();
        basicPrintConfigQueryWrapper.lambda().eq(BasicPrintConfig::getCardRuleId, cardRule.getId());
        int basicPrintConfigCount = basicPrintConfigService.count(basicPrintConfigQueryWrapper);

        QueryWrapper<ExamCard> examCardQueryWrapper = new QueryWrapper<>();
        examCardQueryWrapper.lambda().eq(ExamCard::getCardRuleId, cardRule.getId());
        int examCardCount = examCardService.count(examCardQueryWrapper);

        QueryWrapper<ExamTask> examTaskQueryWrapper = new QueryWrapper<>();
        examTaskQueryWrapper.lambda().eq(ExamTask::getCardRuleId, cardRule.getId());
        int examTaskCount = examTaskService.count(examTaskQueryWrapper);

        if (basicPrintConfigCount == 0 && examCardCount == 0 && examTaskCount == 0) {
            this.removeById(cardRule.getId());
        } else {
            throw ExceptionResultEnum.ERROR.exception("题卡规则已绑定数据，不能删除");
        }
        return true;
    }

    @Transactional
    @Override
    public boolean saveCardRule(BasicCardRule cardRule) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        cardRule.setSchoolId(schoolId);
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();

        if (cardRule.getTitleRule().length() > 200) {
            throw ExceptionResultEnum.ERROR.exception("题卡标题规则长度不能超过200字符");
        }

        QueryWrapper<BasicCardRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicCardRule::getSchoolId, cardRule.getSchoolId()).eq(BasicCardRule::getName, cardRule.getName());
        BasicCardRule basicCardRule = this.getOne(queryWrapper);
        boolean isSuccess;
        // 新增
        if (Objects.isNull(cardRule.getId())) {
            if (basicCardRule != null) {
                throw ExceptionResultEnum.ERROR.exception("题卡规则名称已存在");
            }
            cardRule.setId(SystemConstant.getDbUuid());
            cardRule.setOrgId(sysUser.getOrgId());
            cardRule.setCreateId(sysUser.getId());
            cardRule.setCreateTime(System.currentTimeMillis());
            isSuccess = this.save(cardRule);
        }
        // 修改
        else {
            if (basicCardRule != null && basicCardRule.getId().longValue() != cardRule.getId().longValue()) {
                throw ExceptionResultEnum.ERROR.exception("题卡规则名称已存在");
            }

            cardRule.setOrgId(sysUser.getOrgId());
            cardRule.setUpdateId(sysUser.getId());
            cardRule.setUpdateTime(System.currentTimeMillis());

            //删除权限
//            basicTemplateOrgService.removeByRuleId(cardRule.getId());
            isSuccess = this.updateById(cardRule);
        }

//         新增权限
//        basicTemplateOrgService.saveBatch(schoolId, TemplateTypeEnum.CARD_RULE, cardRule.getId(), cardRule.getOrgIds(), cardRule.getCreateId());
        return isSuccess;
    }
}
