package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.shop.mapper.ShopStoreFenceMapper;
import com.gxwebsoft.shop.service.ShopStoreFenceService;
import com.gxwebsoft.shop.entity.ShopStoreFence;
import com.gxwebsoft.shop.param.ShopStoreFenceParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.util.GeoFenceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 黄家明_电子围栏Service实现
 *
 * @author 科技小王子
 * @since 2026-02-07 18:10:25
 */
@Service
public class ShopStoreFenceServiceImpl extends ServiceImpl<ShopStoreFenceMapper, ShopStoreFence> implements ShopStoreFenceService {
    private static final Logger log = LoggerFactory.getLogger(ShopStoreFenceServiceImpl.class);

    @Override
    public PageResult<ShopStoreFence> pageRel(ShopStoreFenceParam param) {
        PageParam<ShopStoreFence, ShopStoreFenceParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<ShopStoreFence> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<ShopStoreFence> listRel(ShopStoreFenceParam param) {
        List<ShopStoreFence> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<ShopStoreFence, ShopStoreFenceParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public ShopStoreFence getByIdRel(Integer id) {
        ShopStoreFenceParam param = new ShopStoreFenceParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public boolean hasEnabledFences(Integer tenantId) {
        if (tenantId == null) {
            return false;
        }
        return this.count(new LambdaQueryWrapper<ShopStoreFence>()
                .eq(ShopStoreFence::getTenantId, tenantId)
                .eq(ShopStoreFence::getStatus, 0)) > 0;
    }

    @Override
    public void validatePointInEnabledFences(Integer tenantId, double lng, double lat) {
        if (tenantId == null) {
            // tenantId 缺失时不做围栏校验，避免误伤；上层应保证 tenantId 正确传入
            return;
        }

        List<ShopStoreFence> fences = this.list(new LambdaQueryWrapper<ShopStoreFence>()
                .eq(ShopStoreFence::getTenantId, tenantId)
                .eq(ShopStoreFence::getStatus, 0)
                .orderByAsc(ShopStoreFence::getSortNumber)
                .orderByDesc(ShopStoreFence::getCreateTime));

        // 无围栏配置：默认放行
        if (fences == null || fences.isEmpty()) {
            return;
        }

        for (ShopStoreFence fence : fences) {
            if (fence == null) {
                continue;
            }
            List<GeoFenceUtil.Point> polygon;
            try {
                polygon = GeoFenceUtil.parsePolygonPoints(fence.getPoints());
            } catch (Exception e) {
                // points 异常：直接拒单并记录日志，避免误送
                log.error("围栏 points 解析失败，tenantId={}, fenceId={}, points={}",
                        tenantId, fence.getId(), fence.getPoints(), e);
                throw new BusinessException("配送范围配置异常，请联系商家");
            }

            if (polygon == null || polygon.size() < 3) {
                log.error("围栏 points 点数不足，tenantId={}, fenceId={}, points={}",
                        tenantId, fence.getId(), fence.getPoints());
                throw new BusinessException("配送范围配置异常，请联系商家");
            }

            if (GeoFenceUtil.containsInclusive(polygon, lng, lat)) {
                return; // 命中任一围栏即通过
            }
        }

        throw new BusinessException("收货地址不在配送范围内");
    }

}
