package com.huatek.frame.base.login.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.huatek.frame.base.dto.UserDTO;
import com.huatek.frame.base.service.LoginService;
import com.huatek.frame.base.util.KerMenuTool;
import com.huatek.frame.base.vo.UserVO;
import com.huatek.torch.frame.log.KerLog;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.util.jwt.TokenMgr;
import com.huatek.torch.util.tools.CodeUtil;
import com.huatek.torch.util.tools.UserUtil;
import com.huatek.torch.util.uuid.Uuid;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 登陆应用
 *
 * @author key_dong
 */
@Api(tags={"登陆应用接口"})
@RestController
@RequestMapping("/api/user")
public class LoginController {

	private static final String TAG = "TAG";

	private static final String CODE = "CODE";

	@Reference(check = false)
	private LoginService loginService;

	@SuppressWarnings("rawtypes")
	@Autowired
	private RedisTemplate redisTemplate;

	@Value("${torch.login.time}")
	private long time;

	@Value("${base.verify}")
	private boolean verify;

	@Value("${base.verifyType}")
	private int verifyType;

	/**
	 * 登陆
	 *
	 * @param user
	 * @param req
	 * @return
	 */
	@ApiOperation(value = "登陆",httpMethod="POST", notes= "登陆", produces = "application/json;charset=utf-8",response=Map.class)
	@KerLog(projectName = "PROJECTNAME", modelName = "USER.LOGINNAME", methodName = "USER.METHODNAME.LOGIN")
	@PostMapping(value = "/login", produces = { "application/json;charset=utf-8" })
	public  Map<String, Object> userLogin(@RequestBody UserDTO user) throws Exception{
		return loginService.login(user, time,"", user.getCode(), verify);
	}

	/**
	 * 获取用户许可资源
	 *
	 * @param user
	 * @return
	 */
	@ApiOperation(value = "获取用户许可资源",httpMethod="POST", notes= "获取用户许可资源", produces = "application/json;charset=utf-8",response=String.class)
	@SuppressWarnings("rawtypes")
	@PostMapping(value = "/allMenus", produces = { "application/json;charset=utf-8" })
	public  Map<String, Object> allMenus(HttpServletRequest request) {
		ValueOperations operations = redisTemplate.opsForValue();
		String token = TokenMgr.getToken(request, ConstantUtil.TOKEN);
		String uid = UserUtil.getUid(token);
		String permissions = operations.get(ConstantUtil.PERMISSIONS  + uid.hashCode()).toString();
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", KerMenuTool.allMenus(permissions));
	}

	/**
	 * 获取用户许可资源2.0
	 *
	 * @param user
	 * @return
	 */
	@ApiOperation(value = "获取用户许可资源2.0",httpMethod="POST", notes= "获取用户许可资源2.0", produces = "application/json;charset=utf-8",response=JSONArray.class)
	@SuppressWarnings("rawtypes")
	@PostMapping(value = "/menus", produces = { "application/json;charset=utf-8" })
	public  Map<String, Object> menus(HttpServletRequest request) {
		ValueOperations operations = redisTemplate.opsForValue();
		String token = TokenMgr.getToken(request, ConstantUtil.TOKEN);
		String uid = UserUtil.getUid(token);
		String permissions = operations.get(ConstantUtil.PERMISSIONS + uid.hashCode()).toString();
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", KerMenuTool.menus(permissions));
	}

	/**
	 * 退出登录
	 *
	 * @return
	 */
	@ApiOperation(value = "退出登录",httpMethod="GET", notes= "退出登录", produces = "application/json;charset=utf-8",response=Map.class)
	@KerLog(projectName = "PROJECTNAME", modelName = "USER.LOGINNAME", methodName = "USER.METHODNAME.LOGINOUT")
	@GetMapping(value = "/logout", produces = { "application/json;charset=utf-8" })
	public  Map<String, Object> logout(HttpServletRequest request) {
		String token = TokenMgr.getToken(request, ConstantUtil.TOKEN);
		loginService.deleteRedis(token);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
	}

	/**
	 * 修改密码
	 *
	 * @return
	 */
	@ApiOperation(value = "修改密码",httpMethod="POST", notes= "修改密码", produces = "application/json;charset=utf-8",response=Map.class)
	@KerLog(projectName = "PROJECTNAME", modelName = "USER.LOGINNAME", methodName = "USER.METHODNAME.CHANGEPWD")
	@PostMapping(value = "/changePwd", produces = { "application/json;charset=utf-8" })
	public  Map<String, Object> changePwd(HttpServletRequest request, @RequestBody Map<String, String> map) {
		String token = TokenMgr.getToken(request, ConstantUtil.TOKEN);
		return loginService.changePwd(token,map);
	}

	/**
	 * 验证码
	 *
	 * @return
	 * @throws IOException
	 */
	@ApiOperation(value = "用户列表",httpMethod="POST", notes= "用户列表", produces = "application/json;charset=utf-8",response=UserVO.class)
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@PostMapping(value = "/code", produces = { "application/json;charset=utf-8" })
	public  Map<String, Object> code(HttpServletResponse response) throws IOException {
		String tag = Uuid.getUUID();
		// (字节流) 获得可以向客户端返回图片的输出流
		final OutputStream output = response.getOutputStream();
		// 创建验证码图片并返回图片上的字符串
		Map<String, String> map = CodeUtil.create(200, 80, "jpeg", output, verifyType);
		map.put(TAG, tag);
		ValueOperations operations = redisTemplate.opsForValue();
		operations.set(CODE + tag.hashCode(), map.get("code"), 60L, TimeUnit.SECONDS);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", map);
	}

}
