package com.wzj.soopin.transaction.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.wzj.soopin.transaction.domain.entity.WxAuthResponse;
import com.wzj.soopin.transaction.config.WechatMiniProgramConfig;
import com.wzj.soopin.transaction.wechat.WechatPayConfig;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class WxAuthService {

    @Autowired
    private WechatPayConfig wechatPayConfig;

    @Autowired
    private WechatMiniProgramConfig wechatMiniProgramConfig;

    private RestTemplate restTemplate = new RestTemplate();

    /**
     * 网页-通过code获取openid
     *
     * @param code 授权码
     * @return 包含openid的响应对象
     */
    public WxAuthResponse getOpenIdByCode(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        url = String.format(url, wechatPayConfig.getAppId(), wechatPayConfig.getSecret(), code);
        WxAuthResponse response = restTemplate.getForObject(url, WxAuthResponse.class);
        log.info("获取openid结果: {}", response);
        log.info("AppId为: {}", wechatPayConfig.getAppId());
        log.info("Secret为: {}", wechatPayConfig.getSecret());
        if (response == null || response.getOpenid() == null) {
            throw new RuntimeException("Failed to get openid from WeChat");
        }
        return response;
    }

    /**
     * 小程序登录-通过code获取openid
     *
     * @param code 授权码
     * @return 包含openid的响应对象
     */
    public WxAuthResponse getOpenIdByMiniProgramCode(String code) {
        String url = StrBuilder.create("https://api.weixin.qq.com/sns/jscode2session?appid=")
            .append(wechatMiniProgramConfig.getAppId())
            .append("&secret=")
            .append(wechatMiniProgramConfig.getSecret())
            .append("&js_code=")
            .append(code)
            .append("&grant_type=authorization_code")
            .toString();
        String body = HttpRequest.get(url).timeout(3000).execute().body();
        Assert.notBlank(body, () -> new ServiceException("微信小程序登录异常"));
        WxAuthResponse response = JSONObject.parseObject(body, WxAuthResponse.class);
        Assert.notBlank(response.getOpenid(), () -> new ServiceException("微信小程序登录异常:" + response.getErrmsg()));
        return response;
    }


}
