package com.zjty.tynotes.pas.service.impl;

import com.zjty.tynotes.pas.dao.AuthorityDao;
import com.zjty.tynotes.pas.dao.RoleAuthorityDao;
import com.zjty.tynotes.pas.entity.Authority;
import com.zjty.tynotes.pas.service.IAuthorityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author: mcj
 * @Date: 19-4-29 下午4:11
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AuthorityServiceImpl implements IAuthorityService {
    private static final Logger logger = LoggerFactory.getLogger(AuthorityServiceImpl.class);

    @Autowired
    private AuthorityDao authorityDao;
    @Autowired
    private RoleAuthorityDao roleAuthorityDao;


    @Override
    public Authority addAuthority(Authority authority) {
        Authority save = authorityDao.save(authority);
        return save;
    }

    @Override
    public boolean deleteAuthority(String id) {
        try {
            roleAuthorityDao.deleteAllByAuthorityId(id);
            authorityDao.deleteById(id);
            return true;
        } catch (Exception e) {
            logger.error("mogodb删除权限失败");
        }
        return false;
    }

    @Override
    public Authority updateAuthority(Authority authority) {
        Optional<Authority> byId = authorityDao.findById(authority.getId());
        if(byId.isPresent()){
            Authority authority1 = byId.get();
            authority1.setName(authority.getName());
            authority1.setDescription(authority.getDescription());
            authorityDao.save(authority1);
            return authority1;
        }
        return null;
    }

    @Override
    public List<Authority> findAuthority() {
        return authorityDao.findAll();
    }
}
