package com.zhiqiyun.open.service.impl;

import com.zhiqiyun.open.exception.ServiceException;
import com.zhiqiyun.open.mapper.RoleInfoMapper;
import com.zhiqiyun.open.models.RoleInfo;
import com.zhiqiyun.open.mybatis.paginator.domain.PageBounds;
import com.zhiqiyun.open.mybatis.paginator.domain.PageResult;
import com.zhiqiyun.open.service.RoleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author jtoms
 */
@Service
public class OauthRoleInfoServiceImpl implements RoleInfoService {

    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Override
    public void updateById(RoleInfo roleInfo) {
        this.roleInfoMapper.updateById(roleInfo);
    }

    @Override
    public void insert(RoleInfo roleInfo) {
        this.roleInfoMapper.insert(roleInfo);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void deleteByIds(List<Long> roleIds) throws ServiceException {
        try {
            this.roleInfoMapper.deleteAuthorities(roleIds);
            this.roleInfoMapper.deleteBatchIds(roleIds);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public List<Long> findAuthorities(Long roleId) {
        return this.roleInfoMapper.findAuthorities(roleId);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void saveAuthorities(Long roleId, Long[] authorities) throws ServiceException {
        try {
            this.roleInfoMapper.deleteAuthorities(Collections.singletonList(roleId));
            if (authorities != null && authorities.length > 0) {
                this.roleInfoMapper.insertAuthority(roleId, authorities);
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public PageResult<RoleInfo> findPage(PageBounds bounds, Map<String, Object> queryWrapper) {
        List<RoleInfo> listData = this.roleInfoMapper.findPage(bounds, queryWrapper);

        return bounds.newPageResult(listData);
    }
}
