package com.cyksj.service.wechat;


import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.IoKit;
import com.cyksj.common.util.J11HttpC;
import com.cyksj.common.util.Jsons;
import com.cyksj.model.dto.AccountJsTicket;
import com.cyksj.model.dto.WeChatAccessToken;
import org.springframework.stereotype.Service;

import java.net.http.HttpResponse;

/**
 * @author valor.
 * @date 2019/12/3 20:44
 */
@Service
public class AccountOperator implements AccountOps {

    @Override
    public WeChatAccessToken accessToken(String appid, String secret) throws Exception {
        // GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}
        String url = "https://api.weixin.qq.com/cgi-bin/token" +
                "?appid=" + appid +
                "&secret=" + secret +
                "&grant_type=client_credential";
        HttpResponse<byte[]> res =
                J11HttpC.custom()
                        .ofGet()
                        .url(url)
                        .send(HttpResponse.BodyHandlers.ofByteArray());

        if (200 != res.statusCode()) {
            throw BusinessRuntimeException.getInstance("获取access_token失败: " + IoKit.toString(res.body()));
        }

        WeChatAccessToken token = Jsons.parseObject(res.body(), WeChatAccessToken.class);
        if (null == token) {
            throw BusinessRuntimeException.getInstance("获取access_token失败: " + IoKit.toString(res.body()));
        }

        final Integer errcode = token.getErrcode();
        if (null != errcode && 0 != errcode) {
            throw BusinessRuntimeException.getInstance("获取access_token失败: " + token.getErrmsg() + "[" + errcode + "]");
        }
        return token;
    }

    @Override
    public AccountJsTicket jsTicket(String access_token) throws Exception {
        // GET https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={ACCESS_TOKEN}&type=jsapi
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket" +
                "?access_token=" + access_token +
                "&type=jsapi";
        HttpResponse<byte[]> res =
                J11HttpC.custom()
                        .ofGet()
                        .url(url)
                        .send(HttpResponse.BodyHandlers.ofByteArray());

        if (200 != res.statusCode()) {
            throw BusinessRuntimeException.getInstance("获取access_token失败: " + IoKit.toString(res.body()));
        }

        AccountJsTicket ticket = Jsons.parseObject(res.body(), AccountJsTicket.class);
        if (null == ticket) {
            throw BusinessRuntimeException.getInstance("获取access_token失败: " + IoKit.toString(res.body()));
        }

        final Integer errcode = ticket.getErrcode();
        if (null != errcode && 0 != errcode) {
            throw BusinessRuntimeException.getInstance("获取access_token失败: " + ticket.getErrmsg() + "[" + errcode + "]");
        }
        return ticket;
    }
}
