package com.keao.edu.auth.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.keao.edu.auth.api.entity.SysRole;
import com.keao.edu.auth.dal.dao.SysRoleDao;
import com.keao.edu.auth.dal.dao.SysRoleMenuDao;
import com.keao.edu.auth.service.SysRoleService;
import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.service.impl.BaseServiceImpl;

@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){
		return sysRoleDao.findRoleByCode(code);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addRole(SysRole sysRole) {
		sysRoleDao.insert(sysRole);
		batchSave(sysRole);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateRole(SysRole sysRole) {
		sysRole.setUpdateTime(new Date());
		sysRoleDao.update(sysRole);
		sysRoleMenuDao.deleteAllMenu(sysRole.getId());
		batchSave(sysRole);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delRole(Integer 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){
//			SysRoleMenu sysRoleMenu = new SysRoleMenu(sysRole.getId(),null);
			sysRoleMenuDao.batchAdd(sysRole.getId(),menuIds,sysRole.getTenantId());
//			menuIds.forEach(e->{
//				sysRoleMenu.setMenuId(e);
//				sysRoleMenuDao.insert(sysRoleMenu);
//			});
		}
	}

}