package com.crunii.micro.service.sysmgr.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.crunii.micro.service.sysmgr.config.WechatProperties;
import com.crunii.micro.service.sysmgr.constants.SysmgrConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

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


/**
 * @author 15294
 */
@Slf4j
@Component
public class WeChatUtil {

    @Resource
    private WechatProperties wechatProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取服务端access_token
     */
    public void refreshToken() {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(SysmgrConstants.WX_ACCESS_TOKEN_LOCK, 1, 3, TimeUnit.SECONDS);
        if (null != flag && flag){
            String url = wechatProperties.getHost() + "/cgi-bin/stable_token";
            HashMap<String, Object> map = new HashMap<>(8);
            map.put("grant_type", "client_credential");
            map.put("appid", wechatProperties.getAppId());
            map.put("secret", wechatProperties.getSecret());
            //发送请求 响应微信返回的参数
            log.info("request wechat token url:{}, body:{}", url, JSONObject.toJSONString(map));
            String res = HttpUtil.post(url, JSONObject.toJSONString(map));
            log.info("request wechat token result:{}", res);
            JSONObject jsonObject = JSONObject.parseObject(res);
            String accessToken = jsonObject.getString("access_token");
            if (StringUtils.isBlank(accessToken)){
                log.error("get access token fail, msg:{}", jsonObject);
                throw new RuntimeException("get wx token fail");
            }else {
                redisTemplate.opsForValue().set(SysmgrConstants.WX_ACCESS_TOKEN, accessToken, 2, TimeUnit.HOURS);
            }
            return;
        }
        log.error("get distribution lock fail, lock result:{}", flag);
    }

    public String getTicket(){
        String token = (String)redisTemplate.opsForValue().get(SysmgrConstants.WX_ACCESS_TOKEN);
        if (StringUtils.isBlank(token)){
            log.error("empty system token");
            refreshToken();
            throw new RuntimeException("服务器繁忙，请稍后重试");
        }
        StringBuilder path1 = new StringBuilder(wechatProperties.getHost());
        path1.append("/cgi-bin/ticket/getticket?access_token=").append(token).append("&type=jsapi");
        JSONObject ticketJson = JSONObject.parseObject(HttpUtil.get(path1.toString()));
        String ticket = ticketJson.getString("ticket");
        if (StringUtils.isBlank(ticket)){
            log.error("wechat get ticket fail,msg:{}", ticketJson);
            if (Objects.equals(ticketJson.get("errcode"), 40001)){
                refreshToken();
            }
            throw new RuntimeException();
        }
        return ticket;
    }

    public String getUserInfo(String code){
        StringBuilder path = new StringBuilder();
        path.append(wechatProperties.getHost());
        path.append("/sns/oauth2/access_token?");
        path.append("&appid=").append(wechatProperties.getAppId());
        path.append("&secret=").append(wechatProperties.getSecret());
        path.append("&code=").append(code);
        path.append("&grant_type=authorization_code");
        String res = HttpUtil.get(path.toString());
        JSONObject jsonObject = JSONObject.parseObject(res);
        String openid = jsonObject.getString("openid");
        if (StringUtils.isBlank(openid)){
            log.error("wechat get user openid fail,msg:{}", jsonObject);
            throw new RuntimeException("系统错误，请稍后重试");
        }
        log.error("wechat get user openid success,msg:{}", jsonObject);
//        StringBuilder path2 = new StringBuilder();
//        path2.append(wechatProperties.getHost())
//            .append("/sns/userinfo?access_token=")
//            .append(accessToken)
//            .append("&openid=")
//            .append(openid)
//            .append("&lang=zh_CN");
//        String userInfo = HttpUtil.get(path2.toString());
//        JSONObject userJson = JSONObject.parseObject(userInfo);
        return openid;
    }


}
