package com.zsc.edu.gateway.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.system.dto.AuthorityDto;
//import com.zsc.edu.gateway.modules.system.dto.RoleAuthorityDto;
import com.zsc.edu.gateway.modules.system.entity.Authority;
import com.zsc.edu.gateway.modules.system.mapper.AuthorityMapper;
import com.zsc.edu.gateway.modules.system.repo.AuthorityRepository;
import com.zsc.edu.gateway.modules.system.service.AuthorityService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author zhuang
 */
@AllArgsConstructor
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityRepository, Authority> implements AuthorityService {
    private AuthorityMapper mapper;
    private AuthorityRepository repo;

    @Override
    public Authority create(AuthorityDto authorityDto) {
        boolean existsByName = count(new LambdaQueryWrapper<Authority>().eq(Authority::getName, authorityDto.getName())) > 0;
        if (existsByName) {
            throw new ConstraintException("name", authorityDto.name, "权限已存在");
        }
        Authority authority = mapper.toEntity(authorityDto);
        save(authority);
        return authority;
    }

    @Override
    public Boolean update(AuthorityDto authorityDto, Long id) {
        boolean isExists = count(new LambdaQueryWrapper<Authority>().ne(Authority::getId, id).eq(Authority::getName, authorityDto.getName())) > 0;
        if (isExists) {
            throw new ConstraintException("name", authorityDto.name, "同名权限已存在");
        }
        return update(authorityDto.updateWrapper(id));
    }


    @Override
    public Boolean toggle(Long id) {
        Authority authority = getById(id);
        authority.setEnabled(!authority.getEnabled());
        return updateById(authority);
    }

    @Override
    public Set<Authority> selectAuthoritiesByRoleId(Long roleId){
        return baseMapper.selectAuthoritiesByRoleId(roleId);
    }

}
