package com.hotent.uc.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.annotation.DataPermission;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.controller.BaseController2;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.*;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.CommonResultUtil;
import com.hotent.base.util.JsonUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.uc.manager.RoleManager;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.manager.UserRoleManager;
import com.hotent.uc.model.Role;
import com.hotent.uc.model.User;
import com.hotent.uc.params.role.RoleVo;
import com.hotent.uc.params.user.UserVo;
import com.hotent.uc.util.OrgUtil;
import com.hotent.uc.util.UpdateMethod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import poi.util.ExcelUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色组织模块接口
 * @author zhangxw
 *
 */
@RestController
@RequestMapping("/api/role/v2/")
@Api(tags="角色管理2")
@ApiGroup(group= {ApiGroupConsts.GROUP_UC})
public class RoleController2 extends BaseController2<RoleManager, Role> {
	
	@Resource
	RoleManager roleService;
	@Autowired
	UserManager userService;
	@Autowired
	UserRoleManager userRoleService;
	
	/**
	 * 获取所有角色
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="roles/getAll",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "获取所有角色", httpMethod = "POST", notes = "获取所有角色")
	public List<Role> getAll() throws Exception{
		return roleService.getAll();
	}
	
	/**
	 * 添加角色
	 * @param Role
	 * @return
	 * @throws Exception
	 * 
	 */
	@RequestMapping(value="role/addRole",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "添加角色", httpMethod = "POST", notes = "添加角色")
	public CommonResult<String> addRole(@ApiParam(name="role",value="角色参数对象", required = true) @RequestBody RoleVo role) throws Exception{
		CommonResult<String> commonResult = roleService.addRole(role);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	/**
	 * 根据角色帐号删除角色
	 * @param json
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/deleteRole",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "根据角色编码删除角色", httpMethod = "POST", notes = "根据角编码识删除角色")
	@DataPermission
	public CommonResult<String> deleteRole(@ApiParam(name="codes",value="角色编码（多个用,号隔开）", required = true) @RequestBody String codes) throws Exception{
		CommonResult<String> commonResult = roleService.deleteRole(codes);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	/**
	 * 根据角色id删除角色
	 * @param json
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/deleteRoleByIds",method=RequestMethod.DELETE, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "根据角色id删除角色", httpMethod = "DELETE", notes = "根据角色id删除角色")
    @DataPermission
	public CommonResult<String> deleteRoleByIds(@ApiParam(name="ids",value="角色id（多个用,号隔开）", required = true) @RequestParam String ids) throws Exception{
		CommonResult<String> commonResult = roleService.deleteRoleByIds(ids);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	
	/**
	 * 更新角色
	 * @param Role
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/updateRole",method=RequestMethod.PUT, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "更新角色", httpMethod = "PUT", notes = "更新角色")
	@UpdateMethod(type=RoleVo.class)
	@DataPermission
	public CommonResult<String> updateRole(@ApiParam(name="role",value="角色参数对象", required = true) @RequestBody  RoleVo role) throws Exception{
		CommonResult<String> commonResult = roleService.updateRole(role);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	
	/**
	 * 获取角色信息
	 * @param json
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/getRole",method=RequestMethod.GET, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "根据角色编码获取角色信息", httpMethod = "GET", notes = "获取角色信息")
	public CommonResult<Role> getRole(@ApiParam(name="code",value="角色编码", required = true) @RequestParam String code) throws Exception{
		CommonResult<Role> commonResult = roleService.getRoleByCode(code);
		return CommonResultUtil.<Role>getResult(commonResult);
	}
	
	/**
	 * 分配用户（按用户）
	 * @param Role
	 * @return
	 * @throws Exception
	 * 
	 */
	@RequestMapping(value="roleUser/saveUserRole",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "分配用户（按用户）", httpMethod = "POST", notes = "分配用户（按用户）")
	public CommonResult<String> saveUserRole(@ApiParam(name="code",value="角色编码", required = true) @RequestParam String code,
			@ApiParam(name="accounts",value="用户帐号，多个用“,”号隔开", required = true) @RequestParam String accounts) throws Exception{
		CommonResult<String> commonResult = roleService.saveUserRole(code, accounts);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	/**
	 * 分配用户（按用户）
	 * @param Role
	 * @return
	 * @throws Exception
	 * 
	 */
	@RequestMapping(value="roleUser/saveUserRoles",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "分配用户（按角色编码）", httpMethod = "POST", notes = "分配用户（按用户）")
	public CommonResult<String> saveUserRoles(@ApiParam(name="codes",value="角色编码，多个用“,”号隔开", required = true) @RequestParam String codes,
			@ApiParam(name="account",value="用户帐号", required = true) @RequestParam String account) throws Exception{
		CommonResult<String> commonResult = roleService.saveUserRoles(codes, account);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	/**
	 * 分配用户（按组织）
	 * @param Role
	 * @return
	 * @throws Exception
	 * 
	 */
	@RequestMapping(value="roleUser/addUserRoleByOrg",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "分配用户（按组织）", httpMethod = "POST", notes = "分配用户（按组织）")
	public CommonResult<String> addUserRoleByOrg(@ApiParam(name="code",value="角色编码", required = true) @RequestParam String code,
			@ApiParam(name="orgCodes",value="组织编码，多个用“,”号隔开", required = true) @RequestParam String orgCodes) throws Exception{
		CommonResult<String> commonResult = roleService.addUserRoleByOrg(code, orgCodes);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	/**
	 * 角色移除用户
	 * @param Role
	 * @return
	 * @throws Exception
	 * 
	 */
	@RequestMapping(value="roleUser/deleteUserRole",method=RequestMethod.DELETE, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "角色移除用户", httpMethod = "DELETE", notes = "角色移除用户")
	public CommonResult<String> deleteUserRole(@ApiParam(name="code",value="角色编码", required = true) @RequestParam String code,
			@ApiParam(name="accounts",value="用户帐号，多个用“,”号隔开", required = true) @RequestParam String accounts) throws Exception{
		CommonResult<String> commonResult = roleService.removeUserRole(code, accounts);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	/**
	 * 获取用户所属角色列表
	 * @param json
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/getRolesByUser",method=RequestMethod.GET, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "获取用户所属角色列表", httpMethod = "GET", notes = "获取用户所属角色列表")
	public CommonResult<List<Role>> getRolesByUser(@ApiParam(name="account",value="用户帐号", required = true) @RequestParam String account) throws Exception{
		List<Role> roleList = roleService.getListByAccount(account);
		return CommonResult.<List<Role>>ok().value(roleList);
	}
	
	/**
	 * 获取角色（多个）中的用户
	 * @param json
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/getUsersByRoleCode",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "获取角色（多个）中的用户", httpMethod = "POST", notes = "获取角色（多个）中的用户")
	public CommonResult<List<UserVo>> getUsersByRoleCode(@ApiParam(name="codes",value="角色编码，多个用“,”号隔开", required = true) @RequestBody String codes) throws Exception{
		List<UserVo> userVoList = roleService.getUsersByRoleCode(codes);
		return CommonResult.<List<UserVo>>ok().value(userVoList);

	}
	
	/**
	 * 物理删除所有逻辑删除了的角色数据
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/deleteRolePhysical",method=RequestMethod.DELETE, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "物理删除所有逻辑删除了的角色数据", httpMethod = "DELETE", notes = "物理删除所有逻辑删除了的角色数据")
	public CommonResult<Integer> deleteRolePhysical() throws Exception{
		Integer num = roleService.removePhysical();
		CommonResult<Integer> commonResult = OrgUtil.getRemovePhysiMsg(num);
		return CommonResultUtil.<Integer>getResult(commonResult);
	}
	
	/**
	 * 物理删除所有逻辑删除了的用户角色关系数据
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/deleteUserRolePhysical",method=RequestMethod.DELETE, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "物理删除所有逻辑删除了的用户角色关系数据", httpMethod = "DELETE", notes = "物理删除所有逻辑删除了的用户角色关系数据")
	public CommonResult<Integer> deleteUserRolePhysical() throws Exception{
		Integer num = userRoleService.removePhysical();
		CommonResult<Integer> commonResult = OrgUtil.getRemovePhysiMsg(num);
		return CommonResultUtil.<Integer>getResult(commonResult);
	}
	
	/**
	 * 禁用角色（多个用,号隔开）
	 * @param json
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/forbiddenRoles",method=RequestMethod.PUT, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "禁用角色（多个用,号隔开）", httpMethod = "PUT", notes = "禁用角色（多个用,号隔开）")
	public CommonResult<String> forbiddenRoles(@ApiParam(name="codes",value="角色编码，多个用“,”号隔开", required = true) @RequestBody String codes) throws Exception{
		CommonResult<String> commonResult = roleService.forbiddenRoles(codes);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	/**
	 * 激活角色（多个用,号隔开）
	 * @param json
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/activateRoles",method=RequestMethod.PUT, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "激活角色（多个用,号隔开）", httpMethod = "PUT", notes = "激活角色（多个用,号隔开）")
	public CommonResult<String> activateRoles(@ApiParam(name="codes",value="角色编码，多个用“,”号隔开", required = true) @RequestBody String codes) throws Exception{
		CommonResult<String> commonResult = roleService.activateRoles(codes);
		return CommonResultUtil.<String>getResult(commonResult);
	}
	
	/**
	 * 根据时间获取角色数据（数据同步）
	 * @param btime
	 * @param etime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="roles/getRoleByTime",method=RequestMethod.GET, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "根据时间获取角色数据（数据同步）", httpMethod = "GET", notes = "根据时间获取角色数据（数据同步）")
	public CommonResult<List<Role>> getRoleByTime(@ApiParam(name="btime",value="开始时间（格式：2018-01-01 12:00:00或2018-01-01）") @RequestParam(required=false) String btime,@ApiParam(name="etime",value="结束时间（格式：2018-02-01 12:00:00或2018-02-01）") @RequestParam(required=false) String etime) throws Exception{
		List<Role> roleList = roleService.getRoleByTime(btime, etime);
		return CommonResult.<List<Role>>ok().value(roleList);
	}
	
	/**
	 * 获取角色用户（分页）
	 * @param filter
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="role/getRoleUsers",method=RequestMethod.POST, produces = {
	"application/json; charset=utf-8" })
	@ApiOperation(value = "获取角色用户（分页）", httpMethod = "POST", notes = "获取角色用户（分页）",hidden=false)
	public CommonResult<PageList<User>> getRoleUsers(@ApiParam(name="filter",value="查询参数", required = true) @RequestBody QueryFilter filter,@ApiParam(name="code",value="角色编码", required = true) @RequestParam String code) throws Exception{
		filter.addFilter("r.CODE_",code, QueryOP.EQUAL, FieldRelation.AND, "group_code");
		Page<User> list = (Page<User>)userService.getRoleUserQuery(filter);
		PageList<User> userPageList = new PageList<>(list);
		return CommonResult.<PageList<User>>ok().value(userPageList);
	}


	@RequestMapping(value="role/isCodeExist",method=RequestMethod.GET, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "查询角色编码是否已存在", httpMethod = "GET", notes = "查询角色编码是否已存在")
	public CommonResult<Boolean> isCodeExist(@ApiParam(name="code",value="角色编码")
												@RequestParam(required=true) String code) throws Exception{
		CommonResult<Boolean> commonResult = roleService.isCodeExist(code);
		return CommonResultUtil.<Boolean>getResult(commonResult);
	}

	/**
	 *  根据角色别名获取除这个角色之外的所有角色
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="roles/getNotCodeAll",method=RequestMethod.GET, produces = {
			"application/json; charset=utf-8" })
	@ApiOperation(value = "根据角色别名获取除这个角色之外的所有角色", httpMethod = "GET", notes = "获取所有角色")
	public CommonResult<List<Role>> getNotCodeAll(@ApiParam(name="code",value="角色编码") @RequestParam(required=true) String code) throws Exception{
		List<Role> roleList = roleService.getOrgRoleListNotCode(code);
		return CommonResult.<List<Role>>ok().value(roleList);
	}

	@RequestMapping(value="roles/export" ,method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
	@ApiOperation(value = "角色导出", httpMethod = "GET", notes = "角色导出")
	public void export(HttpServletResponse response,@ApiParam(name="ids",value="ids", required = true)@RequestParam String ids) throws 	Exception{
		QueryFilter filter = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
		filter.addFilter("id", ids.split(","), QueryOP.IN);
		PageList<Role> roles = roleService.query(filter);
		List<Map<String,Object>> list = new ArrayList<>();
		if(BeanUtils.isNotEmpty(roles.getRows())){
			for (Role role : roles.getRows()) {
				list.add(JsonUtil.toMap(JsonUtil.toJson(role)));
			}
		}
		Map<String,String> exportMap = new LinkedHashMap<>();
		exportMap.put("name","角色名称");
		exportMap.put("code","角色编码");
		exportMap.put("enabled","状态");
		exportMap.put("description","描述");
		HSSFWorkbook exportFile = ExcelUtil.exportExcel("角色列表", 22, exportMap, list);
		ExcelUtil.downloadExcel(exportFile,"角色导出",response);
	}
}
