package com.jd.lightapplication.utils;


import cn.hutool.core.util.StrUtil;
import com.jd.lightapplication.common.exception.CaptchaException;
import com.jd.lightapplication.model.ConfigInfo;
import com.jd.lightapplication.service.ConfigInfoService;
import lombok.AllArgsConstructor;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class ValidateLoginAreaUtil {

    private RedisTemplate redisTemplate;
    private ConfigInfoService configInfoService;

    /**
     * 判断经坐标是否符合登录条件，这里使用Redis特殊数据类型来做
     *
     * @param longitude 经度
     * @param latitude  纬度
     */
    public void checkCoordinate(Double longitude, Double latitude) {
        //先获取系统配置里面的登录区域是否开启
        ConfigInfo configInfo = configInfoService.findByKey("LOGIN_AREA_ISENABLE");
        if (configInfo != null && "false".equals(configInfo.getConfigValue())) {
            //未开启直接放行
            return;
        }
        //查询经度、纬度、距离配置
        String lgt = configInfoService.findByKey("LOGIN_AREA_LONGITUDE").getConfigValue(),
                lat = configInfoService.findByKey("LOGIN_AREA_LATITUDE").getConfigValue(),
                range = configInfoService.findByKey("LOGIN_AREA_RANGE").getConfigValue();
        if (StrUtil.isBlank(lgt) || StrUtil.isBlank(lat) || StrUtil.isBlank(range)) {
            throw new CaptchaException("系统配置异常，请联系管理员。");
        }
        Double lgtDouble;
        Double latDouble;
        Double rangeDouble;
        try {
            lgtDouble = Double.parseDouble(lgt);
            latDouble = Double.parseDouble(lat);
            rangeDouble = Double.parseDouble(range);
        } catch (Exception e) {
            throw new CaptchaException("系统配置异常，请联系管理员。");
        }
        //判断坐标是否符合登录要求
        redisTemplate.opsForGeo().add("geo", new Point(lgtDouble, latDouble), "basic");
        redisTemplate.opsForGeo().add("geo", new Point(longitude, latitude), "user");

        Distance rangeDistance = redisTemplate.opsForGeo().distance("geo", "basic", "user", RedisGeoCommands.DistanceUnit.METERS);
        if (rangeDistance.getValue() >= rangeDouble) {
            throw new CaptchaException("请在城管局范围内使用小程序");
        }

    }
}
