package com.rj.gaode;

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

public class AllShopCollectorV5 {

    // ==================== 只需要改这里 5 项 ====================
    private static final String AMAP_KEY = "34eaa47387aa9e8c1a8ca0d4c8abaa1d";     // 替换成你的Key
    private static final String CITY = "河北省廊坊市三河市燕郊镇";                // 城市
    private static final String ADDRESS = "燕顺路星河皓月小区";           // 地标/街道/路（自动转经纬度）
    private static final int RADIUS = 800;                      // 半径800米（可改300/500/1000）
    private static final int MAX_PAGE = 2;                      // 采集页数
    // ==========================================================

    public static void main(String[] args) {
        try {
            System.out.println("正在获取地址：" + ADDRESS + " 的经纬度...");
            String location = getLocationByAddress(CITY, ADDRESS);
            System.out.println("经纬度获取成功：" + location);

            // 开始全行业采集
            for (int page = 1; page <= MAX_PAGE; page++) {
                System.out.println("\n===== 全量采集第 " + page + " 页商家 =====");
                String json = getAllShops(location, page);
                parseAndPrint(json);
                Thread.sleep(800); // 风控间隔，稳定不封号
            }
            System.out.println("\n===== 全行业商家采集完成 =====");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 1. 地址自动转经纬度（核心：不用手动打开网页）
     */
    public static String getLocationByAddress(String city, String address) throws Exception {
        String url = "https://restapi.amap.com/v3/geocode/geo"
                + "?key=" + AMAP_KEY
                + "&city=" + URLEncoder.encode(city, "UTF-8")
                + "&address=" + URLEncoder.encode(address, "UTF-8")
                + "&output=json";
        String json = sendGet(url);
        int start = json.indexOf("\"location\":\"") + 12;
        int end = json.indexOf("\"", start);
        return json.substring(start, end);
    }

    /**
     * 2. 【不指定行业】搜索周边所有商家（核心）
     */
    public static String getAllShops(String location, int page) throws Exception {
        String url = "https://restapi.amap.com/v3/place/around"  // 周边搜索（无关键词=全行业）
                + "?key=" + AMAP_KEY
                + "&location=" + location          // 中心点经纬度
                + "&radius=" + RADIUS             // 半径范围
                + "&offset=50"                   // 每页50条
                + "&page=" + page                // 页码
                + "&output=json";
        return sendGet(url);
    }

    /**
     * HTTP请求工具
     */
    public static String sendGet(String url) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        conn.disconnect();
        return content.toString();
    }

    /**
     * 解析所有商家信息
     */
    public static void parseAndPrint(String json) {
        String[] shops = json.split("\"name\":\"");
        for (int i = 1; i < shops.length; i++) {
            String s = shops[i];
            String name   = get(s, "");
            String addr   = get(s, "address\":\"");
            String tel    = get(s, "tel\":\"");
            String type   = get(s, "type\":\"");
            String loc    = get(s, "location\":\"");

            System.out.println("店名：" + name);
            System.out.println("地址：" + addr);
            System.out.println("电话：" + tel);
            System.out.println("行业：" + type);
            System.out.println("坐标：" + loc);
            System.out.println("---------------------------");
        }
    }

    private static String get(String s, String pre) {
        try {
            int i = s.indexOf(pre) + pre.length();
            return s.substring(i, s.indexOf("\"", i));
        } catch (Exception e) {
            return "无";
        }
    }
}