package com.fs.baidu.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.baidu.domain.BdApi;
import com.fs.baidu.param.BdRequestParam;
import com.fs.baidu.service.IBdApiService;
import com.fs.baidu.vo.BdResultHeaderVo;
import com.fs.baidu.vo.BdResultVo;
import com.fs.common.exception.base.BaseException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

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

@Component
@AllArgsConstructor
public class BdApiRequest {

    public final IBdApiService apiService;

    public <T> String request(String url, Long apiId, String userName, T body){
        BdApi api = apiService.getById(apiId);
        return requestToken(url, api.getAccessToken(), userName, body);
    }

    public <T> String requestToken(String url, String accToken, String userName, T body){
        Map<String, String> header = new HashMap<>();
        header.put("userName", userName);
        header.put("accessToken", accToken);
        BdRequestParam<T> build = BdRequestParam.<T>builder().body(body).header(header).build();
        String json = JSON.toJSONString(build);
        HttpRequest request = HttpUtil.createPost(url).body(json);
        HttpResponse execute = request.execute();
        JSONObject result = JSON.parseObject(execute.body());

        BdResultVo resultVo = new BdResultVo();
        resultVo.setHeader(result.getJSONObject("header").toJavaObject(BdResultHeaderVo.class));
        resultVo.setBody(result.getString("body"));
        if(resultVo.getStatus() != 0){
            throw new BaseException("百度接口请求失败：" + resultVo.getHeader().getFailures().get(0).getMessage());
        }
        return resultVo.getBody();
    }



}
