package com.jeequan.jeepay.thirdparty.oauth2;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icbc.api.internal.apache.http.impl.cookie.S;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * TODO
 * 微信托管业务处理
 * @author crystal
 * @date 2023/11/13 15:47
 */
@Service
public class WxDepositService {

    public final static String DOMAIN = "https://xcx.shouyinbei.cn";

    public final static String API_PREFIX = "/prod-mini-api";

    public final static String THIRD_ACCESS_TOEN = "authAccessToken";

    public final static String THIRD_COMPONENT_TOKEN = "componentToken";

    /**
     * 微信第三方渠道号appid
     */
    public static final String THIRD_WX_APPID = "wx2aac7e9da59d74b0";

    public static final String THIRD_USER_OPENID = "https://api.weixin.qq.com/sns/component/jscode2session?appid=APPID&js_code=CODE&grant_type=authorization_code&component_appid=COMPONENT_APPID&component_access_token=COMPONENT_ACCESS_TOKEN";
    /**
     * 渠道授权获取openid地址
     */
    public static final String THIRD_OAUTH2_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=APPID&code=CODE&grant_type=authorization_code&component_appid=COMPONENT_APPID&component_access_token=COMPONENT_ACCESS_TOKEN";


    public String getWxAccessToken(String appid,String tokenName) {
        String url = DOMAIN + API_PREFIX + "/api/open/cache/get?appid="+appid;
        String response = HttpUtil.get(url);
        JSONObject result = JSON.parseObject(response);
        JSONObject data = result.getJSONObject("data");
        return data.getString(tokenName);
    }

    /**
     * 获取第三方代开小程序 ACCESS_TOKEN
     * @param appid
     * @return
     */
    public String getThirdAccessToken(String appid) {
        return getWxAccessToken(appid,THIRD_ACCESS_TOEN);
    }

    public String getComponentToken(String appid) {
        return getWxAccessToken(appid,THIRD_COMPONENT_TOKEN);
    }

    public String getThidOpenUserId(String appid,String code) {
        String componentToken = getComponentToken(appid);
        String url = THIRD_USER_OPENID.replace("COMPONENT_APPID",THIRD_WX_APPID).replace("CODE",code).replace("APPID",appid).replace("COMPONENT_ACCESS_TOKEN",componentToken);
        String response = HttpUtil.get(url);
        JSONObject result = JSON.parseObject(response);
        return result.getString("openid");
    }
}
