package com.dcit.authority.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dcit.authority.dto.RoleResourcesInfoDTO;
import com.dcit.authority.dto.form.RoleResourcesForm;
import com.dcit.authority.dto.form.SysRoleForm;
import com.dcit.authority.exception.AuthException;
import com.dcit.authority.model.SysRole;
import com.dcit.authority.model.SysRoleExample;
import com.dcit.authority.model.SysRoleExample.Criteria;
import com.dcit.authority.model.SysRoleResources;
import com.dcit.authority.service.SysRoleService;
import com.dcit.authority.service.SysUserService;
import com.dcit.authority.shiro.filter.ShiroFilterChainManager;
//import com.dcit.authority.shiro.ShiroKit;
import com.dcit.common.enums.ResultEnum;
import com.dcit.common.utils.BeanCopyUtil;
import com.dcit.common.utils.KeyUtil;
import com.dcit.common.utils.ResultVOUtil;
import com.dcit.common.vo.ResultVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value="角色管理API")
@RestController
@RequestMapping("/role")
@Slf4j
public class SysRoleController {

	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
    private ShiroFilterChainManager shiroFilterChainManager;
	
	@ApiOperation(value = "获取所有的角色列表")
    @GetMapping("/getAllRoles")
	public ResultVO<Object> getAllRoles(){
		SysRoleExample example = new SysRoleExample();
        Criteria criteria = example.createCriteria();
        criteria.andRoleStatusEqualTo("0");
        List<SysRole> sysRoleList = sysRoleService.selectByExample(example);
        
        return ResultVOUtil.success(sysRoleList);
	}
	
	@ApiOperation(value = "查询角色列表")
    @GetMapping("/getRoleList")
    public ResultVO<Object> getRoleList(@RequestParam(required=false,defaultValue="") String roleName,
    		@RequestParam(required = false, defaultValue = "1") int page,
			@RequestParam(required = false, defaultValue = "10") int size) {

    	ModelMap modelMap = new ModelMap();
    	
        PageHelper.startPage(page,size);
        SysRoleExample example = new SysRoleExample();
        Criteria criteria = example.createCriteria();
        //criteria.andRoleStatusEqualTo("0");
        if(!StringUtils.isEmpty(roleName)){
        	criteria.andRoleNameLike("%"+ roleName +"%");
        }
        List<SysRole> sysRoleList = sysRoleService.selectByExample(example);
        PageInfo<SysRole> pageInfo = new PageInfo<SysRole>(sysRoleList);
        
        modelMap.put("pageData", pageInfo.getList());
        modelMap.put("total", pageInfo.getTotal());
        
        return ResultVOUtil.success(modelMap);
    }
	
	@ApiOperation(value = "根据id获取角色详情")
    @GetMapping("/getRoleInfoById/{id}")
	public ResultVO<Object> getRoleInfoById(@PathVariable String id){
		
		SysRole sysRole = sysRoleService.selectByPrimaryKey(id);
		
		return ResultVOUtil.success(sysRole);
		
	}
	
	@ApiOperation(value = "新增编辑角色")
    @PostMapping("/addOrEditRoleInfo")
	public ResultVO<Object> addOrEditRoleInfo(@RequestBody SysRoleForm sysRoleForm,BindingResult bindingResult){
    	
    	if(bindingResult.hasErrors()){
			log.error("【新增编辑角色信息】参数不正确,sysRoleForm={}",sysRoleForm);
			throw new AuthException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
    	
		SysRole sysRole = null;
		try {
			if(StringUtils.isEmpty(sysRoleForm.getId())){
				sysRole = new SysRole();
				
				BeanUtils.copyProperties(sysRoleForm, sysRole, BeanCopyUtil.getNullOrIgnorePropertyNames(sysRoleForm, null));
				
				sysRole.setId(KeyUtil.getUUIDKey());
				//sysRole.setCreateUser(ShiroKit.getUserId());
				sysRoleService.insertSelective(sysRole);
			}else{
				sysRole = sysRoleService.selectByPrimaryKey(sysRoleForm.getId());
				if(null != sysRole){
					BeanUtils.copyProperties(sysRoleForm, sysRole, BeanCopyUtil.getNullOrIgnorePropertyNames(sysRoleForm, null));
					sysRole.setUpdateTime(new Date());
					
					sysRoleService.updateByPrimaryKey(sysRole);
				}else{
					log.error("【编辑角色信息】操作出错,记录不存在,sysRole={},sysRoleForm={}",sysRole,sysRoleForm);
    				throw new AuthException(ResultEnum.NOT_EXIST);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【新增编辑用户信息】操作出错,error={},sysRoleForm={}",e.getMessage(),sysRoleForm);
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success(sysRole);
    	
	}
	
	@ApiOperation(value = "删除角色")
    @GetMapping("/delRoleInfoById/{id}")
	public ResultVO<Object> delRoleInfoById(@PathVariable String id){
		try {
			SysRole sysRole = sysRoleService.selectByPrimaryKey(id);
			if(null != sysRole){
				sysRole.setRoleStatus("1");
				sysRole.setUpdateTime(new Date());
				
				sysRoleService.updateByPrimaryKeySelective(sysRole);
				
				//级联删除角色用户关联关系
				sysUserService.deleteRoleUsersByRoleId(id);
				
				//级联删除角色资源关联关系
				sysRoleService.deleteRoleResourcesByRoleId(id);
				
				//重新加载角色权限
	        	shiroFilterChainManager.reloadFilterChain();
				
			}else{
				log.error("【删除角色信息】操作出错,记录不存在,roleId={}",id);
				throw new AuthException(ResultEnum.NOT_EXIST);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【删除角色信息】操作出错,error={}",e.getMessage());
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
		
    	return ResultVOUtil.success();
	}
	
	
	@ApiOperation(value = "查询角色资源")
    @GetMapping("/getRoleResourcesByRoleId/{roleId}")
	public ResultVO<Object> getRoleResourcesByRoleId(@PathVariable String roleId,@RequestParam String resourceType){
		
		List<RoleResourcesInfoDTO> resTree = new ArrayList<RoleResourcesInfoDTO>();
		
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("roleId", roleId);
			map.put("resourceType", resourceType);
			
			List<RoleResourcesInfoDTO> dtoList = sysRoleService.selectRoleResourcesByRoleId(map);
			
			for(RoleResourcesInfoDTO dto : dtoList){
				if(!StringUtils.isEmpty(dto.getParentId()) && dto.getParentId().equals("0")){
					resTree.add(dto);
				}
			}
			
			for(RoleResourcesInfoDTO pTree : resTree){
				List<RoleResourcesInfoDTO> childTree = new ArrayList<RoleResourcesInfoDTO>();
				for(RoleResourcesInfoDTO dto : dtoList){
					if(!StringUtils.isEmpty(dto.getParentId()) && dto.getParentId().equals(pTree.getResourceId())){
						childTree.add(dto);
					}
				}
				pTree.setChildList(childTree);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【查询角色资源信息】操作出错,error={}",e.getMessage());
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
		
		return ResultVOUtil.success(resTree);
	}
	
	@Transactional
	@ApiOperation(value = "新增编辑角色资源")
    @PostMapping("/addOrEditRoleResources")
	public ResultVO<Object> addOrEditRoleResources(@RequestBody List<RoleResourcesForm> roleResourcesFormList, BindingResult bindingResult){
    	
    	if(bindingResult.hasErrors()){
			log.error("【新增编辑角色资源】参数不正确,roleResourcesFormList={}",roleResourcesFormList);
			throw new AuthException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
    	
    	try {
    		//先删除所有roleId的资源，再全部保存
    		sysRoleService.deleteRoleResourcesByRoleId(roleResourcesFormList.get(0).getRoleId());
        	
        	for(RoleResourcesForm form : roleResourcesFormList){
        		
        		SysRoleResources sysRoleResources = new SysRoleResources();
        		BeanUtils.copyProperties(form, sysRoleResources, BeanCopyUtil.getNullOrIgnorePropertyNames(form, null));
        		if(StringUtils.isEmpty(form.getRid())){
        			sysRoleResources.setId(KeyUtil.getUUIDKey());
        		}else{
        			sysRoleResources.setId(form.getRid());
        		}
        		
        		sysRoleService.addRoleResources(sysRoleResources);
        	}
        	
        	//重新加载角色权限
        	shiroFilterChainManager.reloadFilterChain();
        	
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【新增编辑角色资源】操作出错,error={}",e.getMessage());
			throw new AuthException(ResultEnum.OPERATION_FAIL);
		}
    	
    	
		return ResultVOUtil.success();
	}
}
