package com.tourism.webadmin.app.wechat.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.webadmin.app.wechat.dto.MapDto;
import com.tourism.webadmin.back.model.TourMapData;
import com.tourism.webadmin.back.service.TourMapDataService;
import com.tourism.webadmin.back.vo.TourMapDataVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

@Tag(name = "小程序地图板块接口")
@Slf4j
@SaIgnore
@RestController
@RequestMapping("/wechat/map")
public class WechatMapController {
    public static String REVERSEGEO = "http://restapi.amap.com/v3/geocode/regeo?";

    public static String SEARCHPOI = "http://restapi.amap.com/v3/place/text?";

    public static String AK = "3f9549681920d6d9c504fa73186c416e";

    @Autowired
    public TourMapDataService tourMapDataService;

    /**
     * 逆地理解析接口
     */
    @SaIgnore
    @GetMapping("reverse/geo")
    public ResponseResult<Map<String, Object>> reverseGeo() throws Exception{


        Map params = new LinkedHashMap<String, String>();
        params.put("key", AK);
        params.put("location", "9.585539,49.431014");
        String result = this.requestGetAK(REVERSEGEO, params);

        Map<String, Object> map = new HashMap<>();
        // 解析JSON字符串
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            // 获取状态码
            String status = jsonObject.getString("status");
            if ("1".equals(status)) {
                // 获取信息
//                String info = jsonObject.getString("info");
//                String infocode = jsonObject.getString("infocode");
                JSONObject regeocode = JSONObject.parseObject(jsonObject.getString("regeocode"));
                // 获取地址信息
                String formattedAddress = regeocode.getString("formatted_address");
                map.put("address", formattedAddress);
                String country = regeocode.getString("country");
                String province = regeocode.getString("province");
                String city = regeocode.getString("city");
                String adcode = regeocode.getString("adcode");
                String rectangle = regeocode.getString("rectangle");
                String level = regeocode.getString("level");

                // 输出地址信息
                System.out.println("Formatted Address: " + formattedAddress);
                System.out.println("Country: " + country);
                System.out.println("Province: " + province);
                System.out.println("City: " + city);
                System.out.println("Adcode: " + adcode);
                System.out.println("Rectangle: " + rectangle);
                System.out.println("Level: " + level);
            } else {
                System.out.println("请求失败，状态码: " + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(map);
    }

    /**
     * POI搜索接口
     */
    @SaIgnore
    @GetMapping("searchPoi")
    public ResponseResult<List<Map<String, Object>>> searchPOI(@Valid MapDto mapDto) throws Exception{
        List<Map<String, Object>> list = new ArrayList<>();
        Map param = new LinkedHashMap<String, String>();
        param.put("key", AK);
        param.put("keywords", mapDto.getKeywords());
        param.put("city", mapDto.getCity());
        param.put("offset", "20");
        param.put("citylimit", "true");
        String result = this.requestGetAK(SEARCHPOI, param);
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);

            // 获取状态码
            String status = jsonObject.getString("status");
            if ("1".equals(status)) {
                // 获取信息
//                String info = jsonObject.getString("info");
//                String infocode = jsonObject.getString("infocode");
                int count = jsonObject.getInteger("count");

                // 获取pois数组
                JSONArray pois = jsonObject.getJSONArray("pois");

                // 遍历pois数组
                for (int i = 0; i < pois.size(); i++) {
                    Map<String, Object> map = new HashMap<>();
                    JSONObject poi = pois.getJSONObject(i);

                    // 获取POI信息
//                    String id = poi.getString("id");
                    String name = poi.getString("name");
                    map.put("address", name);
//                    String location = poi.getString("location");
//                    String address = poi.getString("address");
//                    String type = poi.getString("type");
//                    String adname = poi.getString("adname");
//                    String adcode = poi.getString("adcode");
//                    String businessArea = poi.getString("business_area");
//                    String poiWeight = poi.getString("poiweight");
//                    String entrLocation = poi.getString("entr_location");
//                    String exitLocation = poi.getString("exit_location");
//                    String gridcode = poi.getString("gridcode");
//                    String naviPoiid = poi.getString("navi_poiid");
//                    String distance = poi.getString("distance");
//                    String bizType = poi.getString("biz_type");
//                    String tel = poi.getString("tel");
//                    String website = poi.getString("website");
//                    String email = poi.getString("email");
//                    String postcode = poi.getString("postcode");
//                    String tag = poi.getString("tag");

                    // 获取照片数组
//                    JSONArray photos = poi.getJSONArray("photos");
//                    for (int j = 0; j < photos.size(); j++) {
//                        JSONObject photo = photos.getJSONObject(j);
//                        String photoUrl = photo.getString("url");
//                        String photoTitle = photo.getString("title");
//                        String photoWidth = photo.getString("width");
//                        String photoHeight = photo.getString("height");
//                    }
                    list.add(map);
                }
            } else {
                System.out.println("请求失败，状态码: " + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return ResponseResult.success(list);
    }


    public String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return "";
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        System.out.println("AK: " + buffer.toString());
        return buffer.toString();
    }


    /**
     * 城市定位接口
     */
    @SaIgnore
    @GetMapping("searchCity")
    public ResponseResult<List<TourMapDataVo>> searchCity() throws Exception{

        List<TourMapData> list = tourMapDataService.getTourMapDataList(null, null);

        List<TourMapDataVo> vos = MyModelUtil.copyCollectionTo(list, TourMapDataVo.class);

        return ResponseResult.success(vos);
    }
}
