package shop.alien.storeplatform.util;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import shop.alien.entity.store.EssentialCityCode;
import shop.alien.mapper.EssentialCityCodeMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * 高德地图API工具类
 *
 * @author ssk
 * @version 1.0.0
 * @since 2025-01-xx
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GaoDeMapApiUtil {

    @Value("${gaode.key}")
    private String key;

    @Value("${gaode.geoUrl}")
    private String geoUrl;

    @Value("${gaode.geoListUrl}")
    private String geoListUrl;

    @Value("${gaode.getDistrict}")
    private String getDistrict;

    @Value("${gaode.distanceUrl}")
    private String distanceUrl;

    @Value("${gaode.distanceTypeUrl}")
    private String distanceTypeUrl;

    @Value("${gaode.nearUrl}")
    private String nearUrl;

    @Value("${gaode.subwayUrl}")
    private String subwayUrl;

    @Value("${gaode.addressUrl}")
    private String addressUrl;

    private final EssentialCityCodeMapper essentialCityCodeMapper;

    /**
     * 根据关键词获取地址提示
     *
     * @param address 地址关键词
     * @param city    城市名称
     * @return JSONObject
     */
    public JSONObject getInputPrompt(String address, String city) {
        log.info("GaoDeMapApiUtil.getInputPrompt?address={}&city={}", address, city);
        
        // 如果按照城市查询，需要获取城市编码
        String cityCode = "";
        if (StringUtils.isNotEmpty(city)) {
            LambdaQueryWrapper<EssentialCityCode> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EssentialCityCode::getAreaName, city);
            EssentialCityCode essentialCityCode = essentialCityCodeMapper.selectOne(wrapper);
            if (null != essentialCityCode) {
                cityCode = essentialCityCode.getCityCode().toString();
            }
        }
        
        // 调用高德地图输入提示接口
        String formattedUrl = String.format(geoListUrl, address, key, cityCode);
        JSONObject obj = getResponse(formattedUrl);
        return obj;
    }

    /**
     * 获取行政区划
     *
     * @param adCode 行政区划代码
     * @return JSONObject
     */
    public JSONObject getDistrict(String adCode) {
        log.info("GaoDeMapApiUtil.getDistrict?adCode={}", adCode);
        
        // 调用高德地图行政区划接口
        String formattedUrl = String.format(getDistrict, key, adCode);
        JSONObject obj = getResponse(formattedUrl);
        return obj;
    }


    public JSONObject getNearbySubway(String longitude, String latitude) {
        try {
            // 使用高德地图POI搜索接口，搜索类型为地铁站(010100)
            String encodedKeywords = URLEncoder.encode("地铁站", "UTF-8");
            String urlString = String.format(
                    subwayUrl,
                    key, latitude, longitude, encodedKeywords, 1000, 150500);
            JSONObject obj = getResponse(urlString);
            if (null != obj && "1".equals(String.valueOf(obj.get("status")))) {
                JSONObject pois = obj.getJSONArray("pois").getJSONObject(0);
                return pois;
            }
        } catch (Exception e) {
            log.error("GaoDeMapUtil.getNearbySubway ERROR {}", e.getMessage());
        }
        return new JSONObject();
    }


//
//    /**
//     * 获取附近地铁站
//     *
//     * @param longitude 经度
//     * @param latitude  纬度
//     * @return JSONObject 包含地铁站名称和位置信息
//     */
//    public JSONObject getNearbySubway(String longitude, String latitude) {
//        log.info("GaoDeMapApiUtil.getNearbySubway?longitude={}&latitude={}", longitude, latitude);
//
//        try {
//            // 调用高德地图周边搜索接口，查询地铁站
//            // types=150500 表示地铁站类型
//            String location = longitude + "," + latitude;
//            String formattedUrl = String.format(getNearbyUrl, location, key);
//            JSONObject response = getResponse(formattedUrl);
//
//            if (response != null && "1".equals(response.getString("status"))) {
//                com.alibaba.fastjson.JSONArray pois = response.getJSONArray("pois");
//                if (pois != null && !pois.isEmpty()) {
//                    // 返回最近的地铁站信息
//                    JSONObject nearestSubway = pois.getJSONObject(0);
//                    log.info("GaoDeMapApiUtil.getNearbySubway - 找到最近地铁站: {}",
//                            nearestSubway.getString("name"));
//                    return nearestSubway;
//                }
//            }
//
//            log.warn("GaoDeMapApiUtil.getNearbySubway - 未找到附近地铁站");
//            return new JSONObject();
//        } catch (Exception e) {
//            log.error("GaoDeMapApiUtil.getNearbySubway ERROR: {}", e.getMessage(), e);
//            return new JSONObject();
//        }
//    }

    /**
     * 创建HTTP请求并获取响应
     *
     * @param serverUrl 请求地址
     * @return JSONObject
     */
    private JSONObject getResponse(String serverUrl) {
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            log.error("GaoDeMapApiUtil.getResponse ERROR {}", e.getMessage());
            return null;
        }
        return JSONObject.parseObject(result.toString());
    }
}

