package com.yeejoin.amos.boot.module.tzs.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tzs.api.service.IWechatService;
import com.yeejoin.amos.boot.module.tzs.biz.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号服务实现类
 */
@Service
public class WechatServiceImpl implements IWechatService {

    @Autowired
    RedisUtils redisUtils;

    /**
     * token 过期时间，wechat 系统为7200 ，tzs 系统小于7200 防止获取到无效token
     */
    private long time = 6000l;

    @Value("${tzs.wechat.appid}")
    private String APP_ID;

    @Value("${tzs.wechat.secret}")
    private String SECRET_KEY;

    @Value("${tzs.wechat.url}")
    private String wechatUrl;

    @Override
    public String getAccessToken() {
        if(redisUtils.hasKey(RedisKey.WECHAT_TOKEN)){
            Object obj= redisUtils.get(RedisKey.WECHAT_TOKEN);
            return obj.toString();
        } else {
            String tokenAccessUrl = wechatUrl+ "/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + SECRET_KEY;
            String responseStr = HttpUtils.doGet(tokenAccessUrl);
            JSONObject response = null;
            try {
                response = JSONObject.parseObject(responseStr);
            } catch (Exception e) {
                throw  new BadRequest("获取token 出错：" + e.getMessage());
            }
            if(response.get("access_token") != null) { // 获取token 成功
                try {
                    String token = response.getString("access_token");
                    redisUtils.set(RedisKey.WECHAT_TOKEN, token,time);
                    return token;
                } catch (Exception e) {
                    throw  new BadRequest("获取token 出错：" + e.getMessage());
                }
            } else {
                throw  new BadRequest("获取token 出错：" + response);
            }
        }
    }

    @Override
    public String getOpenId(String code) {
        String openIdUrl = wechatUrl+ "/sns/oauth2/access_token?appid=" +APP_ID + "&secret=" + SECRET_KEY + "&code=" + code + "&grant_type=authorization_code";
        String responseStr = HttpUtils.doGet(openIdUrl);
        JSONObject response = null;
        try {
            response = JSONObject.parseObject(responseStr);
        } catch (Exception e) {
            throw  new BadRequest("获取openId 出错：" + e.getMessage());
        }
        if(response.get("openid") != null) { // 获取token 成功
            try {
                String openid = response.getString("openid");
                return openid;
            } catch (Exception e) {
                throw  new BadRequest("获取openId 出错：" + e.getMessage());
            }
        } else {
            throw  new BadRequest("获取openId 出错" + response);
        }
    }

}