package com.platform.modules.sys.controller;

//import com.platform.modules.process.utils.AESUtils;

import com.platform.common.annotation.SysLog;
import com.platform.common.utils.HttpContextUtils;
import com.platform.common.utils.IPUtils;
import com.platform.common.utils.R;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.form.SysLoginForm;
import com.platform.modules.sys.service.SysCaptchaService;
import com.platform.modules.sys.service.SysUserService;
import com.platform.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 登录相关

 *
 *
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
	    response.setHeader("Cache-Control", "no-store, no-cache");
	    response.setContentType("image/jpeg");

	    //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@SysLog("用户登录")
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() <= 0){
			return R.error("账号已被锁定,请联系管理员");
		}
		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		user.setLastLoginIp(IPUtils.getIpAddr(request));
		user.setLastLoginTime(new Date());
		user.setPassword(null);
		sysUserService.updateLastLogin(user);
		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout() {
		sysUserTokenService.logout(getUserId());
		SecurityUtils.getSubject().logout();
		return R.ok();
	}

/*	@RequestMapping("/process/token")
	public R token(String sign, Long t) {
		if(StringUtils.isBlank(sign)||null==t) {
			return R.error("信息缺失");
		}
		String decryptSign = null;
		try {
			decryptSign = AESUtils.decrypt(sign);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("签名信息有误");
		}
		String[] dsArr = decryptSign.split("\\$\\$");
		if(dsArr.length!=3) {
			return R.error("签名信息有误");
		}
		String key = dsArr[0];
		String time = dsArr[1];
		String sercret = dsArr[2];
		if(StringUtils.isBlank(key) || StringUtils.isBlank(time) || StringUtils.isBlank(sercret) ||
				!t.equals(Long.valueOf(time))) {
			return R.error("签名信息有误");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(key);

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(sercret, user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}*/

}
