package com.ghy.web.controller.tool;


import com.alibaba.fastjson.JSONObject;
import com.ghy.common.config.BaiduConfig;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.http.HttpUtils;
import com.ghy.framework.web.domain.server.Sys;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 百度地图逆解析
 * @author clunt
 */
@Controller
@RequestMapping("/tool/baidu")
public class BaiduController extends BaseController {

    @Autowired
    private BaiduConfig baiduConfig;

    @Autowired
    private ISysAreaService iSysAreaService;

    @PostMapping("/getLocation")
    @ResponseBody
    public AjaxResult getLocationByLot(@RequestBody JSONObject jsonObject){
        try {
            JSONObject json = new JSONObject();

            String location = jsonObject.getString("location");
            
            // 解析经纬度
            String[] coordinates = location.split(",");
            if (coordinates.length != 2) {
                return AjaxResult.error("location格式错误，应为：经度,纬度");
            }
            
            try {
                double longitude = Double.parseDouble(coordinates[1]); // 经度
                double latitude = Double.parseDouble(coordinates[0]);  // 纬度
                
                // 将经纬度添加到返回结果中
                json.put("longitude", longitude);
                json.put("latitude", latitude);
                json.put("coordinates", coordinates);
                
                logger.info("解析到的坐标 - 经度: {}, 纬度: {}", longitude, latitude);
            } catch (NumberFormatException e) {
                return AjaxResult.error("经纬度格式错误");
            }
            
            String url = baiduConfig.getUrl().replace("#AK#", baiduConfig.getAk()) + location;
            String result = HttpUtils.sendGet(url);
            result = result.replaceAll("\n", "").replaceAll("\t", "");
            JSONObject resultJson = JSONObject.parseObject(result);
            if("0".equals(resultJson.getString("status"))){
                JSONObject addressJson = resultJson.getJSONObject("result").getJSONObject("addressComponent");
                logger.info("百度地图获取到的地址 :" + addressJson);
                String provinceName = addressJson.getString("province");
                logger.info("provinceName :" + provinceName);
                SysArea provinceArea = iSysAreaService.selectByName(provinceName, null);
                String cityName = addressJson.getString("city");
                logger.info("cityName :" + cityName);
                SysArea cityArea = iSysAreaService.selectByName(cityName, provinceArea.getAreaCode());
                String countryName = addressJson.getString("district");
                logger.info("countryName :" + countryName);
                SysArea countryArea = iSysAreaService.selectByName(countryName, cityArea.getAreaCode());
                String streetName = addressJson.getString("town");
                logger.info("streetName :" + streetName);
                SysArea streetArea = iSysAreaService.selectByName(streetName, countryArea.getAreaCode());
                
                // 添加地址信息
                json.put("provinceArea", provinceArea);
                json.put("cityArea", cityArea);
                json.put("countryArea", countryArea);
                json.put("streetArea", streetArea);
                
                // 添加完整地址
                String fullAddress = (provinceName != null ? provinceName : "") + 
                                   (cityName != null ? cityName : "") + 
                                   (countryName != null ? countryName : "") + 
                                   (streetName != null ? streetName : "");
                json.put("fullAddress", fullAddress);
                
                // 保留原有的location字段用于兼容
                json.put("location", location);
            }else {
                return AjaxResult.error("Api服务异常!");
            }
            return AjaxResult.success(json);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    /**
     * 百度地图正向地理编码（地址 -> 经纬度）
     * 接收JSON：{provinceName, cityName, countryName, streetName, address}
     */
    @PostMapping("/geocode")
    @ResponseBody
    public AjaxResult geocode(@RequestBody JSONObject jsonObject) {
        try {
            String provinceName = jsonObject.getString("provinceName");
            String cityName = jsonObject.getString("cityName");
            String countryName = jsonObject.getString("countryName");
            String streetName = jsonObject.getString("streetName");
            String detailAddress = jsonObject.getString("address");

            StringBuilder full = new StringBuilder();
            if (provinceName != null) { full.append(provinceName); }
            if (cityName != null) { full.append(cityName); }
            if (countryName != null) { full.append(countryName); }
            if (streetName != null) { full.append(streetName); }
            if (detailAddress != null) { full.append(detailAddress); }

            String address = full.toString();
            if (address == null || address.trim().isEmpty()) {
                return AjaxResult.error("地址不能为空");
            }

            String encoded = URLEncoder.encode(address, StandardCharsets.UTF_8.name());
            // 使用百度正向地理编码API
            String url = "https://api.map.baidu.com/geocoding/v3/?output=json&ak="
                    + baiduConfig.getAk() + "&address=" + encoded;

            String result = HttpUtils.sendGet(url);
            result = result.replaceAll("\n", "").replaceAll("\t", "");
            JSONObject resultJson = JSONObject.parseObject(result);
            if ("0".equals(resultJson.getString("status"))) {
                JSONObject location = resultJson.getJSONObject("result").getJSONObject("location");
                JSONObject data = new JSONObject();
                data.put("longitude", location.getBigDecimal("lng"));
                data.put("latitude", location.getBigDecimal("lat"));
                data.put("fullAddress", address);
                return AjaxResult.success(data);
            } else {
                return AjaxResult.error("百度地理编码失败:" + resultJson.getString("msg"));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }


    public static void main(String[] args) {
        String result = " {\"status\":0,\"result\":{\"location\":{\"lng\":113.29950224957551,\"lat\":23.019282373814027},\"formatted_address\":\"广东省广州市番禺区安平路\",\"business\":\"大石\",\"addressComponent\":{\"country\":\"中国\",\"country_code\":0,\"country_code_iso\":\"CHN\",\"country_code_iso2\":\"CN\",\"province\":\"广东省\",\"city\":\"广州市\",\"city_level\":2,\"district\":\"番禺区\",\"town\":\"\",\"town_code\":\"\",\"distance\":\"\",\"direction\":\"\",\"adcode\":\"440113\",\"street\":\"安平路\",\"street_number\":\"\"},\"pois\":[],\"roads\":[],\"poiRegions\":[],\"sematic_description\":\"\",\"cityCode\":257}}\n";
    }
}
