package com.sikey.wa04.business.infrastructure.adapter.baidumap;

import cn.hutool.json.JSONUtil;
import com.sikey.wa04.business.infrastructure.dto.response.baidu.BaiduLocationResponse;
import com.sikey.wa04.common.utils.BaiduLocationApiClient;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @Author: qin
 * @Date: 2025/3/21
 * @Description: 百度地图
 */
@Slf4j
@Component
public class BaiduMapRequestService {

    /**
     * 成功
     */
    private static final int AM_AP_BAIDU_SUCCESSFUL_STATUS = 0;

    /*@Value("${mapbaidu.key}")
    private String amapBaiduKey;*/

    /*@Value("${mapbaidu.url}")
    private String amapBaiduUrl;*/

    // private final OkHttpClient client = new OkHttpClient();

    /**
     * 百度定位
     *
     * @param map 百度定位
     * @return
     */
    public BaiduLocationResponse locate(Map map) {
        try {
            BaiduLocationApiClient locationApiClient = new BaiduLocationApiClient();
            String locate = locationApiClient.locate(map);
            log.info("[百度定位]定位返回数据：{}", locate);

            int errcode = Integer.parseInt(String.valueOf(JSONUtil.parseObj(locate).get("errcode")));
            String msg = String.valueOf(JSONUtil.parseObj(locate).get("msg"));
            if (errcode != AM_AP_BAIDU_SUCCESSFUL_STATUS) {
                log.warn("[百度定位]百度定位失败：{}", msg);
                throw new IOException("百度定位失败：" + msg);
            }

            String body = String.valueOf(JSONUtil.parseObj(locate).get("body"));
            return JSONUtil.toList(body, BaiduLocationResponse.class).stream().findFirst().get();

        } catch (Exception e) {
            log.error("[百度定位]定位返回数据异常：{0}", e);
        }
        return null;
    }

}
