	package com.blueland.sys.power.web;


import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blueland.constant.RedisConstant;
import com.blueland.annotation.Log;
import com.blueland.model.TPfApplication;
import com.blueland.model.TPfAuth;
import com.blueland.model.TPfRole;
import com.blueland.result.R;
import com.blueland.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.blueland.bo.MenuEntity;
/**
 * @author 代码自动生成工具
 * @version 1.0
 * @since  
 * @author cg
 */
import com.blueland.bo.RoleEntity;
import com.blueland.bo.RoleUserRest;
import com.blueland.bo.TucStaffEntity;
import com.blueland.service.impl.TucStaffServiceImpl;

import io.swagger.annotations.Api;

import static com.blueland.constant.CommonConstant.*;
import static com.blueland.constant.ResponseConstant.*;

	@Slf4j
@Api(value = "role")
@RestController
@RequestMapping(value = "/role")
public class RoleRest {
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private TucStaffServiceImpl pubUserService;
	@Autowired
	private IApplicationService appService;
	@Autowired
	private IMenuService iMenuService;
	@Autowired
	private IAuthService authService;

	@Autowired
	private SysRedisService sysRedisService;
	
	
	
	/**
	 * 根据应用ID、员工ID查询有权限访问的菜单列表资源
	 * @author changgao
	 * 2019年4月24日14:34:54 
	 */
	@RequestMapping(value = "/{appId}/auth/{userId}/resource",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listMenuUser(@PathVariable("appId") String appId,@PathVariable("userId") String userId,String menuType,String menuId,
			HttpServletRequest request,HttpServletResponse response){
		Map < String , Object > result = new HashMap< String , Object>();
		List<MenuEntity> menuEntryList = null;
		try {
			if(StringUtils.isBlank(appId)||StringUtils.isBlank(userId)){
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "输入参数异常");
			}else{
				TucStaffEntity userEntry = pubUserService.getStaffByStaffId(userId);
				TPfApplication appEntity = appService.getById(appId);
				if(userEntry==null){
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "用户ID错误");
				}else if(appEntity==null){
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "应用ID错误");
				}else{
					menuEntryList = iMenuService.getMenu(appId, userId, menuType,menuId);
					if(menuEntryList.isEmpty()){
						menuEntryList = iMenuService.getMenuIsOpenStatus(appId);
					}
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("resultMsg", "处理成功");
					result.put("result", menuEntryList);
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 根据应用ID查询角色列表
	 */
	@RequestMapping(value = "/{appId}/role",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public R<Page<RoleEntity>> listRole(@PathVariable("appId") String appId,@RequestParam Map<String,Object> queryParams,HttpServletRequest request,HttpServletResponse response) {
		int curPageSize = 10;
		int curPage = 1;
		if(queryParams.containsKey("pageSize")){
			curPageSize =Integer.parseInt(queryParams.get("pageSize").toString());
		}
		if(queryParams.containsKey("pageNum")){
			curPage =Integer.parseInt(queryParams.get("pageNum").toString());
		}
		queryParams.put("appId", appId);
		if(StringUtils.isBlank(appId)){
			throw new RuntimeException("输入参数异常");
		}
		TPfApplication appEntity = appService.getById(appId);
		if(appEntity==null){
			throw new RuntimeException("应用ID错误");
		}
		Page<RoleEntity> RoleRestList =roleService.getAppRole(queryParams,curPage,curPageSize);
		return R.ok(RoleRestList);
	}
	
	/**
	 * 成员管理
	 * 角色里面有的成员（用户）
	 */
	@RequestMapping(value = "/{appId}/role/{roleId}/users",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listRoleUser(@PathVariable("appId") String appId,@PathVariable("roleId")String roleId,
			String companyId,String deptId,String orgId,
			Integer curPage,Integer curPageSize,HttpServletRequest request,HttpServletResponse response)  {
		Map < String , Object > result = new HashMap< String , Object>(); 
		Page<RoleUserRest> RoleUserRestList = null;
		if(curPageSize==null){
			curPageSize =9999;
		}
		if(curPage==null){
			curPage =1;
		}
		try {
			if(StringUtils.isBlank(appId)){
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "输入参数异常");
			}else{
				TPfApplication app = appService.getById(appId);
				int role = roleService.findAppidByRoleId(appId,roleId);
			    if(app==null){
			    	result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "应用ID错误");
				}else if(role==0){
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "角色ID错误");
				}else{
					RoleUserRestList =pubUserService.getAppRoleUser2(appId,roleId,companyId,deptId,orgId,curPage,curPageSize);
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("pageNum", RoleUserRestList.getCurrent());
					result.put("pageSize", RoleUserRestList.getSize());
					result.put("total", RoleUserRestList.getTotal());
					result.put("pages", RoleUserRestList.getPages());
					result.put("resultMsg", "处理成功");
					result.put("result", RoleUserRestList.getRecords());
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 
	 * 根据角色返回对应资源
	 **/
	@RequestMapping(value = "/{roleId}/{appId}/resource",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listRoleMenu(@PathVariable("roleId") String roleId,@PathVariable("appId") String appId,HttpServletRequest request,HttpServletResponse response){
		List<MenuEntity> menuEntity = null;
		Map < String , Object > result = new HashMap< String , Object>(); 
		try {
			
			if(StringUtils.isBlank(roleId)){
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "输入参数异常");
			}else{
				int o = roleService.findAppidByRoleId(roleId,appId);
			    if(o>0){
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "角色错误");
				}else{
					menuEntity = iMenuService.listRoleMenu(roleId,appId);
					result.put("resultMsg", "处理成功");
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("result", menuEntity);
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	
	
	/** 
	 * 搜索对象 
	 **/
	@RequestMapping(value = "",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Page<RoleEntity>> list(RoleEntity roleEntity) {
		Page<RoleEntity> page = this.roleService.findPage(roleEntity);
		return R.ok(page);
	}

	
	/** 
	 * 查看对象
	 **/
	@RequestMapping(value = "/{roleId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TPfRole> view(@PathVariable String roleId)  {
		TPfRole roleEntity  = roleService.getById(roleId);
		return R.ok(roleEntity);
	}


	/** 
	 * 查看对象（支持多条件查询）
	 **/
	@RequestMapping(value = "get",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TPfRole> get(RoleEntity model)  {
		TPfRole roleEntity  = roleService.get(model);
		return R.ok(roleEntity);
	}

	/** 
	 * 新增对象
	 **/
	@Log(busiType = "新增角色", opType = SAVE, type = "web")
	@RequestMapping(value = "save",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<RoleEntity> save(HttpServletRequest request,@RequestBody RoleEntity model)  {
        String[] authRole = model.getAuthRole();
		TPfRole role = BeanUtil.copyProperties(model, TPfRole.class);
        if (authRole.length > 0) {
            authService.deleteRole(model.getRoleId(), model.getAppId());
            for (int i = 0; i < authRole.length; i++) {
				TPfAuth authEntity = new TPfAuth();
                authEntity.setMenuId(authRole[i]);
                authEntity.setAppId(model.getAppId());
                authEntity.setStatus("Y");
                authEntity.setCreatorId("czadmin");
                authEntity.setCreateDate(new Date());
                authEntity.setUpdatorId("czadmin");
                authEntity.setUpdateDate(new Date());
                authEntity.setRoleId(model.getRoleId());
                authService.save(authEntity);
                try {
                    //新增redis
					sysRedisService.flushMenuId();
                }catch (Exception e){
                    log.info("新增redis数据失败->参数:"+authRole[i]+"，位置: RoleRest.save");
                }
            }
        }
		role.setCreatorId("czadmin");
		role.setUpdatorId("czadmin");
		role.setCreateDate(new Date());
		role.setUpdateDate(new Date());
        roleService.save(role);
//		LogUtil.addSysOplog(request, model.getRoleId(), "角色", CommonConstant.OPTYPE_ADD, "role/add,操作人", "success", "sys", "");
        return R.ok(model);
	}
	
	
	/**
	 * 更新对象
	 * @return 
	 **/
	@Log(busiType = "修改角色", opType = UPDATE, type = "web")
	@RequestMapping(value = "update",method = RequestMethod.PUT,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<RoleEntity> update(HttpServletRequest request, @RequestBody RoleEntity model)  {
		String[] authRole = model.getAuthRole();
		TPfRole role = BeanUtil.copyProperties(model, TPfRole.class);
		if(authRole.length>0) {
		  authService.deleteRole(model.getRoleId(),model.getAppId());
		  for(int i=0;i<authRole.length;i++){
			  TPfAuth authEntity = new TPfAuth();
			  authEntity.setMenuId(authRole[i]);
			  authEntity.setAppId(model.getAppId());
			  authEntity.setStatus("Y");
			  authEntity.setCreatorId("czadmin");
			  authEntity.setCreateDate(new Date());
			  authEntity.setUpdatorId("czadmin");
			  authEntity.setUpdateDate(new Date());
			  authEntity.setRoleId(model.getRoleId());
			  authService.save(authEntity);
			  try {
                  //更新redis
				  sysRedisService.flushMenuId();
              } catch (Exception e){
                  log.info("更新redis数据失败->参数:"+authRole[i]+"，位置: RoleRest.update");
              }
          }
		}
		role.setUpdatorId("czadmin");
		role.setUpdateDate(new Date());
		roleService.updateById(role);
		return R.ok(model);
	}
	
	/**
	 * 删除对象
	 * @return 
	 **/
	@Log(busiType = "删除角色", opType = DELETE, type = "web")
	@RequestMapping(value = "delete",method = RequestMethod.DELETE,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Boolean> delete(@RequestParam Map<String,Object> queryParams,HttpServletRequest request,HttpServletResponse response) {
		authService.deleteRole(queryParams.get("roleId").toString(),queryParams.get("appId").toString());
		roleService.deleteRole(queryParams);
		sysRedisService.flushMenuId();
		return R.ok();
	}
	
	/**
	 *  批量删除对象
	 * @return 
	 **/
	@Log(busiType = "批量删除角色", opType = DELETE, type = "web")
	@RequestMapping(value = "deleteBatch",method = RequestMethod.DELETE,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TPfRole> deleteBatch(String[] ids) {
		roleService.removeByIds(Arrays.asList(ids));
		try {
			sysRedisService.flushMenuId();
		} catch (Exception e){
			log.info("删除redis数据失败");
		}
		return R.ok();
	}
	
	/** 
	 * 角色新增用户
	 **/
	@Log(busiType = "角色新增用户", opType = SAVE, type = "web")
	@RequestMapping(value = "save/user",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> saveUser(@RequestBody RoleEntity model,HttpServletRequest request)  {
		Map < String , Object > result = new HashMap< String , Object>(); 
		if(StringUtils.isBlank(model.getRoleId())) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "角色ID不能为空");
		}else if(StringUtils.isBlank(model.getAppId())) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "应用ID不能为空");
		}else {
			int role = roleService.findAppidByRoleId(model.getAppId(),model.getRoleId());
			TPfApplication app = appService.getById(model.getAppId());
			if(role==0) {
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "角色ID错误");
			}else if(app==null) {
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "应用ID错误");
			}else {
				result = roleService.saveRoles(model);
			}
		}
		return result;
	}
	
	/** 
	 * 角色删除用户
	 **/
	@Log(busiType = "角色删除用户", opType = DELETE, type = "web")
	@RequestMapping(value = "/user",method = RequestMethod.DELETE,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> deleteUser(@RequestBody RoleEntity model)  {
		Map < String , Object > result = new HashMap< String , Object>(); 
		if(StringUtils.isBlank(model.getRoleId())) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "角色ID不能为空");
		}else if(StringUtils.isBlank(model.getAppId())) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "应用ID不能为空");
		}else {
			TPfRole role = roleService.getById(model.getRoleId());
			TPfApplication app = appService.getById(model.getAppId());
			if(role==null) {
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "角色ID错误");
			}else if(app==null) {
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "应用ID错误");
			}else {
				String[] userIds = model.getUserId();
				if(userIds.length>0) {
					for(int i=0;i<userIds.length;i++){
						TucStaffEntity pubUser =  pubUserService.getStaffByStaffId(userIds[i]);
						if(pubUser!=null) {
							roleService.deleteUserId(model.getAppId(),model.getRoleId(),userIds[i]);
						}
						result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
						result.put("resultMsg", "处理成功");
						result.put("result", "true");
					}
				}
			}
		}
		return result;
	}
	
	/**
	 * 根据角色ID、用户ID判断用户是否属于该角色
	 * gaoch
	 * 2019年4月29日
	 */
	@RequestMapping(value = "/{appId}/role/{roleId}/users/{userId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public  Map<String, Object> findRoleUserBy(@PathVariable("appId") String appId,
			@PathVariable("roleId") String roleId,
			@PathVariable("userId") String userId,
			HttpServletRequest request,HttpServletResponse response)  {
		Map < String , Object > result = new HashMap< String , Object>(); 
		Map < String , Object > queryParams = new HashMap< String , Object>(); 
		List<RoleEntity> roleEntryList = null;
		boolean isRole=false;
		try {
			if(StringUtils.isBlank(appId)){
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "appId不能为空");
			}else if(StringUtils.isBlank(roleId)) {
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "roleId不能为空");
			}else if(StringUtils.isBlank(userId)) {
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "userId不能为空");
			}else{
				TPfApplication app = appService.getById(appId);
				int role = roleService.findAppidByRoleId(appId,roleId);
				TucStaffEntity user = pubUserService.getStaffByStaffId(userId);
			    if(app==null){
			    	result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "应用ID错误");
				}else if(role==0){
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "角色ID错误");
				}else if(user == null) {
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "用户ID错误");
				}else{
					queryParams.put("appId", appId);
					queryParams.put("roleId", roleId);
					queryParams.put("userId", userId);
					roleEntryList = roleService.findRoleUserBy(queryParams);
					if(roleEntryList.size()>0) {
						isRole=true;
					}
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("resultMsg", "处理成功");
					result.put("result", isRole);
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
}



