package cn.pluss.platform.ipLocation.impl;

import cn.pluss.platform.converter.Converter;
import cn.pluss.platform.entity.IpLocationCache;
import cn.pluss.platform.ipLocation.IpLocationCacheService;
import cn.pluss.platform.ipLocation.IpLocationService;
import com.aliyuncs.geoip.model.v20200101.DescribeIpv4LocationResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;

/**
 * ip138的接口
 */
@Service("ipLocationService")
@Slf4j
public class IpLocationServiceImpl implements IpLocationService {

    @Value("${ip138.url}")
    private String IP138_URL;

    @Value("${ip138.token}")
    private String IP138_TOKEN;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IpLocationCacheService ilcService;

    @Override
    public DescribeIpv4LocationResponse getLocation(String ip) {
        // 先从缓存里面获取
        IpLocationCache ipLocationCache = new IpLocationCache();
        ipLocationCache.setIp(ip);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, -2);
        ipLocationCache.setCreateTimeStart(calendar.getTime());
        LambdaQueryWrapper<IpLocationCache> qWrapper = Wrappers.lambdaQuery(ipLocationCache);
        qWrapper.orderByDesc(IpLocationCache::getCreateTime);
        qWrapper.last("limit 1");
        IpLocationCache one = ilcService.getOne(qWrapper);
        if (one != null) {
            DescribeIpv4LocationResponse response = new DescribeIpv4LocationResponse();
            response.setIp(ip);
            response.setCountry(one.getCountry());
            response.setProvince(one.getProvince());
            response.setCity(one.getCity());
            response.setCounty(one.getCounty());
            response.setIsp(one.getIsp());
            return response;
        }

        Map reqResult;
        try {
            reqResult = restTemplate.getForObject(IP138_URL + "?ip=" + ip + "&token=" + IP138_TOKEN, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("IP138接口异常");
            return null;
        }

        if (reqResult == null) {
            log.error("IP138接口数据异常");
            DescribeIpv4LocationResponse result = new DescribeIpv4LocationResponse();
            result.setIp(ip);

            return null;
        }

        if (!"ok".equals(reqResult.get("ret"))) {
            log.error(reqResult.get("msg").toString());

            DescribeIpv4LocationResponse result = new DescribeIpv4LocationResponse();
            result.setIp(ip);
            return result;
        }

        ArrayList<String> data = (ArrayList<String>) reqResult.get("data");

        DescribeIpv4LocationResponse response = new DescribeIpv4LocationResponse();
        response.setIp(ip);
        response.setCountry(data.get(0));
        response.setProvince(data.get(1));
        response.setCity(data.get(2));
        response.setCounty(data.get(3));
        response.setIsp(data.get(4));

        IpLocationCache cache = new IpLocationCache();
        Converter.INSTANCE.cp(response, cache);
        ilcService.save(cache);

        return response;
    }
}
