package com.yonge.cooleshow.auth.service.impl;

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

import com.yonge.toolset.mybatis.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonge.cooleshow.auth.api.entity.SysRole;
import com.yonge.cooleshow.auth.dal.dao.SysRoleDao;
import com.yonge.cooleshow.auth.dal.dao.SysRoleMenuDao;
import com.yonge.cooleshow.auth.service.SysRoleService;
import com.yonge.toolset.mybatis.dal.BaseDAO;
import com.yonge.toolset.base.exception.BizException;

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

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

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

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

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

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateRole(SysRole sysRole) {
		SysRole findByName = sysRoleDao.findByRoleName(sysRole.getRoleName());
		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(Long id) {
		sysRoleDao.delete(id);
		sysRoleMenuDao.deleteAllMenu(id);
	}

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

	private void batchSave(SysRole sysRole){
		List<Long> menuIds = sysRole.getMenuIds();
		if(menuIds != null && menuIds.size() > 0){
//			SysRoleMenu sysRoleMenu = new SysRoleMenu(sysRole.getId(),null);
			sysRoleMenuDao.batchAdd(sysRole.getId(),menuIds);
//			menuIds.forEach(e->{
//				sysRoleMenu.setMenuId(e);
//				sysRoleMenuDao.insert(sysRoleMenu);
//			});
		}
	}

}