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.CardRuleDto;
import com.qmth.distributed.print.business.entity.BasicCardRule;
import com.qmth.distributed.print.business.enums.TemplateTypeEnum;
import com.qmth.distributed.print.business.mapper.BasicCardRuleMapper;
import com.qmth.distributed.print.business.service.BasicCardRuleService;
import com.qmth.distributed.print.business.service.BasicTemplateOrgService;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysOrg;
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.beans.factory.annotation.Autowired;
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 {

    @Autowired
    private BasicTemplateOrgService basicTemplateOrgService;

    @Resource
    TeachcloudCommonService teachcloudCommonService;

    @Override
    public IPage<CardRuleDto> list(Boolean enable, String name, Long createStartTime, Long createEndTime, Integer pageNumber, Integer pageSize) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        Page<CardRuleDto> page = new Page<>(pageNumber, pageSize);
        IPage<CardRuleDto> cardRuleDtoIPage = this.baseMapper.listPage(page, schoolId, enable, SystemConstant.translateSpecificSign(name), createStartTime, createEndTime);
        if (cardRuleDtoIPage.getRecords().size() > 0) {
            cardRuleDtoIPage.getRecords().forEach(m -> {
                //查询适用学院
                List<SysOrg> sysOrgs = basicTemplateOrgService.listByTypeAndTemplateId(TemplateTypeEnum.CARD_RULE.name(), Long.valueOf(m.getId()));
                m.setOrgs(sysOrgs);
            });
        }
        return cardRuleDtoIPage;
    }

    @Override
    public List<BasicCardRule> list(String param) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
//        QueryWrapper<BasicCardRule> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(BasicCardRule::getSchoolId, schoolId).eq(BasicCardRule::getEnable, true);
//        if (StringUtils.isNotBlank(param)) {
//            queryWrapper.lambda().like(BasicCardRule::getName, ConvertUtil.translateSpecificSign(param));
//        }
        Set<Long> orgIds = teachcloudCommonService.listSubOrgIds(null);
        return this.baseMapper.list(schoolId, param, orgIds);
    }

    @Override
    public boolean enable(BasicCardRule cardRule) {
        UpdateWrapper<BasicCardRule> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(BasicCardRule::getEnable, cardRule.getEnable()).eq(BasicCardRule::getId, cardRule.getId());
        return this.update(updateWrapper);
    }

    @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;
    }


}
