package com.willalp.wx.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.willalp.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class WxUtils {

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.appSecret}")
    private String appSecret;
    /**微信官方换取openid的固定接口*/
    final String CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";

    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisCache redisUtils;


    public HashMap<String, String> getFormat(String str) {
        return new HashMap<String, String>() {{
            put("value", str);
        }};
    }

    /**
     * 获取openid和session_key，参数code是小程序端传过来的
     */
    public Map code2Session(String code) throws JsonMappingException, JsonProcessingException {
        Map<String, Object> params = new HashMap<>();
        params.put("appId", appId);
        params.put("appSecret", appSecret);
        params.put("code", code);
        ResponseEntity<String> response = restTemplate.exchange(CODE2SESSION_URL, HttpMethod.GET, RequestEntity.EMPTY, String.class, params);
        JsonNode json = objectMapper.readTree(response.getBody());
        Map returnMap = new HashMap();
        returnMap.put("session_key", json.get("session_key").asText());
        /*获取到openid*/
        returnMap.put("openid", json.get("openid").asText());
        return returnMap;
    }

    public String getAccessToken() {
        /*先从缓存中取openid，缓存中取不到 说明已经过期，则重新申请*/
        String expires = redisUtils.getCacheObject("access_token");
        if (expires != null) {
            return expires;
        }
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appId);
        params.put("APPSECRET", appSecret);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        /*access_token有效时长*/
        int expires_in = object.getInteger("expires_in");
        /*过期时间减去10毫秒：10毫秒是网络连接的程序运行所占用的时间*/
        redisUtils.setCacheObject("access_token", Access_Token, expires_in - 10, TimeUnit.MILLISECONDS);
        return Access_Token;
    }

//    public JsonNode decryptData(String encryptedData, String session_key, String iv) throws IOException {
//        AES aes = new AES();
//        byte[] data = aes.decrypt(Base64.getDecoder().decode(encryptedData), Base64.getDecoder().decode(session_key), Base64.getDecoder().decode(iv));
//        return objectMapper.readTree(data);
//    }
}