package com.huimv.apiservice.controller;

import cn.hutool.json.JSONObject;
import com.huimv.common.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.apiservice.controller
 * @Description : TODO
 * @Author : yuxuexuan
 * @Create : 2021/4/28 0028 17:24
 **/
@RestController
public class TokenController {

    @Value("${renyang.client}")
    private String clientId;

    @GetMapping("/getToken")
    public JSONObject getToken(@RequestParam("userId") String userId,
                               @RequestParam("random") String random,
                               @RequestParam("timestamp") String timestamp,
                               @RequestParam("sign") String sign) throws NoSuchAlgorithmException {

        JSONObject result = new JSONObject();

        if (!clientId.equals(userId)) {
            result.put("code", 201);
            result.put("msg", "用户信息错误");
            return result;
        }


        MessageDigest md = MessageDigest.getInstance("MD5");
        String data = random + ";" + timestamp;
        String oneSign = Hex.encodeHexString(md.digest(data.getBytes(StandardCharsets.UTF_8)));
        oneSign = oneSign + "HuiMv";
        String twoSign = Hex.encodeHexString(md.digest(oneSign.getBytes(StandardCharsets.UTF_8)));
        System.out.println(twoSign);


        if (!sign.equals(twoSign)) {
            result.put("code", 201);
            result.put("msg", "加密方式错误");
            return result;
        }

        String token = TokenUtil.sign(userId);
        System.out.println(token);
        result.put("code", 200);
        result.put("accessToken", token);

        return result;
    }

    @RequestMapping("/verify")
    public boolean getToken(String verify) {
        return TokenUtil.verify(verify);
    }
}
