package com.goafanti.permission.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

import com.goafanti.common.dao.RoleMapper;
import com.goafanti.common.dao.RolePermissionMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.dao.UserRoleMapper;
import com.goafanti.common.model.Role;
import com.goafanti.common.model.RolePermission;
import com.goafanti.common.model.UserRole;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.permission.bo.RoleBo;
import com.goafanti.permission.bo.RolePermissionBo;
import com.goafanti.permission.service.NewRoleService;
@Service
public class NewRoleServiceImpl extends BaseMybatisDao<RoleMapper> implements NewRoleService {
	@Autowired
	RoleMapper				roleMapper;
	@Autowired
	UserMapper				userMapper;
	@Autowired
	UserRoleMapper			userRoleMapper;
	@Autowired
	RolePermissionMapper	rolePermissionMapper;
	@Override
	public Pagination<RoleBo> findRoles(RoleBo role, Integer pageNo, Integer pageSize) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String,Object> params =disposeParams(role);
		@SuppressWarnings("unchecked")
		Pagination<RoleBo> p=(Pagination<RoleBo>)findPage("selectRoleList","selectRoleCount",params,pageNo,pageSize);		
		@SuppressWarnings("unchecked")
		List<RoleBo> list=(List<RoleBo>) p.getList();
		for(RoleBo i:list){
			if(i.getCreateTime()!=null){
				i.setCreateTimez(sdf.format(i.getCreateTime()));
			}
			
		}
		return p;
	}
	private Map<String,Object> disposeParams(RoleBo role){
		Map<String,Object> params = new HashMap<String, Object>();			
		if(StringUtils.isNotBlank(role.getRoleName())) params.put("roleName", role.getRoleName());		
		return params;
		
	}
	
	@Override
	public Set<String> findRoleByUserId(String userId) {
		return roleMapper.findRoleByUserId(userId);
	}

	

	@Override
	public int insert(List<Role> records) {
		return roleMapper.insertBatch(records);
	}

	@Override
	public int deleteByPrimaryKeys(List<String> records) {
		rolePermissionMapper.deleteByRoleId(records);
		userRoleMapper.deleteByRoleId(records);
		List<String> data= userRoleMapper.findUserIdByRoleIds(records);
		TokenManager.clearUserAuthByUserId(data.toArray(new String[]{}));
		return roleMapper.deleteByPrimaryKeys(records);
	}


	@Override
	public int bindPermission(String rid, String pid) {
		TokenManager.clearUserAuthByUserId((String[]) userRoleMapper.findUserIdByRoleId(rid).toArray());
		return rolePermissionMapper.insert(new RolePermission(rid, pid));
	}

	@Override
	public int bindUser(String rid, String uid) {
		TokenManager.clearUserAuthByUserId(new String[] { uid });
		return userRoleMapper.insert(new UserRole(uid, rid));
	}

	@Override
	public int unbindPermission(String roleId, String permissionId) {
		Map<String, Object> params = new HashMap<>();
		params.put("rid", roleId);
		params.put("pid", permissionId);
		TokenManager.clearUserAuthByUserId((String[]) userRoleMapper.findUserIdByRoleId(roleId).toArray());
		return rolePermissionMapper.deleteByPrimaryKey(params);
	}

	@Override
	public int unbindUser(String roleId, String userId) {
		Map<String, Object> params = new HashMap<>();
		params.put("rid", roleId);
		params.put("uid", userId);
		TokenManager.clearUserAuthByUserId(new String[] { userId });
		return userRoleMapper.deleteByUserRole(params);
	}

	@Override
	public int insert(Role record, List<String> permissions) {
		Date now = new Date();
		if (record.getId() != null) {
			List<RolePermission> rps = new ArrayList<>();
			rolePermissionMapper.deleteByRid(record.getId());
			for (String pid : permissions) {
				rps.add(new RolePermission(record.getId(), pid));
			}
			if (!rps.isEmpty()) {
				rolePermissionMapper.insertBatch(rps);
			}
			List<String> ids = userRoleMapper.findUserIdByRoleId(record.getId());
			TokenManager.clearUserAuthByUserId(ids.toArray(new String[ids.size()]));
		}
		record.getId();
		record.setCreater("管理员");		
		record.setCreateTime(now);
		return roleMapper.insert(record);
	}
	@Override
	public List<RolePermissionBo> selectRolePList(String id) {
		List<RolePermissionBo> list=roleMapper.selectRolePList(id);
		return list;
	}
	
}
