package shop.alien.store.service.impl;

import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Service;
import shop.alien.store.config.BaseRedisService;
import shop.alien.store.service.NearMeService;
import shop.alien.store.util.FunctionMagic;
import shop.alien.util.common.constant.Constant;

import java.util.List;
import java.util.function.Consumer;

@Service
@RequiredArgsConstructor
public class NearMeServiceImpl implements NearMeService {

    private final BaseRedisService baseRedisService;

    /**
     * 添加地址位置
     *
     * @param point
     * @param content
     */
    @Override
    public void inGeolocation(Point point, String content, Boolean flag) {
        baseRedisService.inGeolocation(point, content, flag ? Constant.GEO_STORE_PRIMARY : Constant.GEO_STORE_NAME);
    }

    /**
     * 附近的商家
     *
     * @param lat
     * @param lon
     * @param distance
     * @return
     */
    @Override
    public List nearbyMerchants(Double lon, Double lat, Double distance, Boolean flag) {

        List nearbyArray = Lists.newArrayList();
        String type = flag ? Constant.GEO_STORE_PRIMARY : Constant.GEO_STORE_NAME;
        GeoResults<RedisGeoCommands.GeoLocation<String>> res = baseRedisService.radius(new Point(lon, lat), distance, Constant.LIMIT_COUNT, type);
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> contentArray = res.getContent();
        Consumer accept = FunctionMagic.createNearMeDtoConsumer(nearbyArray);
        FunctionMagic.processList(contentArray, accept);
        return nearbyArray;
    }

    /**
     * 删除GEO类型中的成员
     *
     * @param flag
     * @param content 要删除的成员名称
     * @return 实际删除的成员数量
     */
    @Override
    public Long removeGeolocation(Boolean flag, String content) {
        return baseRedisService.removeGeoMember(flag ? Constant.GEO_STORE_PRIMARY : Constant.GEO_STORE_NAME, content);
    }

}
