package com.ym.mec.auth.service.impl;

import com.ym.mec.auth.api.entity.SysRole;
import com.ym.mec.auth.dal.dao.SysRoleDao;
import com.ym.mec.auth.dal.dao.SysRoleMenuDao;
import com.ym.mec.auth.service.SysRoleService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SysRoleServiceImpl extends BaseServiceImpl<Integer, SysRole>  implements SysRoleService {
	
	@Autowired
	private SysRoleDao sysRoleDao;
	@Autowired
	private SysRoleMenuDao sysRoleMenuDao;

	@Override
	public BaseDAO<Integer, SysRole> getDAO() {
		return sysRoleDao;
	}

	@Override
	public List<SysRole> findRoleByUserId(Integer userId) {
		return sysRoleDao.findRoleByUserId(userId);
	}

	@Override
	public SysRole findRoleByCode(String code, Integer tenantId){
		return sysRoleDao.findRoleByCode(code, tenantId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addRole(SysRole sysRole) {
		SysRole findByName = sysRoleDao.findByRoleName(sysRole.getRoleName(),sysRole.getTenantId());
		if(findByName != null){
			throw new BizException("操作失败：角色 {} 已存在",sysRole.getRoleName());
		}
		sysRoleDao.insert(sysRole);
		batchSave(sysRole);
	}

	public void checkManageRole(Integer id){
		Integer tenantId = TenantContextHolder.getTenantId();
		Integer roleId = sysRoleDao.getMinRoleId(tenantId);
		if(roleId.equals(id)){
			throw new BizException("操作失败：机构管理员角色不允许调整");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateRole(SysRole sysRole) {
		this.checkManageRole(sysRole.getId());
		SysRole findByName = sysRoleDao.findByRoleName(sysRole.getRoleName(),sysRole.getTenantId());
		if(findByName != null && !findByName.getId().equals(sysRole.getId())){
			throw new BizException("操作失败：角色 {} 已存在",sysRole.getRoleName());
		}
		sysRole.setUpdateTime(new Date());
		sysRoleDao.update(sysRole);
		sysRoleMenuDao.deleteAllMenu(sysRole.getId());
		batchSave(sysRole);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delRole(Integer id) {
		this.checkManageRole(id);
		sysRoleDao.delete(id);
		sysRoleMenuDao.deleteAllMenu(id);
	}

	@Override
	public SysRole getRole(Integer id) {
		SysRole sysRole = sysRoleDao.get(id);
		sysRole.setMenuIds(sysRoleMenuDao.queryMenuIdByRoleId(id));
		return sysRole;
	}

	private void batchSave(SysRole sysRole){
		List<Integer> menuIds = sysRole.getMenuIds();
		if(menuIds != null && menuIds.size() > 0){
			sysRoleMenuDao.batchAdd(sysRole.getId(),menuIds, sysRole.getTenantId());
		}
	}

}