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 AutoLocationCollector {

    // ==================== 配置区（只改这里）====================
    private static final String AMAP_KEY = "你的Web服务Key";
    private static final String CITY = "杭州市";                // 城市
    private static final String ADDRESS = "万达广场";           // 地标/街道/路/建筑（自动转经纬度）
    private static final String KEYWORDS = "餐饮";               // 招商行业
    private static final String TYPES = "050000";                // 行业编码
    private static final int RADIUS = 800;                       // 半径800米
    private static final int MAX_PAGE = 3;                       // 采集页数
    // ==========================================================

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

            // 2. 自动采集周边商家
            for (int page = 1; page <= MAX_PAGE; page++) {
                System.out.println("\n===== 正在采集第 " + page + " 页商家 =====");
                String json = getShopList(location, page);
                parseAndPrint(json);
                Thread.sleep(800);
            }
            System.out.println("\n===== 全自动招商采集完成 =====");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 高德地理编码API：地址 → 自动获取经纬度
     */
    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 = sendHttpRequest(url);
        return extractLocation(json);
    }

    /**
     * 调用POI搜索，获取周边商家
     */
    public static String getShopList(String location, int page) throws Exception {
        String url = "https://restapi.amap.com/v3/place/text"
                + "?key=" + AMAP_KEY
                + "&city=" + URLEncoder.encode(CITY, "UTF-8")
                + "&keywords=" + URLEncoder.encode(KEYWORDS, "UTF-8")
                + "&types=" + TYPES
                + "&location=" + location
                + "&radius=" + RADIUS
                + "&citylimit=true"
                + "&offset=50"
                + "&page=" + page
                + "&output=json";
        return sendHttpRequest(url);
    }

    /**
     * 统一HTTP请求工具
     */
    public static String sendHttpRequest(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuilder result = new StringBuilder();
        while ((line = br.readLine()) != null) {
            result.append(line);
        }
        br.close();
        conn.disconnect();
        return result.toString();
    }

    /**
     * 从地理编码结果中提取经纬度
     */
    public static String extractLocation(String json) {
        int start = json.indexOf("\"location\":\"") + 12;
        int end = json.indexOf("\"", start);
        return json.substring(start, end);
    }

    /**
     * 解析并打印商家信息
     */
    public static void parseAndPrint(String json) {
        String[] shops = json.split("\"name\":\"");
        for (int i = 1; i < shops.length; i++) {
            String item = shops[i];
            String name = getItem(item, "");
            String address = getItem(item, "address\":\"");
            String tel = getItem(item, "tel\":\"");
            String type = getItem(item, "type\":\"");
            String location = getItem(item, "location\":\"");

            System.out.println("店名：" + name);
            System.out.println("地址：" + address);
            System.out.println("电话：" + tel);
            System.out.println("类型：" + type);
            System.out.println("坐标：" + location);
            System.out.println("---------------------------");
        }
    }

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