package com.blueland.render.rest;


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

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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blueland.annotation.ApiVersion;
import com.blueland.core.util.UserUtils;
import com.blueland.enums.Version;
import com.blueland.model.TPfApplication;
import com.blueland.model.TPfRole;
import com.blueland.result.R;
import com.blueland.service.*;
import io.swagger.annotations.ApiOperation;
import com.blueland.annotation.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.blueland.bo.MenuEntity;
import com.blueland.bo.Role2userEntity;
import com.blueland.bo.RoleEntity;
import com.blueland.bo.RoleUserRest;
import com.blueland.bo.TucStaffEntity;

import io.swagger.annotations.Api;

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


@Api(value = "role")
@RestController
@RequestMapping(value = "/role")
public class RoleRest {
	@Autowired
	private IRoleService roleServiceImpl;
	@Autowired
	private ITucStaffService pubUserService;
	@Autowired
	private IApplicationService appService;
	@Autowired
	private IMenuService menuServiceImpl;
	@Autowired
	private IRole2userService iRole2userService;

	@Autowired
	private SysRedisService sysRedisService;
	
	
	/**
	 * 根据应用ID、员工ID查询有权限访问的菜单列表资源
	 * @author changgao
	 * 2019年4月24日14:34:54 
	 */
	@RequestMapping(value = "/auth/{userId}/resource",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> listMenuUser(@PathVariable("userId") String userId,String menuType,String menuId,
			HttpServletRequest request,HttpServletResponse response){
		String appId = UserUtils.getTenantId();
		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 = menuServiceImpl.getMenu(appId, userId, menuType,menuId);
					//BUG9522 测试环境把黄鹃的账号与生科有关的全部角色移除后，
					//使用黄鹃的账号依然可以看到很多菜单，以及有新建客户、订单的权限
					/*if(menuEntryList.isEmpty()){
						menuEntryList = menuService.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、员工ID查询有权限访问的菜单列表资源
	 * @author changgao
	 * 2019年4月24日14:34:54 
	 */
	@RequestMapping(value = "/{menuCode}/auth/{userId}/resource",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> listMenuCode(@PathVariable("menuCode") String menuCode,@PathVariable("userId") String userId,
			String menuType,HttpServletRequest request,HttpServletResponse response){
		String appId = UserUtils.getTenantId();
		Map < String , Object > result = new HashMap< String , Object>(); 
		List<MenuEntity> menuEntryList = null;
		try {
			if(menuType==null) {
				menuType = "button";
			}else if(menuType.equals("all")) {
				menuType = "";
			}
				TucStaffEntity userEntry = pubUserService.getStaffByStaffId(userId);
				if(userEntry==null){
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "用户ID错误");
				}else{
					menuEntryList = menuServiceImpl.getMenuCode(menuCode, userId,appId,menuType);
					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 = "/listRole",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listRole(@RequestParam Map<String,Object> queryParams,HttpServletRequest request,HttpServletResponse response) {
		String appId = UserUtils.getTenantId();
		Map < String , Object > result = new HashMap< String , Object>();
		Page<RoleEntity> RoleRestList = null;
		int curPageSize = 10;
		int curPage = 1;
		if(queryParams.containsKey("curPageSize")){
			curPageSize =Integer.parseInt(queryParams.get("curPageSize").toString());
		}
		if(queryParams.containsKey("curPage")){
			curPage =Integer.parseInt(queryParams.get("curPage").toString());
		}
		queryParams.put("appId", appId);
		try {
			if(StringUtils.isBlank(appId)){
				result.put("resultCode", "401");
				result.put("resultMsg", "输入参数异常");
			}else{
				TPfApplication appEntity = appService.getById(appId);
			    if(appEntity==null){
					result.put("resultCode", "401");
					result.put("resultMsg", "应用ID错误");
				}else{
					RoleRestList = roleServiceImpl.getAppRole(queryParams,curPage,curPageSize);
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("pageNum", RoleRestList.getCurrent());
					result.put("pageSize", RoleRestList.getSize());
					result.put("total", RoleRestList.getTotal());
					result.put("pages", RoleRestList.getPages());
					result.put("resultMsg", "处理成功");
					result.put("result", RoleRestList.getRecords());
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 成员管理
	 * 角色里面有的成员（用户）
	 */
	@RequestMapping(value = "/{roleId}/users",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listRoleUser(@PathVariable("roleId")String roleId,
			String companyId,String deptId,String orgId,
			Integer curPage,Integer curPageSize,HttpServletRequest request,HttpServletResponse response)  {
		String appId = UserUtils.getTenantId();
		Map < String , Object > result = new HashMap< String , Object>(); 
		Page<RoleUserRest> RoleUserRestList = null;
		if(curPageSize==null){
			curPageSize =10;
		}
		if(curPage==null){
			curPage =1;
		}
		try {
			if(StringUtils.isBlank(appId)){
				result.put("resultCode", "401");
				result.put("resultMsg", "输入参数异常");
			}else{
				TPfApplication app = appService.getById(appId);
				TPfRole role = roleServiceImpl.getById(roleId);
			    if(app==null){
			    	result.put("resultCode", "401");
					result.put("resultMsg", "应用ID错误");
				}else if(role==null){
					result.put("resultCode", "401");
					result.put("resultMsg", "角色ID错误");
				}else{
					RoleUserRestList = pubUserService.getAppRoleUser(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;
	}
	
	/**
	 * 获取用户租户下面所有角色（区分租户）
	 * @param appId
	 * @param userId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/user/{userId}/roles",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listUserRole(@PathVariable("userId")String userId,
			HttpServletRequest request,HttpServletResponse response)  {
		String appId = UserUtils.getTenantId();
		Map < String , Object > result = new HashMap< String , Object>(); 
		try {
			if(StringUtils.isBlank(appId) || StringUtils.isBlank(userId)){
				result.put("resultCode", "401");
				result.put("resultMsg", "输入参数异常");
			}else{
				TPfApplication app = appService.getById(appId);
				TucStaffEntity user = pubUserService.getStaffByStaffId(userId);
			    if(app==null){
			    	result.put("resultCode", "401");
					result.put("resultMsg", "应用ID错误");
				}else if(user==null){
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "用户ID错误");
				}else{
					List<RoleEntity> roleEntryList = roleServiceImpl.findRolesByUser(appId, userId);
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("resultMsg", "处理成功");
					result.put("result", roleEntryList);
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 
	 * 根据角色返回对应资源
	 **/
	@RequestMapping(value = "/{roleId}/resource",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listRoleMenu(@PathVariable("roleId") String roleId,HttpServletRequest request,HttpServletResponse response){
		String appId = UserUtils.getTenantId();
		List<MenuEntity> menuEntity = null;
		Map < String , Object > result = new HashMap< String , Object>(); 
		try {
			
			if(StringUtils.isBlank(roleId)){
				result.put("resultCode", "401");
				result.put("resultMsg", "输入参数异常");
			}else{
				int rolecount = roleServiceImpl.findAppidByRoleId( appId,roleId);
			    if(rolecount <= 0){
					result.put("resultCode", "401");
					result.put("resultMsg", "查无此角色！");
				}else{
					menuEntity = menuServiceImpl.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;
	}
	
	
	
	/**
	 * 根据角色ID、用户ID判断用户是否属于该角色
	 * gaoch
	 * 2019年4月29日
	 */
	@RequestMapping(value = "/{roleId}/users/{userId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public  Map<String, Object> findRoleUserBy(@PathVariable("roleId") String roleId,
			@PathVariable("userId") String userId,
			HttpServletRequest request,HttpServletResponse response)  {
		String appId = UserUtils.getTenantId();
		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 = roleServiceImpl.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 = roleServiceImpl.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;
	}
	
	/** 
	 * 角色新增用户
	 **/
	@Log(busiType = "角色新增用户", opType = SAVE, type = "render")
	@RequestMapping(value = "/user",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> saveUser(@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 {
			int role = roleServiceImpl.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 {
				try {
					String[] userIds = model.getUserId();
					if (userIds.length > 0) {
						for (int i = 0; i < userIds.length; i++) {
							TucStaffEntity pubUser = pubUserService.getStaffByStaffId(userIds[i]);
							int cout = roleServiceImpl.findUserId(model.getAppId(), model.getRoleId(), userIds[i]);
							if (pubUser != null && cout == 0) {
								Role2userEntity role2user = new Role2userEntity();
								role2user.setRoleId(model.getRoleId());
								role2user.setUserId(userIds[i]);
								role2user.setStatus("Y");
								role2user.setCreatorId("czadmin");
								role2user.setUpdatorId("czadmin");
								role2user.setOrgId(pubUser.getOrgId());
								role2user.setOrgName(pubUser.getOrgName());
								role2user.setTitleId(null);
								role2user.setCreateDate(new Date());
								role2user.setUpdateDate(new Date());
								role2user.setAppId(model.getAppId());
								roleServiceImpl.saveUser(role2user);
							}
							result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
							result.put("resultMsg", "处理成功");
							result.put("result", "true");
						}
					}
				} catch (Exception e) {
					result.put("resultCode", RESULT_SERVER_ERR_CODE);
				    result.put("resultMsg", "处理失败" +e.getMessage());
				    result.put("result", "false");
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	/** 
	 * 角色删除用户
	 **/
	@Log(busiType = "角色删除用户", opType = DELETE, type = "render")
	@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 {
			int role = roleServiceImpl.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 {
				try {
					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) {
							  roleServiceImpl.deleteUserId(model.getAppId(),model.getRoleId(),userIds[i]);
						  }
						  result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
						  result.put("resultMsg", "处理成功");
						  result.put("result", "true");
					   }
					}
				} catch (Exception e) {
					result.put("resultCode", RESULT_SERVER_ERR_CODE);
				    result.put("resultMsg", "处理失败" +e.getMessage());
				    result.put("result", "false");
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	@RequestMapping(value = "/operation/button/{userId}/{menuCode}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Map<String,Object>> getOperationButton (@PathVariable String userId, @PathVariable String menuCode){
		String appId = UserUtils.getTenantId();
		Map<String, Object> rs = menuServiceImpl.getButton(appId, userId, menuCode);
		return R.ok(rs);
	}
	
	/**
	 * 获取用户下面所有角色(不区分租户)
	 * @param userId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/user/{userId}/rolesNoAppId",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listRoleByUser(
			@PathVariable("userId")String userId,
			HttpServletRequest request,HttpServletResponse response)  
	{
		Map < String , Object > result = new HashMap< String , Object>(); 
		try {
			if(StringUtils.isBlank(userId)){
				result.put("resultCode", "401");
				result.put("resultMsg", "输入参数异常");
			}else{
				TucStaffEntity user = pubUserService.getStaffByStaffId(userId);
			    if(user==null){
					result.put("resultCode", RESULT_CODE_ERROR_CODE);
					result.put("resultMsg", "用户ID错误");
				}else{
					List<RoleEntity> roleEntryList = roleServiceImpl.findRoleTenantidByUserid(userId);
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("resultMsg", "处理成功");
					result.put("result", roleEntryList);
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 成员管理200200728 add
	 * 角色里面有的成员（用户）
	 */
	@RequestMapping(value = "/{roleId}/userlist",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
	@ResponseBody
	@CrossOrigin
	public Map<String, Object> listRoleUserlist(@PathVariable("roleId")String roleId,
			String companyId,String deptId,String orgId,
			HttpServletRequest request,HttpServletResponse response) 
	{
		String appId = UserUtils.getTenantId();
		Map <String, Object> result = new HashMap<String, Object>(); 
		try {
			if(StringUtils.isBlank(appId)){
				result.put("resultCode", "401");
				result.put("resultMsg", "输入参数异常");
			}else{
				TPfApplication app = appService.getById(appId);
				int rolecount = roleServiceImpl.findAppidByRoleId(appId, roleId);
			    if(app==null){
			    	result.put("resultCode", "401");
					result.put("resultMsg", "应用ID错误");
				}else if(rolecount == 0){
					result.put("resultCode", "401");
					result.put("resultMsg", "角色ID错误");
				}else{
					List<TucStaffEntity> userlist =pubUserService.getAppRoleUserList(appId,roleId,companyId,deptId,orgId);
					result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
					result.put("resultMsg", "处理成功");
					result.put("result", userlist);
				}
			}
		} catch (Exception e) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "系统内部异常");
			e.printStackTrace();
		}
		return result;
	}
	//租户id:用户编码 -> List<角色redisKey（租户id:角色id）>
    @ApiOperation(value = "加载租户id:角色id对应List<租户id:菜单类型type:菜单id>的redis数据")
    @GetMapping("/initRoleId")
    public R initRoleId(){
		sysRedisService.initRole();
        return R.ok();
    }

	// 6.0.0 多租户多岗位

	@ApiVersion(groups = Version.SIX)
	@ApiOperation(value = "根据应用ID、员工岗位id查询有权限访问的菜单列表资源", notes = "根据应用ID、员工岗位id查询有权限访问的菜单列表资源")
	@GetMapping("/auth/{postCode}/menuResource")
	public Map<String, Object> listMenuByUser(@PathVariable("postCode") String postCode,
											String menuType,String menuId) {
		Map<String, Object > result = new HashMap<>();
		String appId = UserUtils.getTenantId();
		if(StringUtils.isBlank(appId)||StringUtils.isBlank(postCode)){
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "输入参数异常");
		}else{
			Long userCount = pubUserService.selectUserCount(postCode);
			TPfApplication appEntity = appService.getById(appId);
			if(userCount<= 0){
				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{
				List<MenuEntity> menuEntryList = menuServiceImpl.getMenuByPostCode(appId, postCode, menuType,menuId);
				result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
				result.put("resultMsg", "处理成功");
				result.put("result", menuEntryList);
			}
		}
		return result;
	}

	@ApiVersion(groups = Version.SIX)
	@ApiOperation("根据菜单ID、员工ID查询有权限访问的菜单列表资源")
	@GetMapping("/auth/{postCode}/menuResource/{menuCode}")
	public Map<String, Object> listMenuByCode(@PathVariable("menuCode") String menuCode,
											@PathVariable("postCode") String postCode,String menuType){
		String appId = UserUtils.getTenantId();
		Map<String, Object > result = new HashMap<>();
		if(menuType==null) {
			menuType = "button";
		}else if("all".equals(menuType)) {
			menuType = "";
		}
		Long userCount = pubUserService.selectUserCount(postCode);
		if(userCount <= 0){
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "用户ID错误");
		}else{
			List<MenuEntity> menuEntryList = menuServiceImpl.getMenuBuCode(menuCode, postCode,appId,menuType);
			result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
			result.put("resultMsg", "处理成功");
			result.put("result", menuEntryList);
		}
		return result;
	}

	@ApiVersion(groups = Version.SIX)
	@ApiOperation("获取用户租户下面所有角色（区分租户）")
	@GetMapping("/user/{postCode}/rolesByCode")
	@CrossOrigin
	public Map<String, Object> listUserRoleByCode(@PathVariable("postCode")String postCode)  {
		String appId = UserUtils.getTenantId();
		Map<String, Object> result = new HashMap<>();
		if(StringUtils.isBlank(appId) || StringUtils.isBlank(postCode)){
			result.put("resultCode", "401");
			result.put("resultMsg", "输入参数异常");
		}else{
			TPfApplication app = appService.getById(appId);
			Long userCount = pubUserService.selectUserCount(postCode);
			if(app==null){
				result.put("resultCode", "401");
				result.put("resultMsg", "应用ID错误");
			}else if(userCount <= 0){
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "用户ID错误");
			}else{
				List<RoleEntity> roleEntryList = roleServiceImpl.findRolesByPostCode(appId, postCode);
				result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
				result.put("resultMsg", "处理成功");
				result.put("result", roleEntryList);
			}
		}
		return result;
	}

	@ApiVersion(groups = Version.SIX)
	@ApiOperation("根据角色ID、用户岗位ID判断用户是否属于该角色")
	@GetMapping("/usersByCode/{roleId}/{postCode}")
	@CrossOrigin
	public  Map<String, Object> findRoleUserByCode(@PathVariable("roleId") String roleId,
											   @PathVariable("postCode") String postCode)  {
		String appId = UserUtils.getTenantId();
		Map<String, Object> result = new HashMap<>();
		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(postCode)) {
			result.put("resultCode", RESULT_CODE_ERROR_CODE);
			result.put("resultMsg", "postCode不能为空");
		}else{
			TPfApplication app = appService.getById(appId);
			int role = roleServiceImpl.findAppidByRoleId(appId,roleId);
			Long user = pubUserService.selectUserCount(postCode);
			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 <= 0) {
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "用户ID错误");
			}else{
				boolean isRole=false;
				Long count = iRole2userService.selectRoleUserByCode(appId, roleId, postCode);
				if(count > 0) {
					isRole=true;
				}
				result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
				result.put("resultMsg", "处理成功");
				result.put("result", isRole);
			}
		}
		return result;
	}

	@ApiVersion(groups = Version.SIX)
	@Log(busiType = "角色新增用户", opType = SAVE, type = "render")
	@ApiOperation("角色新增用户")
	@PostMapping("/user/new")
	@CrossOrigin
	public Map<String, Object> saveUserNew(@RequestBody RoleEntity model)  {
		Map<String, Object> result = new HashMap<>();
		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 = roleServiceImpl.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 {
				String[] postCodes = model.getPostCodes();
				if (postCodes.length > 0) {
					for (String postCode : postCodes) {
						TucStaffEntity pubUser = pubUserService.getStaffByPostCode(postCode);
						Long count = iRole2userService.selectRoleUserByCode(model.getAppId(), model.getRoleId(), postCode);
						if (pubUser != null && count <= 0) {
							Role2userEntity role2user = new Role2userEntity();
							role2user.setRoleId(model.getRoleId());
							role2user.setUserId(pubUser.getStaffCode());
							role2user.setStatus("Y");
							role2user.setCreatorId("czadmin");
							role2user.setUpdatorId("czadmin");
							role2user.setOrgId(pubUser.getOrgId());
							role2user.setOrgName(pubUser.getOrgName());
							role2user.setTitleId(null);
							role2user.setCreateDate(new Date());
							role2user.setUpdateDate(new Date());
							role2user.setAppId(model.getAppId());
							role2user.setStaffPostCode(postCode);
							roleServiceImpl.saveUser(role2user);
						}
						result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
						result.put("resultMsg", "处理成功");
						result.put("result", "true");
					}
				}
			}
		}
		return result;
	}

	@ApiVersion(groups = Version.SIX)
	@ApiOperation("获取用户下面所有角色(不区分租户)")
	@GetMapping("/user/{postCode}/rolesByCodeNoAppId")
	@CrossOrigin
	public Map<String, Object> listUserRole(@PathVariable("postCode")String postCode)
	{
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isBlank(postCode)) {
			result.put("resultCode", "401");
			result.put("resultMsg", "输入参数异常");
		} else {
			Long user = pubUserService.selectUserCount(postCode);
			if (user <= 0) {
				result.put("resultCode", RESULT_CODE_ERROR_CODE);
				result.put("resultMsg", "用户ID错误");
			} else {
				List<RoleEntity> roleEntryList = roleServiceImpl.findRoleAllByPostCode(postCode);
				result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
				result.put("resultMsg", "处理成功");
				result.put("result", roleEntryList);
			}
		}
		return result;
	}


	@Log(busiType = "角色删除用户", opType = DELETE, type = "render")
	@ApiVersion(groups = Version.SIX)
	@DeleteMapping("/user/new")
	@CrossOrigin
	public Map<String, Object> deleteUserByCode(@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 {
			int role = roleServiceImpl.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 {
				String[] postCodes = model.getPostCodes();
				if (ObjectUtil.isNotEmpty(postCodes)) {
					for (String code : postCodes) {
						TucStaffEntity pubUser =  pubUserService.getStaffByPostCode(code);
						if(pubUser!=null) {
							roleServiceImpl.deleteByPostCode(model.getAppId(),model.getRoleId(),code);
						}
						result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
						result.put("resultMsg", "处理成功");
						result.put("result", "true");
					}
				}
			}
		}
		return result;
	}

	@ApiVersion(groups = Version.SIX)
	@ApiOperation("获取按钮资源")
	@GetMapping("/operation/buttonByCode/{postCode}/{menuCode}")
	@CrossOrigin
	public R<Map<String,Object>> getOperationButtonByCode (@PathVariable String postCode,
														   @PathVariable String menuCode){
		String appId = UserUtils.getTenantId();
		Map<String, Object> rs = menuServiceImpl.getButtonByCode(appId, postCode, menuCode);
		return R.ok(rs);
	}

}



