package com.wx.application.adapter.controller;

import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
//import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
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.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kaptcha.Kaptcha;
import com.google.common.collect.ImmutableMap;
import com.wx.application.adapter.dto.qo.RiskUserQ;
import com.wx.application.base.BaseController;
import com.wx.application.base.ErrorCodeEnum;
import com.wx.application.base.ResponseData;
import com.wx.application.constant.CONSTANT;
import com.wx.application.core.entity.RiskUser;
import com.wx.application.core.service.RiskUserService;
import com.wx.application.util.JwtUtils;
import com.wx.application.util.MD5Util;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequestMapping("/login")
@RestController("loginController")
public class LoginController extends BaseController {

	@Autowired
	RiskUserService riskUserService;
	
    /*@Autowired
    RedissonClient redissonClient;*/

    @Autowired
    private Kaptcha kaptcha;

    /**
     * @api {post} /login/captcha 获取验证码
     * @apiName 获取验证码
     * @apiGroup Login
     * @apiParam {String} name 角色名称
     * @apiParam {String} description 角色描述
     * @apiParam {Boolean} isAssistant 是否为医生助理
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     * }
     * @apiDescription 向后端申请一个验证码
     * 返回验证码的图片流,并且存入对应cookie_id
     * 登录时传入对应cookie_id,用来验证对应错误码
     * ---------------------------------
     * @author : zj
     * @since : Create in 2021-05-08
     */
    @RequestMapping("captcha")
    public void captcha() {
        kaptcha.render();
    }

	
	/**
	 * 登录
	 */
	@PostMapping(value = "/user")
    public ResponseData login(@RequestBody RiskUserQ loginQo) throws Exception {
		
//		if(StringUtils.isBlank(loginQo.getCode())) {
//			Map<String,String> data = new HashMap<>();
//			data.put("msg", "验证码不能为空");
//			return error(ErrorCodeEnum.USER_NOT_EXIST,data);
//		}
//
//		try {
//			kaptcha.validate(loginQo.getCode());
//		} catch (Exception e) {
//			Map<String,String> data = new HashMap<>();
//			data.put("msg", "验证码错误");
//			return error(ErrorCodeEnum.USER_NOT_EXIST,data);
//		}

		/*if(StringUtils.isBlank(loginQo.getCode())) {
			Map<String,String> data = new HashMap<>();
			data.put("msg", "验证码不能为空");
			return error(ErrorCodeEnum.USER_NOT_EXIST,data);
		}
		
		try {
			kaptcha.validate(loginQo.getCode());
		} catch (Exception e) {
			Map<String,String> data = new HashMap<>();
			data.put("msg", "验证码错误");
			return error(ErrorCodeEnum.USER_NOT_EXIST,data);
		}*/
		
		/**
		 * 将密码改成md5加密查询
		 */
		Map<String,Object> mQ = new HashMap<>();
		mQ.put("EQS_username", loginQo.getUsername());
		mQ.put("EQS_password", MD5Util.MD5(loginQo.getPassword()));
		mQ.put("EQS_type", loginQo.getType());
		
		RiskUser riskUser = riskUserService.queryUnique(mQ);
		
		if(riskUser != null) {
			String token = JwtUtils.generateJwtToken(riskUser.getId(), CONSTANT.LOGIN_TYPE_ADMIN, riskUser);
			
			RiskUser _riskUser = new RiskUser();
			_riskUser.setRealname(riskUser.getRealname());
			_riskUser.setUsername(riskUser.getUsername());
			
			return success(ImmutableMap.<String, Object>builder()
	                .put("Authorization",token)
	                .put("user", _riskUser)
	                .build());
		}
		Map<String,String> data = new HashMap<>();
		data.put("msg", "用户名密码错误");
		return error(ErrorCodeEnum.USER_NOT_EXIST,data);
    }
    
    /**
     * 解密用户敏感数据获取用户信息
     *
     * @param sessionKey    数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv            加密算法的初始向量
     * @return
     */
    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSON.parseObject(result);
            }
        } catch (Exception e) {

        }
        return null;
    }

}
