package com.dxhy.admin.sys.service.impl;

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

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.admin.sys.dao.SysRoleDeptDao;
import com.dxhy.admin.sys.entity.SysRoleDeptEntity;
import com.dxhy.admin.sys.service.SysRoleDeptService;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.utils.Aops;

import lombok.extern.slf4j.Slf4j;

/**
 * 角色与部门对应关系
 *
 * @author jiaohongyang
 */
@Service("sysRoleDeptService")
@Slf4j
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDeptDao, SysRoleDeptEntity>
    implements SysRoleDeptService {

    @Override
    public void saveOrUpdate(Long roleId, List<Long> deptIdList) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        if (deptIdList == null) {
            return;
        }
        // 先删除角色与部门关系
        Aops.getSelf(this).delete(roleId);
        // 保存数据
        Aops.getSelf(this).saveDept(roleId, deptIdList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveDept(Long roleId, List<Long> deptIdList) {
        // 保存角色与菜单关系
        List<SysRoleDeptEntity> entityList = new ArrayList<>();
        for (Long deptId : deptIdList) {
            SysRoleDeptEntity sysRoleDeptEntity = new SysRoleDeptEntity();
            sysRoleDeptEntity.setDeptId(deptId);
            sysRoleDeptEntity.setRoleId(roleId);
            entityList.add(sysRoleDeptEntity);
        }
        if (entityList.size() > 0) {
            this.saveBatch(entityList);
        }
    }

    @Override
    public List<Long> queryDeptIdList(Long[] roleIds) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryDeptIdList(roleIds);
    }

    @Override
    public int deleteBatch(Long roleIds) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        return Aops.getSelf(this).delete(roleIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public int delete(long roleId) {
        return baseMapper.deleteById(roleId);
    }
}
