
package com.tmerclub.cloud.flow.util;

import cn.hutool.core.io.IoUtil;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.util.IpHelper;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;

/**
 * 流量统计计算工具类
 *
 * @author YXF
 */
public class IpSearchUtil {

    private static final Logger LOG = LoggerFactory.getLogger(IpSearchUtil.class);

    private static Searcher searcher;

    static {
        // 获取ip库路径
        ClassPathResource classPathResource = new ClassPathResource("ip2region.xdb");
        if (classPathResource.getClassLoader() == null){
            LOG.error("ip2region.xdb 存储路径发生错误，没有被发现");
            searcher =  null;
        }
        InputStream inputStream = null;
        try {
            inputStream = classPathResource.getInputStream();
        } catch (IOException e) {
            throw new LuckException(e.getMessage());
        }
        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff = IoUtil.readBytes(inputStream);

        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        Searcher searcherNew = null;
        try {
            searcherNew = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            System.out.printf("failed to create content cached searcher: %s\n", e);
        }
        searcher = searcherNew;
    }





    public static Long getProvinceIdByUserIp(Long ipNum, Map<String, Long> areaMap) {
        if (Objects.isNull(ipNum) || ipNum == 0L) {
            return 0L;
        }

        String province = "";
        // 根据IP搜索地址信息
        try {
            String ip = IpHelper.longToIp(ipNum);
            String region = searcher.search(ip);
            province = region.split("\\|")[2];
        } catch (Exception e) {
            LOG.info("ip查询异常： {}",  e.toString());
            return 0L;
        }
        if (areaMap.containsKey(province)) {
            return areaMap.get(province);
        }
        LOG.info("ip地区名称与数据库省名称不匹配： {}",  province);
        return 0L;
    }

}
