package com.ghy.web.controller;

import com.ghy.common.core.controller.BaseController;
import com.ghy.shop.domain.Shop;
import com.ghy.shop.domain.ShopDistanceQuery;
import com.ghy.shop.service.ShopService;
import com.ghy.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.client.RestTemplate;
import com.ghy.common.utils.LocationUtils;
import java.util.stream.Collectors;
import java.util.Comparator;

/**
 * 店铺管理接口
 */
@RestController
@RequestMapping("/shop")
public class ShopController extends BaseController {
    @Autowired
    private ShopService shopService;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/add")
    public AjaxResult addShop(@RequestBody Shop shop) {
        // 如果没有经纬度，尝试通过地址解析获取
        if ((shop.getLatitude() == null || shop.getLongitude() == null) && 
            shop.getAddress() != null && !shop.getAddress().trim().isEmpty()) {
            try {
                Map<String, Double> coordinates = getCoordinatesByAddress(shop);
                if (coordinates != null) {
                    shop.setLatitude(coordinates.get("latitude"));
                    shop.setLongitude(coordinates.get("longitude"));
                    logger.info("为店铺[{}]自动获取到坐标: 经度={}, 纬度={}", 
                               shop.getShopName(), shop.getLongitude(), shop.getLatitude());
                }
            } catch (Exception e) {
                logger.warn("获取地址经纬度失败: {}", e.getMessage());
            }
        }
        
        int result = shopService.addShop(shop);
        if (result > 0) {
            Map<String, Object> response = new HashMap<>();
            response.put("shopId", shop.getShopId());
            response.put("shopName", shop.getShopName());
            response.put("latitude", shop.getLatitude());
            response.put("longitude", shop.getLongitude());
            response.put("address", shop.getAddress());
            return AjaxResult.success("店铺创建成功", response);
        } else {
            return AjaxResult.error("店铺创建失败");
        }
    }

    @GetMapping("/list")
    public AjaxResult listShops() {
        List<Shop> list = shopService.listShops();
        return AjaxResult.success(list);
    }

    @GetMapping("/{id}")
    public AjaxResult getShop(@PathVariable Long id) {
        Shop shop = shopService.getShop(id);
        return shop != null ? AjaxResult.success(shop) : AjaxResult.error("未找到店铺");
    }

    @PostMapping("/update")
    public AjaxResult updateShop(@RequestBody Shop shop) {
        // 如果没有经纬度但有地址，尝试通过地址解析获取经纬度
        if ((shop.getLatitude() == null || shop.getLongitude() == null) && 
            shop.getAddress() != null && !shop.getAddress().trim().isEmpty()) {
            try {
                Map<String, Double> coordinates = getCoordinatesByAddress(shop);
                if (coordinates != null) {
                    shop.setLatitude(coordinates.get("latitude"));
                    shop.setLongitude(coordinates.get("longitude"));
                }
            } catch (Exception e) {
                logger.warn("更新店铺时获取地址经纬度失败: {}", e.getMessage());
            }
        }
        return toAjax(shopService.updateShop(shop));
    }

    @PostMapping("/delete/{id}")
    public AjaxResult deleteShop(@PathVariable Long id) {
        return toAjax(shopService.deleteShop(id));
    }

    @GetMapping("/{id}/location")
    public AjaxResult getShopLocation(@PathVariable Long id) {
        Shop shop = shopService.getShop(id);
        if (shop == null) {
            return AjaxResult.error("未找到店铺");
        }
        Map<String, Object> location = new HashMap<>();
        location.put("address", shop.getAddress());
        location.put("latitude", shop.getLatitude());
        location.put("longitude", shop.getLongitude());
        location.put("provinceName", shop.getProvinceName());
        location.put("cityName", shop.getCityName());
        location.put("countryName", shop.getCountryName());
        location.put("streetName", shop.getStreetName());
        return AjaxResult.success(location);
    }

//    @GetMapping("/getCurrentLocation")
//    public AjaxResult getCurrentLocation() {
//        try {
//            // 直接调用百度地图API获取当前位置信息
//            String url = "/tool/baidu/getLocation";
//            return restTemplate.getForObject(url, AjaxResult.class);
//        } catch (Exception e) {
//            return AjaxResult.error("获取当前位置失败：" + e.getMessage());
//        }
//    }

    @GetMapping("/worker/{workerId}")
    public AjaxResult getShopsByWorkerId(@PathVariable Long workerId) {
        List<Shop> shops = shopService.getShopsByWorkerId(workerId);
        return AjaxResult.success(shops);
    }

//    /**
//     * 通过地址获取经纬度坐标
//     */
//    @PostMapping("/getCoordinates")
//    public AjaxResult getCoordinatesByAddress(@RequestBody Shop shop) {
//        try {
//            Map<String, Double> coordinates = getCoordinatesByAddress(shop);
//            if (coordinates != null) {
//                return AjaxResult.success("获取坐标成功", coordinates);
//            } else {
//                return AjaxResult.error("无法获取该地址的坐标信息");
//            }
//        } catch (Exception e) {
//            logger.error("获取坐标失败: {}", e.getMessage(), e);
//            return AjaxResult.error("获取坐标失败: " + e.getMessage());
//        }
//    }
    
    /**
     * 通过经纬度逆解析获取地址信息并保存到店铺
     */
    @PostMapping("/saveShopByLocation")
    public AjaxResult saveShopByLocation(@RequestBody Map<String, Object> params) {
        try {
            String location = params.get("location").toString(); // 格式: "经度,纬度"
            
            // 调用百度地图逆解析API
            String url = "/tool/baidu/getLocation";
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("location", location);
            
            // 这里应该调用百度接口获取地址信息
            // AjaxResult locationResult = restTemplate.postForObject(url, requestBody, AjaxResult.class);
            
            // 解析经纬度
            String[] coordinates = location.split(",");
            if (coordinates.length != 2) {
                return AjaxResult.error("location格式错误，应为：经度,纬度");
            }
            
            Double longitude = Double.parseDouble(coordinates[0]);
            Double latitude = Double.parseDouble(coordinates[1]);
            
            // 创建店铺对象
            Shop shop = new Shop();
            shop.setLongitude(longitude);
            shop.setLatitude(latitude);
            
            // 设置其他信息
            if (params.containsKey("shopName")) {
                shop.setShopName(params.get("shopName").toString());
            }
            if (params.containsKey("workerId")) {
                shop.setWorkerId(Long.valueOf(params.get("workerId").toString()));
            }
            if (params.containsKey("phone")) {
                shop.setPhone(params.get("phone").toString());
            }
            
            // 保存店铺
            int result = shopService.addShop(shop);
            if (result > 0) {
                Map<String, Object> response = new HashMap<>();
                response.put("shopId", shop.getShopId());
                response.put("longitude", longitude);
                response.put("latitude", latitude);
                response.put("location", location);
                return AjaxResult.success("店铺创建成功", response);
            } else {
                return AjaxResult.error("店铺创建失败");
            }
            
        } catch (Exception e) {
            logger.error("通过位置创建店铺失败: {}", e.getMessage(), e);
            return AjaxResult.error("创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 内部方法：通过地址解析获取经纬度
     */
    private Map<String, Double> getCoordinatesByAddress(Shop shop) {
        try {
            // 构建完整地址
            StringBuilder fullAddress = new StringBuilder();
            if (shop.getProvinceName() != null) fullAddress.append(shop.getProvinceName());
            if (shop.getCityName() != null) fullAddress.append(shop.getCityName());
            if (shop.getCountryName() != null) fullAddress.append(shop.getCountryName());
            if (shop.getStreetName() != null) fullAddress.append(shop.getStreetName());
            if (shop.getAddress() != null) fullAddress.append(shop.getAddress());
            
            String address = fullAddress.toString();
            if (address.isEmpty()) {
                return null;
            }
            
            logger.info("开始解析地址获取坐标: {}", address);
            
            // TODO: 这里应该调用真实的地图API
            // 示例：百度地图正向地理编码API
            // String url = "https://api.map.baidu.com/geocoding/v3/?address=" + 
            //              java.net.URLEncoder.encode(address, "UTF-8") + 
            //              "&output=json&ak=YOUR_BAIDU_API_KEY";
            // 
            // String result = restTemplate.getForObject(url, String.class);
            // JSONObject jsonResult = JSONObject.parseObject(result);
            // 
            // if ("0".equals(jsonResult.getString("status"))) {
            //     JSONObject location = jsonResult.getJSONObject("result").getJSONObject("location");
            //     Double lng = location.getDouble("lng");
            //     Double lat = location.getDouble("lat");
            //     
            //     Map<String, Double> coordinates = new HashMap<>();
            //     coordinates.put("longitude", lng);
            //     coordinates.put("latitude", lat);
            //     return coordinates;
            // }
            
            // 临时返回示例坐标（实际使用时请替换为真实的API调用）
            Map<String, Double> coordinates = new HashMap<>();
            coordinates.put("latitude", 39.915 + Math.random() * 0.1); // 示例纬度
            coordinates.put("longitude", 116.404 + Math.random() * 0.1); // 示例经度
            
            logger.info("地址解析成功: {} -> 经度={}, 纬度={}", 
                       address, coordinates.get("longitude"), coordinates.get("latitude"));
            
            return coordinates;
        } catch (Exception e) {
            logger.error("地址解析失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 手动设置店铺经纬度
     */
    @PostMapping("/setCoordinates")
    public AjaxResult setCoordinates(@RequestBody Map<String, Object> params) {
        try {
            Long shopId = Long.valueOf(params.get("shopId").toString());
            Double latitude = Double.valueOf(params.get("latitude").toString());
            Double longitude = Double.valueOf(params.get("longitude").toString());
            
            Shop shop = new Shop();
            shop.setShopId(shopId);
            shop.setLatitude(latitude);
            shop.setLongitude(longitude);
            
            int result = shopService.updateShop(shop);
            if (result > 0) {
                Map<String, Object> response = new HashMap<>();
                response.put("shopId", shopId);
                response.put("latitude", latitude);
                response.put("longitude", longitude);
                return AjaxResult.success("坐标设置成功", response);
            } else {
                return AjaxResult.error("坐标设置失败");
            }
        } catch (Exception e) {
            logger.error("设置坐标失败: {}", e.getMessage(), e);
            return AjaxResult.error("设置坐标失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量查询店铺（包含经纬度信息）
     */
    @PostMapping("/listWithLocation")
    public AjaxResult listShopsWithLocation(@RequestBody(required = false) Map<String, Object> params) {
        try {
            List<Shop> shops = shopService.listShops();
            
            // 可以根据参数进行筛选
            if (params != null) {
                // 按城市筛选
                if (params.containsKey("cityId")) {
                    Long cityId = Long.valueOf(params.get("cityId").toString());
                    shops = shops.stream()
                           .filter(shop -> shop.getCityId() != null && shop.getCityId().equals(cityId))
                           .collect(java.util.stream.Collectors.toList());
                }
                
                // 按师傅筛选
                if (params.containsKey("workerId")) {
                    Long workerId = Long.valueOf(params.get("workerId").toString());
                    shops = shops.stream()
                           .filter(shop -> shop.getWorkerId() != null && shop.getWorkerId().equals(workerId))
                           .collect(java.util.stream.Collectors.toList());
                }
                
                // 只返回有坐标的店铺
                if (params.containsKey("hasLocation") && Boolean.valueOf(params.get("hasLocation").toString())) {
                    shops = shops.stream()
                           .filter(shop -> shop.getLatitude() != null && shop.getLongitude() != null)
                           .collect(java.util.stream.Collectors.toList());
                }
            }
            
            return AjaxResult.success(shops);
        } catch (Exception e) {
            logger.error("查询店铺列表失败: {}", e.getMessage(), e);
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询附近的店铺
     */
    @PostMapping("/nearby")
    public AjaxResult getNearbyShops(@RequestBody Map<String, Object> params) {
        try {
            Double latitude = Double.valueOf(params.get("latitude").toString());
            Double longitude = Double.valueOf(params.get("longitude").toString());
            Double radiusKm = params.containsKey("radiusKm") ? 
                              Double.valueOf(params.get("radiusKm").toString()) : 5.0; // 默认5公里
            
            // 验证坐标有效性
            if (!LocationUtils.isValidCoordinate(latitude, longitude)) {
                return AjaxResult.error("无效的坐标参数");
            }
            
            // 获取所有店铺
            List<Shop> allShops = shopService.listShops();
            
            // 筛选出有坐标的店铺并计算距离
            List<Map<String, Object>> nearbyShops = allShops.stream()
                .filter(shop -> LocationUtils.isValidCoordinate(shop.getLatitude(), shop.getLongitude()))
                .map(shop -> {
                    double distance = LocationUtils.getDistanceInKilometers(
                        latitude, longitude, shop.getLatitude(), shop.getLongitude());
                    
                    Map<String, Object> shopWithDistance = new HashMap<>();
                    shopWithDistance.put("shop", shop);
                    shopWithDistance.put("distance", distance);
                    shopWithDistance.put("distanceText", LocationUtils.formatDistance(distance * 1000));
                    
                    // 计算方向
                    double bearing = LocationUtils.getBearing(latitude, longitude, 
                                                            shop.getLatitude(), shop.getLongitude());
                    shopWithDistance.put("direction", LocationUtils.getDirectionDescription(bearing));
                    shopWithDistance.put("bearing", bearing);
                    
                    return shopWithDistance;
                })
                .filter(shopMap -> (Double) shopMap.get("distance") <= radiusKm)
                .sorted(Comparator.comparingDouble(shopMap -> (Double) shopMap.get("distance")))
                .collect(Collectors.toList());
            
            Map<String, Object> result = new HashMap<>();
            result.put("centerLatitude", latitude);
            result.put("centerLongitude", longitude);
            result.put("radiusKm", radiusKm);
            result.put("totalCount", nearbyShops.size());
            result.put("shops", nearbyShops);
            
            return AjaxResult.success("查询成功", result);
            
        } catch (Exception e) {
            logger.error("查询附近店铺失败: {}", e.getMessage(), e);
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 计算两个店铺之间的距离
     */
    @PostMapping("/distance")
    public AjaxResult getShopsDistance(@RequestBody Map<String, Object> params) {
        try {
            Long shopId1 = Long.valueOf(params.get("shopId1").toString());
            Long shopId2 = Long.valueOf(params.get("shopId2").toString());
            
            Shop shop1 = shopService.getShop(shopId1);
            Shop shop2 = shopService.getShop(shopId2);
            
            if (shop1 == null || shop2 == null) {
                return AjaxResult.error("店铺不存在");
            }
            
            if (!LocationUtils.isValidCoordinate(shop1.getLatitude(), shop1.getLongitude()) ||
                !LocationUtils.isValidCoordinate(shop2.getLatitude(), shop2.getLongitude())) {
                return AjaxResult.error("店铺坐标信息不完整");
            }
            
            double distanceKm = LocationUtils.getDistanceInKilometers(
                shop1.getLatitude(), shop1.getLongitude(),
                shop2.getLatitude(), shop2.getLongitude());
            
            double bearing = LocationUtils.getBearing(
                shop1.getLatitude(), shop1.getLongitude(),
                shop2.getLatitude(), shop2.getLongitude());
            
            Map<String, Object> result = new HashMap<>();
            result.put("shop1", shop1);
            result.put("shop2", shop2);
            result.put("distanceKm", distanceKm);
            result.put("distanceText", LocationUtils.formatDistance(distanceKm * 1000));
            result.put("direction", LocationUtils.getDirectionDescription(bearing));
            result.put("bearing", bearing);
            
            return AjaxResult.success("计算成功", result);
            
        } catch (Exception e) {
            logger.error("计算店铺距离失败: {}", e.getMessage(), e);
            return AjaxResult.error("计算失败: " + e.getMessage());
        }
    }
    
    /**
     * 通过店铺ID查询详细信息并计算距离
     * 最终效果：
     * 1. 传入的详细地址 → 转换为经纬度
     * 2. 店铺有经纬度 → 直接使用
     * 3. 店铺没有经纬度 → 通过详细地址生成经纬度
     * 4. 最终通过经纬度计算距离 → 放在店铺的距离字段上
     * 
     * @param query 距离查询请求实体
     * @return 包含距离信息的完整店铺详情
     */
    @PostMapping("/getShopDetailWithDistance")
    public AjaxResult getShopDetailWithDistance(@RequestBody ShopDistanceQuery query) {
        try {
            // 验证参数
            if (query.getShopId() == null) {
                return AjaxResult.error("店铺ID不能为空");
            }
            
            // 验证是否有足够的信息来计算距离或获取位置
            if (!query.hasEnoughInfo()) {
                return AjaxResult.error("请提供经纬度或地址信息");
            }
            
            // 如果提供了经纬度，验证其有效性
            if (query.hasCoordinateInfo() && !LocationUtils.isValidCoordinate(query.getLatitude(), query.getLongitude())) {
                return AjaxResult.error("无效的坐标参数");
            }
            
            // 验证地址参数（如果提供了地址信息，则验证其完整性）
            if (query.hasAddressInfo()) {
                String fullAddress = query.getFullAddress();
                if (fullAddress.trim().length() < 5) {
                    return AjaxResult.error("地址信息不完整，请提供更详细的地址");
                }
                logger.info("使用传入的地址信息: {}", fullAddress);
            }
            
            // 调用服务层方法获取店铺详情和距离
            Shop shop = shopService.getShopWithDistance(query);
            
            if (shop == null) {
                return AjaxResult.error("未找到店铺");
            }
            
            // 检查距离是否有效
            if (shop.getDistance() == null || shop.getDistance().equals("无法计算距离")) {
                if (query.hasCoordinateInfo()) {
                    return AjaxResult.error("无法计算店铺距离，请检查店铺地址信息或提供更详细的地址参数");
                } else {
                    // 如果没有经纬度，只获取位置信息
                    logger.info("仅获取店铺位置信息，无法计算距离");
                }
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("shopId", shop.getShopId());
            result.put("shopName", shop.getShopName());
            result.put("imageUrl", shop.getImageUrl());
            result.put("workerId", shop.getWorkerId());
            result.put("provinceId", shop.getProvinceId());
            result.put("provinceName", shop.getProvinceName());
            result.put("cityId", shop.getCityId());
            result.put("cityName", shop.getCityName());
            result.put("countryId", shop.getCountryId());
            result.put("countryName", shop.getCountryName());
            result.put("streetId", shop.getStreetId());
            result.put("streetName", shop.getStreetName());
            result.put("address", shop.getAddress());
            result.put("phone", shop.getPhone());
            result.put("latitude", shop.getLatitude());
            result.put("longitude", shop.getLongitude());
            result.put("distance", shop.getDistance());
            

            return AjaxResult.success("查询成功", result);
            
        } catch (Exception e) {
            logger.error("查询店铺详情失败: {}", e.getMessage(), e);
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }
    
//    /**
//     * 获取店铺覆盖范围内的其他店铺
//     */
//    @PostMapping("/coverage")
//    public AjaxResult getShopsCoverage(@RequestBody Map<String, Object> params) {
//        try {
//            Long shopId = Long.valueOf(params.get("shopId").toString());
//            Double radiusKm = params.containsKey("radiusKm") ?
//                              Double.valueOf(params.get("radiusKm").toString()) : 10.0; // 默认10公里
//
//            Shop centerShop = shopService.getShop(shopId);
//            if (centerShop == null) {
//                return AjaxResult.error("店铺不存在");
//            }
//
//            if (!LocationUtils.isValidCoordinate(centerShop.getLatitude(), centerShop.getLongitude())) {
//                return AjaxResult.error("中心店铺坐标信息不完整");
//            }
//
//            // 获取附近的店铺
//            Map<String, Object> nearbyParams = new HashMap<>();
//            nearbyParams.put("latitude", centerShop.getLatitude());
//            nearbyParams.put("longitude", centerShop.getLongitude());
//            radiusKm);
//
//            AjaxResult nearbyResult = getNearbyShops(nearbyParams);
//            if (nearbyResult.isSuccess()) {
//                Map<String, Object> data = (Map<String, Object>) nearbyResult.get("data");
//                List<Map<String, Object>> shops = (List<Map<String, Object>>) data.get("shops");
//
//                // 排除自己
//                shops = shops.stream()
//                      .filter(shopMap -> {
//                          Shop shop = (Shop) shopMap.get("shop");
//                          return !shop.getShopId().equals(shopId);
//                      })
//                      .collect(Collectors.toList());
//
//                data.put("centerShop", centerShop);
//                data.put("shops", shops);
//                data.put("totalCount", shops.size());
//
//                return AjaxResult.success("查询成功", data);
//            } else {
//                return nearbyResult;
//            }
//
//        } catch (Exception e) {
//            logger.error("查询店铺覆盖范围失败: {}", e.getMessage(), e);
//            return AjaxResult.error("查询失败: " + e.getMessage());
//        }
//    }
} 