package com.ghy.web.controller.goods;

import com.ghy.common.annotation.Log;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.ShiroUtils;
import com.ghy.common.utils.StringUtils;
import com.ghy.common.utils.bean.BeanUtils;
import com.ghy.common.utils.poi.ExcelUtil;
import com.ghy.common.utils.LocationUtils;
import com.ghy.common.utils.http.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import com.ghy.goods.domain.*;
import com.ghy.goods.service.*;
import com.ghy.shop.domain.Shop;
import com.ghy.shop.service.ShopService;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import io.swagger.annotations.ApiModel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import com.ghy.common.utils.BaiduMapUtils;

@Controller
@RequestMapping("/goods/goods")
public class GoodsController extends BaseController {

    private static final String PREFIX = "goods/goods";

    @Resource
    private GoodsService goodsService;
    @Resource
    private DeptGoodsCategoryService deptGoodsCategoryService;
    @Resource
    private GoodsCategoryService goodsCategoryService;
    @Resource
    private GoodsImgsService goodsImgsService;
    @Resource
    private GoodsAreaService goodsAreaService;
    @Resource
    private GoodsStandardService goodsStandardService;
    @Resource
    private ISysAreaService sysAreaService;
    @Resource
    private IInsuranceManagerService insuranceManagerService;
    @Resource
    private IDeptCategoryInsuranceRelationService deptCategoryInsuranceRelationService;
    @Resource
    private ShopService shopService;
    @Resource
    private BaiduMapUtils baiduMapUtils;

    @RequiresPermissions("goods:goods:view")
    @GetMapping()
    public String goods() {
        return PREFIX + "/goods";
    }

//    @RequiresPermissions("goods:goods:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Goods goods) {
        startPage();
        List<Goods> list = goodsService.selectGoodsList(goods);
        list.forEach(one -> {
            // 补全商品
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(one.getGoodsId());
            one.setGoodsAreaList(goodsAreas);

            // 补全商品类别
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(one.getGoodsId());
            one.setGoodsStandardList(goodsStandards);
        });
        return getDataTable(list);
    }

    @PostMapping("/app/detail")
    @ResponseBody
    public AjaxResult appDetail(@RequestBody Goods goods){
        try {
            GoodsEditReq goodsEditReq = new GoodsEditReq();
            List<Goods> list = goodsService.selectGoodsList(goods);
            if(CollectionUtils.isNotEmpty(list)){
                BeanUtils.copyProperties(list.get(0), goodsEditReq);
            }
            // 补全商品服务区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(goodsEditReq.getGoodsId());
            if(CollectionUtils.isNotEmpty(goodsAreas)){
                String areaName;
                GoodsArea goodsArea = goodsAreas.get(0);
                // 第三级
                SysArea sysArea3 = sysAreaService.selectById(goodsArea.getCountryAreaId());
                // 第二级
                SysArea sysArea2 = sysAreaService.selectByAreaCode(sysArea3.getParentCode());
                // 第一级
                SysArea sysArea1 = sysAreaService.selectByAreaCode(sysArea2.getParentCode());
                areaName = sysArea1.getAreaName() + "-" + sysArea2.getAreaName();
                goodsEditReq.setAreaConcatName(areaName);
                goodsEditReq.setParentAreaId(sysArea2.getAreaId());
            }
            goodsEditReq.setGoodsAreaList(goodsAreas);


            // 补全商品规格
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(goodsEditReq.getGoodsId());
            if(CollectionUtils.isNotEmpty(goodsStandards)){
                String standardConcatName;
                GoodsStandard goodsStandard = goodsStandards.get(0);
                DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
                // 当前层级4
                GoodsCategory goodsCategory4 = goodsCategoryService.selectById(deptGoodsCategory.getGoodsCategoryId());
                GoodsCategory goodsCategory3 = goodsCategoryService.selectById(goodsCategory4.getParentCategoryId());
                GoodsCategory goodsCategory2 = goodsCategoryService.selectById(goodsCategory3.getParentCategoryId());
                GoodsCategory goodsCategory1 = goodsCategoryService.selectById(goodsCategory2.getParentCategoryId());
                standardConcatName = goodsCategory1.getGoodsCategoryName() + "-" + goodsCategory2.getGoodsCategoryName() + "-" + goodsCategory3.getGoodsCategoryName();
                goodsEditReq.setCategoryConcatName(standardConcatName);
            }
            //
            goodsStandards.forEach(goodsStandard -> {
                DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
                GoodsCategory category = goodsCategoryService.selectById(deptGoodsCategory.getGoodsCategoryId());
                goodsStandard.setGoodsCategoryName(category.getGoodsCategoryName());
                goodsStandard.setChecked(true);
                goodsStandard.setOneRate(deptGoodsCategory.getOneRate());
                goodsStandard.setTwoRate(deptGoodsCategory.getTwoRate());
                goodsStandard.setThreeRate(deptGoodsCategory.getThreeRate());
                goodsStandard.setDeptRate(deptGoodsCategory.getDeptRate());
                goodsStandard.setDeptMoney(deptGoodsCategory.getDeptMoney());
                goodsStandard.setRetainMoney(deptGoodsCategory.getRetainMoney());
                goodsStandard.setRetainRate(deptGoodsCategory.getRetainRate());

            });
            goodsEditReq.setGoodsStandardList(goodsStandards);

            // 补全商品类目及父级类目信息
            GoodsCategory goodsCategory = goodsCategoryService.selectById(goodsEditReq.getDeptGoodsCategoryId());
            goodsEditReq.setDeptGoodsCategoryName(goodsCategory.getGoodsCategoryName());
            if (goodsCategory.getParentCategoryId() != null) {
                GoodsCategory parGoodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
                goodsEditReq.setParGoodsCategoryId(parGoodsCategory.getGoodsCategoryId());
                goodsEditReq.setParGoodsCategoryName(parGoodsCategory.getGoodsCategoryName());
            }
            List<String> detailUrl = new ArrayList<>();
            List<String> lbUrl = new ArrayList<>();
            List<GoodsImgs> goodsImgs = goodsImgsService.selectByGoodsId(goods.getGoodsId());
            goodsImgs.forEach(imgs -> {
                if(imgs.getImgType() == 0){
                    lbUrl.add(imgs.getImgUrl());
                }else if(imgs.getImgType() == 1){
                    detailUrl.add(imgs.getImgUrl());
                }
            });
            goodsEditReq.setLbUrl(lbUrl);
            goodsEditReq.setDetailUrl(detailUrl);
            return AjaxResult.success(goodsEditReq);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody Goods goods) {
        Integer type=goods.getType();
        if (type==null){
            goods.setType(1);
        }
        
        // 获取用户当前位置
        Double userLatitude = goods.getLatitude();
        Double userLongitude = goods.getLongitude();
        
        // 判断类目id是否为第三级，不是的话需要找到所有符合条件的第三级类目id作为新的条件
        if (goods.getDeptGoodsCategoryId() != null) {
            logger.info("入参：" + goods.getDeptGoodsCategoryId());
            GoodsCategory goodsCategory = goodsCategoryService.selectById(goods.getDeptGoodsCategoryId());
            logger.info("查询到的类目：" + goodsCategory);
            if (goodsCategory.getLevel() == 0) {
                goods.setDeptGoodsCategoryId(null);
            } else if (goodsCategory.getLevel() == 1) {
                GoodsCategory params = new GoodsCategory();
                params.setParentCategoryId(goodsCategory.getGoodsCategoryId());
                List<GoodsCategory> secondCategories = goodsCategoryService.selectGoodsCategoryList(params);
                List<Long> secondCategoryIds = secondCategories.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList());
                List<Long> thirdCategoryIds = new ArrayList<Long>();
                secondCategoryIds.forEach(id -> {
                    params.setParentCategoryId(id);
                    List<GoodsCategory> thirdCategories = goodsCategoryService.selectGoodsCategoryList(params);
                    thirdCategoryIds.addAll(thirdCategories.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList()));
                });
                if (CollectionUtils.isNotEmpty(thirdCategoryIds)) {
                    goods.setDeptGoodsCategoryId(null);
                    goods.setDeptGoodsCategoryIds(thirdCategoryIds);
                } else {
                    goods.setDeptGoodsCategoryId(-1l);
                }
            } else if (goodsCategory.getLevel() == 2) {
                GoodsCategory params = new GoodsCategory();
                params.setParentCategoryId(goodsCategory.getGoodsCategoryId());
                List<GoodsCategory> filteredCategory = goodsCategoryService.selectGoodsCategoryList(params);
                List<Long> filteredCategoryIds = filteredCategory.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(filteredCategoryIds)) {
                    goods.setDeptGoodsCategoryId(null);
                    goods.setDeptGoodsCategoryIds(filteredCategoryIds);
                } else {
                    goods.setDeptGoodsCategoryId(-1l);
                }
            }
        }

        // 通过商品规格名称模糊查询
        if (StringUtils.isNotEmpty(goods.getGoodsStandard())) {
            logger.info("通过商品规格查询：{}", goods.getGoodsStandard());
            List<GoodsStandard> matchedStandards = goodsStandardService.selectByStandardNameLike(goods.getGoodsStandard());
            if (CollectionUtils.isNotEmpty(matchedStandards)) {
                // 获取所有符合规格条件的商品ID
                List<Long> goodsIds = matchedStandards.stream()
                    .map(GoodsStandard::getGoodsId)
                    .distinct()
                    .collect(Collectors.toList());
                logger.info("通过规格查询到的商品ID列表：{}", goodsIds);
                
                // 设置商品ID筛选条件，与现有的类目筛选条件组合使用
                if (goods.getGoodsIds() == null) {
                    goods.setGoodsIds(goodsIds);
                } else {
                    // 如果已有商品ID筛选条件，取交集
                    goods.getGoodsIds().retainAll(goodsIds);
                }
            } else {
                logger.info("未找到符合规格条件的商品，设置空结果");
                // 如果没找到符合条件的规格，设置一个不存在的商品ID
                goods.setGoodsIds(Arrays.asList(-1L));
            }
        }

        startPage();

        List<Goods> list = goodsService.selectGoodsList(goods);
        logger.info("传入的类目id汇总{},传入的goods信息为{},获取到的所有商品{}",goods.getDeptGoodsCategoryIds(),goods,list);
        
        // 用于缓存店铺信息，避免重复查询
        Map<Long, Shop> shopCache = new HashMap<>();
        
        list.forEach(one -> {
            // 补全商品服务区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(one.getGoodsId());
            one.setGoodsAreaList(goodsAreas);

            // 补全商品规格
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(one.getGoodsId());
            one.setGoodsStandardList(goodsStandards);

            // 补全商品类目及父级类目信息
            GoodsCategory goodsCategory = goodsCategoryService.selectById(one.getDeptGoodsCategoryId());
            one.setDeptGoodsCategoryName(goodsCategory.getGoodsCategoryName());
            if (goodsCategory.getParentCategoryId() != null) {
                GoodsCategory parGoodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
                one.setParGoodsCategoryId(parGoodsCategory.getGoodsCategoryId());
                one.setParGoodsCategoryName(parGoodsCategory.getGoodsCategoryName());
            }
            logger.debug("验证坐标是否合理: {}", LocationUtils.isValidCoordinate(userLatitude, userLongitude));
            // 计算距离逻辑
            if (LocationUtils.isValidCoordinate(userLatitude, userLongitude) && one.getShopId() != null) {
                try {
                    // 从缓存获取店铺信息，避免重复查询
                    Shop shop = shopCache.computeIfAbsent(one.getShopId(), 
                        shopId -> shopService.getShop(shopId));
                    
                    if (shop != null && LocationUtils.isValidCoordinate(shop.getLatitude(), shop.getLongitude())) {
                        // 计算距离（米）
                        double distanceInMeters = LocationUtils.getDistanceInMeters(
                            userLatitude, userLongitude,
                            shop.getLatitude(), shop.getLongitude()
                        );
                        
                        // 格式化距离并设置到商品对象
                        one.setDistance(LocationUtils.formatDistance(distanceInMeters));
                        
                        logger.debug("商品[{}]距离用户: {}", one.getGoodsName(), one.getDistance());
                    } else {
                        // 店铺坐标不完整
                        one.setDistance(null);
                    }
                } catch (Exception e) {
                    logger.warn("计算商品[{}]距离失败: {}", one.getGoodsName(), e.getMessage());
                    // 计算异常时设为null
                    one.setDistance(null);
                }
            } else {
                // 用户未提供位置或商品无店铺信息
                one.setDistance(null);
            }
        });
        
        // 如果用户提供了位置信息，按距离排序（距离为null的排在最后）
        if (LocationUtils.isValidCoordinate(userLatitude, userLongitude)) {
            list.sort((goods1, goods2) -> {
                String distance1 = goods1.getDistance();
                String distance2 = goods2.getDistance();
                
                // 距离为null的排在最后
                if (distance1 == null && distance2 == null) return 0;
                if (distance1 == null) return 1;
                if (distance2 == null) return -1;
                
                // 解析距离数值进行比较
                try {
                    double dist1 = parseDistanceToMeters(distance1);
                    double dist2 = parseDistanceToMeters(distance2);
                    return Double.compare(dist1, dist2);
                } catch (Exception e) {
                    // 解析失败时保持原顺序
                    return 0;
                }
            });
            
            logger.info("已按距离排序，用户位置: 纬度={}, 经度={}", userLatitude, userLongitude);
        }
        
        return getDataTable(list);
    }
    
    /**
     * 解析距离字符串为米数（用于排序）
     */
    private double parseDistanceToMeters(String distanceText) {
        if (distanceText == null || distanceText.trim().isEmpty()) {
            return Double.MAX_VALUE;
        }
        
        try {
            if (distanceText.endsWith("米")) {
                return Double.parseDouble(distanceText.replace("米", ""));
            } else if (distanceText.endsWith("公里")) {
                return Double.parseDouble(distanceText.replace("公里", "")) * 1000;
            }
        } catch (NumberFormatException e) {
            logger.warn("无法解析距离字符串: {}", distanceText);
        }
        
        return Double.MAX_VALUE;
    }

    @PostMapping("/hot/list")
    @ResponseBody
    public TableDataInfo hotList(@RequestBody Goods goods) {
        DeptGoodsCategory deptGoodsCategory = new DeptGoodsCategory();
        deptGoodsCategory.setDeptId(goods.getDeptId());
        deptGoodsCategory.setIsHot(1);
        deptGoodsCategory.setLevel(2);
        List<DeptGoodsCategory> categoryList = deptGoodsCategoryService.list(deptGoodsCategory);
        Collection<Long> ids = new ArrayList<>();
        categoryList.forEach(category -> {
            ids.add(category.getGoodsCategoryId());
        });

        startPage();
        List<Goods> list = goodsService.selectByCategoryIds(ids);
        list = list.stream().filter(x -> x.getStatus() == 0).collect(Collectors.toList());
        list.forEach(one -> {
            // 补全商品图片信息
            List<GoodsImgs> goodsImgs = goodsImgsService.selectByGoodsId(one.getGoodsId());
            Map<Integer, List<GoodsImgs>> listMap = new HashMap<>();
            for (GoodsImgs goodsImg : goodsImgs) {
                listMap.computeIfAbsent(goodsImg.getImgType(), k -> new ArrayList<>()).add(goodsImg);
            }
            one.setGoodsImgsMap(listMap);

            // 补全商品
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(one.getGoodsId());
            one.setGoodsAreaList(goodsAreas);

            // 补全商品类别
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(one.getGoodsId());
            one.setGoodsStandardList(goodsStandards);
        });
        return getDataTable(list);
    }

    @PostMapping("/addGoods")
    @ResponseBody
    public AjaxResult addGoods(@RequestBody Goods goods) {
        try {
            goodsService.addGoods(goods);
            return AjaxResult.success("新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    /**
     * 获取商品详情
     * 
     * @param requestBody 请求参数
     * @return 商品详情信息
     */
    @PostMapping("/getDetail")
    @ResponseBody
    public AjaxResult getDetail(@RequestBody JSONObject requestBody) {
        try {
            // 从请求体中提取参数
            Long goodsId = requestBody.getLong("goodsId");
            Double userLatitude = requestBody.getDouble("latitude");
            Double userLongitude = requestBody.getDouble("longitude");
            String provinceName = requestBody.getString("provinceName");
            String cityName = requestBody.getString("cityName");
            String countryName = requestBody.getString("countryName");
            String streetName = requestBody.getString("streetName");
            String address = requestBody.getString("address");
            
            if (goodsId == null) {
                return AjaxResult.error("商品ID不能为空");
            }
            
            Goods result = goodsService.selectById(goodsId);
            if (result == null) {
                return AjaxResult.error("商品不存在");
            }
            
            // 如果用户没有提供经纬度，但有详细地址，则通过地址获取经纬度
            if ((userLatitude == null || userLongitude == null) && 
                (provinceName != null || cityName != null || 
                 countryName != null || streetName != null || 
                 address != null)) {
                try {
                    // 使用BaiduMapUtils工具类获取经纬度
                    Map<String, Double> coordinates = baiduMapUtils.getCoordinatesByAddress(
                        provinceName, cityName, countryName, streetName, address
                    );
                    
                    if (coordinates != null) {
                        userLongitude = coordinates.get("longitude");
                        userLatitude = coordinates.get("latitude");
                        logger.info("通过地址获取到用户经纬度: 经度={}, 纬度={}", userLongitude, userLatitude);
                    } else {
                        logger.warn("通过地址获取用户经纬度失败");
                    }
                } catch (Exception e) {
                    logger.error("调用百度地图API异常: {}", e.getMessage(), e);
                }
            }
            
            // 获取商品店铺信息
            Shop goodsShop = null;
            if (result.getShopId() != null) {
                try {
                    goodsShop = shopService.getShop(result.getShopId());
                } catch (Exception e) {
                    logger.warn("获取商品店铺信息失败: {}", e.getMessage());
                }
            }
            
            // 获取服务店铺信息
            Shop serviceShop = null;

            if (result.getDeptGoodsCategoryId() != null) {
                try {
                    // 1. 通过商品的类目ID获取类目信息
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(result.getDeptGoodsCategoryId());
                    Long serviceCategoryId = null;
                    
                    if (deptGoodsCategory != null) {
                        // 先检查当前类目是否有服务类目ID
                        if (deptGoodsCategory.getServiceCategoryId() != null) {
                            serviceCategoryId = deptGoodsCategory.getServiceCategoryId();
                            logger.debug("当前类目[{}]的服务类目ID: {}", deptGoodsCategory.getGoodsCategoryName(), serviceCategoryId);
                        } else {
                            // 如果当前类目没有服务类目ID，查找上一级类目
                            logger.debug("当前类目[{}]未配置服务类目ID，查找上一级类目", deptGoodsCategory.getGoodsCategoryName());
                            
                            if (deptGoodsCategory.getParentCategoryId() != null) {
                                DeptGoodsCategory parentCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(deptGoodsCategory.getParentCategoryId());
                                if (parentCategory != null && parentCategory.getServiceCategoryId() != null) {
                                    serviceCategoryId = parentCategory.getServiceCategoryId();
                                    logger.debug("上一级类目[{}]的服务类目ID: {}", parentCategory.getGoodsCategoryName(), serviceCategoryId);
                                } else {
                                    logger.debug("上一级类目[{}]也未配置服务类目ID", parentCategory != null ? parentCategory.getGoodsCategoryName() : "null");
                                }
                            } else {
                                logger.debug("当前类目没有父级类目");
                            }
                        }
                    }
                    
                    if (serviceCategoryId != null) {
                        // 2. 通过服务类目ID查询所有使用该服务类目的商品
                        Goods queryGoods = new Goods();
                        queryGoods.setDeptGoodsCategoryId(serviceCategoryId);
                        queryGoods.setStatus(0); // 只查询上架的商品
                        List<Goods> goodsList = goodsService.selectGoodsList(queryGoods);
                        if (goodsList.size()==0){
                            DeptGoodsCategory deptGoodsCategory1=deptGoodsCategoryService.selectOneByGoodsCategoryId(serviceCategoryId);
                            serviceCategoryId=deptGoodsCategory1.getDeptGoodsCategoryId();
                            // 直接使用新方法获取商品列表
                            goodsList = goodsStandardService.selectGoodsByDeptGoodsCategoryId(serviceCategoryId);
                            // 过滤只保留上架的商品
                            goodsList = goodsList.stream()
                                .filter(goods -> goods.getStatus() != null && goods.getStatus() == 0)
                                .collect(Collectors.toList());
                        }
                        logger.info("获取到的服务类目id{} 取到的商品列表：{}", serviceCategoryId,goodsList);
                        // 3. 提取所有店铺ID（去重）
                        Set<Long> shopIds = goodsList.stream()
                            .filter(g -> g.getShopId() != null)
                            .map(Goods::getShopId)
                            .collect(Collectors.toSet());
                        logger.info("取到的店铺列表：{}", shopIds);
                        if (!shopIds.isEmpty()) {
                            // 找到最近的店铺
                            Shop nearestShop = null;
                            double minDistance = Double.MAX_VALUE;
                            
                            for (Long shopId : shopIds) {
                                Shop shop = shopService.getShop(shopId);
                                if (shop != null && LocationUtils.isValidCoordinate(shop.getLatitude(), shop.getLongitude())) {
                                    if (LocationUtils.isValidCoordinate(userLatitude, userLongitude)) {
                                        try {
                                            double distanceInMeters = LocationUtils.getDistanceInMeters(
                                                userLatitude, userLongitude,
                                                shop.getLatitude(), shop.getLongitude()
                                            );
                                            if (distanceInMeters < minDistance) {
                                                minDistance = distanceInMeters;
                                                nearestShop = shop;
                                            }
                                        } catch (Exception e) {
                                            logger.warn("计算店铺[{}]距离失败: {}", shop.getShopName(), e.getMessage());
                                        }
                                    } else {
                                        // 如果用户没有提供位置，选择第一个有效店铺
                                        if (nearestShop == null) {
                                            nearestShop = shop;
                                        }
                                    }
                                }
                            }
                            
                            serviceShop = nearestShop;
                        } else {
                            logger.debug("服务类目[{}]下没有找到商品", serviceCategoryId);
                        }
                    } else {
                        logger.debug("未找到有效的服务类目ID");
                    }
                } catch (Exception e) {
                    logger.warn("获取服务店铺信息失败: {}", e.getMessage());
                }
            }
            
            // 设置商品店铺和服务店铺信息
            if(result.getType()==1){
                serviceShop=goodsShop;
                result.setServiceShop(serviceShop);
            }else {
                result.setShop(goodsShop);
            }
            // 计算距离逻辑
            if (LocationUtils.isValidCoordinate(userLatitude, userLongitude)) {
                // 计算服务店铺距离
                if (serviceShop != null) {
                    try {
                        if (LocationUtils.isValidCoordinate(serviceShop.getLatitude(), serviceShop.getLongitude())) {
                            // 计算距离（米）
                            double distanceInMeters = LocationUtils.getDistanceInMeters(
                                userLatitude, userLongitude,
                                serviceShop.getLatitude(), serviceShop.getLongitude()
                            );
                            
                            // 格式化距离并设置到服务店铺对象
                            serviceShop.setDistance(LocationUtils.formatDistance(distanceInMeters));
                            
                            logger.debug("商品[{}]服务店铺距离用户: {}", result.getGoodsName(), serviceShop.getDistance());
                        } else {
                            // 店铺坐标不完整
                            serviceShop.setDistance(null);
                        }
                    } catch (Exception e) {
                        logger.warn("计算商品[{}]服务店铺距离失败: {}", result.getGoodsName(), e.getMessage());
                        // 计算异常时设为null
                        serviceShop.setDistance(null);
                    }
                }
                
                // 计算商品店铺距离
                if (goodsShop != null) {
                    try {
                        if (LocationUtils.isValidCoordinate(goodsShop.getLatitude(), goodsShop.getLongitude())) {
                            // 计算距离（米）
                            double distanceInMeters = LocationUtils.getDistanceInMeters(
                                userLatitude, userLongitude,
                                goodsShop.getLatitude(), goodsShop.getLongitude()
                            );
                            
                            // 格式化距离并设置到商品店铺对象
                            goodsShop.setDistance(LocationUtils.formatDistance(distanceInMeters));
                            
                            logger.debug("商品[{}]商品店铺距离用户: {}", result.getGoodsName(), goodsShop.getDistance());
                        } else {
                            // 店铺坐标不完整
                            goodsShop.setDistance(null);
                        }
                    } catch (Exception e) {
                        logger.warn("计算商品[{}]商品店铺距离失败: {}", result.getGoodsName(), e.getMessage());
                        // 计算异常时设为null
                        goodsShop.setDistance(null);
                    }
                }
            }
            result.setServiceShop(serviceShop);

            // 补全商品类目及父级类目信息
            GoodsCategory goodsCategory = goodsCategoryService.selectById(result.getDeptGoodsCategoryId());
            result.setDeptGoodsCategoryName(goodsCategory.getGoodsCategoryName());
            if (goodsCategory.getParentCategoryId() != null) {
                GoodsCategory parGoodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
                result.setParGoodsCategoryId(parGoodsCategory.getGoodsCategoryId());
                result.setParGoodsCategoryName(parGoodsCategory.getGoodsCategoryName());
            }

            // 补全商品图片信息
            List<GoodsImgs> goodsImgs = goodsImgsService.selectByGoodsId(result.getGoodsId());
            Map<Integer, List<GoodsImgs>> listMap = new HashMap<>();
            for (GoodsImgs goodsImg : goodsImgs) {
                listMap.computeIfAbsent(goodsImg.getImgType(), k -> new ArrayList<>()).add(goodsImg);
            }
            result.setGoodsImgsMap(listMap);

            // 补全商品区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(result.getGoodsId());
            result.setGoodsAreaList(goodsAreas);

            // 补全商品类别
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(result.getGoodsId());
            goodsStandards.stream().forEach(goodsStandard -> {
                if (StringUtils.isEmpty(goodsStandard.getGoodsUnit())) {
                    goodsStandard.setGoodsUnit(result.getGoodsUnit());
                }
                BigDecimal finalPrice = BigDecimal.ZERO;
                // 获取规格的扣点
                DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
                if(deptGoodsCategory.getOneRate() != null){
                    finalPrice = finalPrice.add(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getOneRate())).multiply(goodsStandard.getGoodsPrice()));
                }
                if(deptGoodsCategory.getTwoRate() != null){
                    finalPrice = finalPrice.add(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getTwoRate())).multiply(goodsStandard.getGoodsPrice()));
                }
                if(deptGoodsCategory.getThreeRate() != null){
                    finalPrice = finalPrice.add(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getThreeRate())).multiply(goodsStandard.getGoodsPrice()));
                }
                if(goodsStandard.getExtMoney() != null){
                    finalPrice = finalPrice.add(goodsStandard.getExtMoney());
                }
                goodsStandard.setFinalPrice(finalPrice);
            });
            result.setGoodsStandardList(goodsStandards);
            // 所有保险信息
            List<InsuranceManager> insuranceManagers = insuranceManagerService.selectInsuranceManagerList(new InsuranceManager());
            // 查询本类目保险信息
            DeptCategoryInsuranceRelation param = new DeptCategoryInsuranceRelation();
            param.setType("01");
            param.setDeptCategoryId(goodsStandards.get(0).getDeptGoodsCategoryId());
            List<DeptCategoryInsuranceRelation> deptCategoryInsuranceRelations = deptCategoryInsuranceRelationService.selectDeptCategoryInsuranceRelationList(param);
            if(CollectionUtils.isNotEmpty(deptCategoryInsuranceRelations)){
                Map<Long, List<DeptCategoryInsuranceRelation>> insuranceMap = deptCategoryInsuranceRelations.stream().collect(Collectors.groupingBy(DeptCategoryInsuranceRelation::getInsuranceId));
                // 目标保险
                List<InsuranceManager> goal = new ArrayList<>();
                insuranceManagers.forEach(model->{
                    if(insuranceMap.containsKey(model.getId())){
                        goal.add(model);
                    }
                });
                result.setInsuranceManagers(goal);
            }
            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    /**
     * 根据商品ID和用户位置获取服务店铺列表
     * @return 服务店铺列表，按距离排序
     */
    @PostMapping("/getShopsByGoodsId")
    @ResponseBody
    public AjaxResult getShopsByGoodsId(@RequestBody JSONObject requestBody) {
        try {
            Long goodsId = requestBody.getLong("goodsId");
            Double latitude = requestBody.getDouble("latitude");
            Double longitude = requestBody.getDouble("longitude");
            String provinceName = requestBody.getString("provinceName");
            String cityName = requestBody.getString("cityName");
            String countryName = requestBody.getString("countryName");
            String streetName = requestBody.getString("streetName");
            String address = requestBody.getString("address");
            
            if (goodsId == null) {
                return AjaxResult.error("商品ID不能为空");
            }
            
            // 如果用户没有提供经纬度，但有详细地址，则通过地址获取经纬度
            if ((latitude == null || longitude == null) && 
                (provinceName != null || cityName != null || countryName != null || 
                 streetName != null || address != null)) {
                try {
                    // 使用BaiduMapUtils工具类获取经纬度
                    Map<String, Double> coordinates = baiduMapUtils.getCoordinatesByAddress(
                        provinceName, cityName, countryName, streetName, address
                    );
                    
                    if (coordinates != null) {
                        longitude = coordinates.get("longitude");
                        latitude = coordinates.get("latitude");
                        logger.info("通过地址获取到用户经纬度: 经度={}, 纬度={}", longitude, latitude);
                    } else {
                        logger.warn("通过地址获取用户经纬度失败");
                    }
                } catch (Exception e) {
                    logger.error("调用百度地图API异常: {}", e.getMessage(), e);
                }
            }
            
            // 获取商品信息
            Goods goods = goodsService.selectById(goodsId);
            if (goods == null) {
                return AjaxResult.error("商品不存在");
            }
            
            List<Shop> serviceShops = new ArrayList<>();
            
            // 通过商品的服务类目获取服务店铺
            if (goods.getDeptGoodsCategoryId() != null) {
                try {
                    // 1. 通过商品的类目ID获取类目信息
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
                    Long serviceCategoryId = null;
                    
                    if (deptGoodsCategory != null) {
                        // 先检查当前类目是否有服务类目ID
                        if (deptGoodsCategory.getServiceCategoryId() != null) {
                            serviceCategoryId = deptGoodsCategory.getServiceCategoryId();
                            logger.debug("当前类目[{}]的服务类目ID: {}", deptGoodsCategory.getGoodsCategoryName(), serviceCategoryId);
                        } else {
                            // 如果当前类目没有服务类目ID，查找上一级类目
                            logger.debug("当前类目[{}]未配置服务类目ID，查找上一级类目", deptGoodsCategory.getGoodsCategoryName());
                            
                            if (deptGoodsCategory.getParentCategoryId() != null) {
                                DeptGoodsCategory parentCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(deptGoodsCategory.getParentCategoryId());
                                if (parentCategory != null && parentCategory.getServiceCategoryId() != null) {
                                    serviceCategoryId = parentCategory.getServiceCategoryId();
                                    logger.debug("上一级类目[{}]的服务类目ID: {}", parentCategory.getGoodsCategoryName(), serviceCategoryId);
                                } else {
                                    logger.debug("上一级类目[{}]也未配置服务类目ID", parentCategory != null ? parentCategory.getGoodsCategoryName() : "null");
                                }
                            } else {
                                logger.debug("当前类目没有父级类目");
                            }
                        }
                    }
                    
                    List<Goods> goodsList = new ArrayList<>();
                    if (serviceCategoryId != null) {
                        // 2. 通过服务类目ID查询所有使用该服务类目的商品
                        Goods queryGoods = new Goods();
                        queryGoods.setDeptGoodsCategoryId(serviceCategoryId);
                        queryGoods.setStatus(0); // 只查询上架的商品
                        goodsList = goodsService.selectGoodsList(queryGoods);
                        if (goodsList.size() == 0) {
                            DeptGoodsCategory deptGoodsCategory1 = deptGoodsCategoryService.selectOneByGoodsCategoryId(serviceCategoryId);
                            serviceCategoryId = deptGoodsCategory1.getDeptGoodsCategoryId();
                            // 直接使用新方法获取商品列表
                            goodsList = goodsStandardService.selectGoodsByDeptGoodsCategoryId(serviceCategoryId);
                            // 过滤只保留上架的商品
                            goodsList = goodsList.stream()
                                .filter(g -> g.getStatus() != null && g.getStatus() == 0)
                                .collect(Collectors.toList());
                        }
                        logger.info("获取到的服务类目id{} 取到的商品列表：{}", serviceCategoryId, goodsList);
                    }
                    
                    if (!goodsList.isEmpty()) {
                        logger.debug("通过商品ID[{}]找到{}个相关服务商品", goodsId, goodsList.size());
                        
                        // 提取所有店铺ID（去重）
                        Set<Long> shopIds = goodsList.stream()
                            .filter(g -> g.getShopId() != null)
                            .map(Goods::getShopId)
                            .collect(Collectors.toSet());
                        
                        if (!shopIds.isEmpty()) {
                            // 获取所有店铺信息并计算距离
                            for (Long shopId : shopIds) {
                                Shop shop = shopService.getShop(shopId);
                                if (shop != null) {
                                    // 计算距离
                                    if (LocationUtils.isValidCoordinate(latitude, longitude) && 
                                        LocationUtils.isValidCoordinate(shop.getLatitude(), shop.getLongitude())) {
                                        try {
                                            double distanceInMeters = LocationUtils.getDistanceInMeters(
                                                latitude, longitude,
                                                shop.getLatitude(), shop.getLongitude()
                                            );
                                            shop.setDistance(LocationUtils.formatDistance(distanceInMeters));
                                        } catch (Exception e) {
                                            logger.warn("计算店铺[{}]距离失败: {}", shop.getShopName(), e.getMessage());
                                            shop.setDistance(null);
                                        }
                                    } else {
                                        shop.setDistance(null);
                                    }
                                    serviceShops.add(shop);
                                }
                            }
                            
                            // 按距离排序（有距离的排在前面，然后按距离升序）
                            serviceShops.sort((s1, s2) -> {
                                if (s1.getDistance() == null && s2.getDistance() == null) {
                                    return 0;
                                }
                                if (s1.getDistance() == null) {
                                    return 1;
                                }
                                if (s2.getDistance() == null) {
                                    return -1;
                                }
                                // 提取距离数值进行比较
                                try {
                                    double d1 = Double.parseDouble(s1.getDistance().replaceAll("[^0-9.]", ""));
                                    double d2 = Double.parseDouble(s2.getDistance().replaceAll("[^0-9.]", ""));
                                    return Double.compare(d1, d2);
                                } catch (Exception e) {
                                    return 0;
                                }
                            });
                        }
                    } else {
                        logger.debug("未找到商品ID[{}]的相关服务商品", goodsId);
                    }
                } catch (Exception e) {
                    logger.warn("获取服务店铺信息失败: {}", e.getMessage());
                }
            }
            
            JSONObject result = new JSONObject();
            result.put("goodsId", goodsId);
            result.put("goodsName", goods.getGoodsName());
            result.put("userLatitude", latitude);
            result.put("userLongitude", longitude);
            result.put("serviceShops", serviceShops);
            result.put("totalCount", serviceShops.size());
            
            return AjaxResult.success(result);
            
        } catch (Exception e) {
            logger.error("获取服务店铺列表失败: {}", e.getMessage(), e);
            return AjaxResult.error("获取服务店铺列表失败: " + ExceptionUtil.getExceptionMessage(e));
        }
    }

    @Log(title = "商品管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("goods:goods:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Goods goods) {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        return util.exportExcel(list, "商品数据");
    }

    @RequiresPermissions("goods:goods:remove")
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{ids}")
    @ResponseBody
    public AjaxResult remove(@PathVariable String ids) {
        try {
            return toAjax(goodsService.deleteGoodsByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 新增商品
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        Long parentId = ShiroUtils.getSysUser().getParentId();
        DeptGoodsCategory category = new DeptGoodsCategory();
        category.setDeptId(parentId);
        mmap.put("deptGoodsCategories", deptGoodsCategoryService.list(category));
        return PREFIX + "/add";
    }

    /**
     * 新增保存商品
     */
    @RequiresPermissions("goods:goods:add")
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated Goods goods) {
        goods.setCreateBy(getLoginName());
        goods.setDeptId(getSysUser().getDeptId());
        return toAjax(goodsService.insertGoods(goods));
    }

    /**
     * 修改商品
     */
    @RequiresPermissions("goods:goods:edit")
    @GetMapping("/edit/{goodsId}")
    public String edit(@PathVariable("goodsId") Long goodsId, ModelMap mmap) {
        Long parentId = ShiroUtils.getSysUser().getParentId();
        DeptGoodsCategory category = new DeptGoodsCategory();
        category.setDeptId(parentId);
        mmap.put("deptGoodsCategories", deptGoodsCategoryService.list(category));
        mmap.put("goods", goodsService.selectById(goodsId));
        return PREFIX + "/edit";
    }

    /**
     * 修改保存商品
     */
    @RequiresPermissions("goods:goods:edit")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated Goods goods) {
        goods.setUpdateBy(getLoginName());
        
        // 处理Long类型字段的空值情况
        // 当前端传入0或空字符串时，将shopId设置为null以便清空
        if (goods.getShopId() != null && goods.getShopId().equals(0L)) {
            goods.setShopId(null);
        }
        
        return toAjax(goodsService.updateGoods(goods));
    }

    @PostMapping("/app/edit")
    @ResponseBody
    public AjaxResult appEditSave(@RequestBody @Validated Goods goods) {
        
        // 处理Long类型字段的空值情况
        // 当前端传入0或空字符串时，将shopId设置为null以便清空
        if (goods.getShopId() != null && goods.getShopId().equals(0L)) {
            goods.setShopId(null);
        }
        
        goodsService.edit(goods);
        return AjaxResult.success();
    }

    /**
     * 校验商品名称
     */
    @PostMapping("/checkGoodsNameUnique")
    @ResponseBody
    public String checkGoodsNameUnique(Goods goods) {
        return goodsService.checkGoodsNameUnique(goods);
    }

    /**
     * 校验商品编码
     */
    @PostMapping("/checkGoodsCodeUnique")
    @ResponseBody
    public String checkGoodsCodeUnique(Goods goods) {
        return goodsService.checkGoodsCodeUnique(goods);
    }

    /**
     * 修改商品状态
     *
     * @param goodsId 商品ID
     * @param status  0=上架,1=下架,2删除
     */
    @PostMapping("/status")
    @ResponseBody
    public AjaxResult status(Long goodsId, Integer status) {
        try {
            Goods goods = new Goods();
            goods.setGoodsId(goodsId);
            goods.setStatus(status);
            goodsService.updateGoods(goods);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    /**
     * 修改商品状态
     */
    @PostMapping("/app/updateStatus")
    @ResponseBody
    public AjaxResult status(@RequestBody Goods goods) {
        try {
            goodsService.updateGoods(goods);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }


}
