<?php

namespace app\service;

class IpLocationService
{
    private $prefStart = [];
    private $prefEnd = [];
    private $endArr = [];
    private $fp;
    private $data;
    private static $instance = null;
    private $dataPath;

    private function __construct()
    {
        $this->dataPath = app()->getRootPath() . 'data/ipdatacloud.dat';
        $this->loadData();
    }

    private function loadData()
    {
        if (!file_exists($this->dataPath)) {
            throw new \Exception("IP数据文件不存在: {$this->dataPath}");
        }

        $this->fp = fopen($this->dataPath, 'rb');
        if (!$this->fp) {
            throw new \Exception("无法打开IP数据文件");
        }

        $fsize = filesize($this->dataPath);
        $this->data = fread($this->fp, $fsize);

        // 确保数据文件有足够的大小
        if (strlen($this->data) < 2052) {
            throw new \Exception("IP数据文件格式错误或损坏");
        }

        for ($k = 0; $k < 256; $k++) {
            $i = $k * 8 + 4;
            
            // 确保不会超出数据范围
            if ($i + 7 >= strlen($this->data)) {
                $this->prefStart[$k] = 0;
                $this->prefEnd[$k] = 0;
                continue;
            }
            
            $this->prefStart[$k] = $this->bytesToLong(
                $this->data[$i],
                $this->data[$i + 1],
                $this->data[$i + 2],
                $this->data[$i + 3]
            );
            $this->prefEnd[$k] = $this->bytesToLong(
                $this->data[$i + 4],
                $this->data[$i + 5],
                $this->data[$i + 6],
                $this->data[$i + 7]
            );
        }
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getLocationFormatted($ip)
    {
        $result = $this->getLocation($ip);
        
        if (!$result['status']) {
            return $result;
        }
        
        // 解析IP位置信息
        // 格式：亚洲|中国|广东|广州|荔湾|电信|440100|China|CN|113.2442|23.12592|18|510000|020|CHXX0037|AS4134
        $location = $result['data']['location'];
        $info = explode('|', $location);
        
        return [
            'status' => true,
            'message' => 'success',
            'data' => [
                'ip' => $ip,
                'continent' => isset($info[0]) ? $info[0] : '',
                'country' => isset($info[1]) ? $info[1] : '',
                'province' => isset($info[2]) ? $info[2] : '',
                'city' => isset($info[3]) ? $info[3] : '',
                'district' => isset($info[4]) ? $info[4] : '',
                'isp' => isset($info[5]) ? $info[5] : '',
                'area_code' => isset($info[6]) ? $info[6] : '',
                'country_en' => isset($info[7]) ? $info[7] : '',
                'country_code' => isset($info[8]) ? $info[8] : '',
                'longitude' => isset($info[9]) ? $info[9] : '',
                'latitude' => isset($info[10]) ? $info[10] : '',
                'altitude' => isset($info[11]) ? $info[11] : '',
                'zip_code' => isset($info[12]) ? $info[12] : '',
                'city_code' => isset($info[13]) ? $info[13] : '',
                'weather_station' => isset($info[14]) ? $info[14] : '',
                'asn' => isset($info[15]) ? $info[15] : ''
            ]
        ];
    }

    public function batchGetLocationFormatted(array $ips)
    {
        $results = [];
        foreach ($ips as $ip) {
            $results[$ip] = $this->getLocationFormatted($ip);
        }
        return $results;
    }

    public function getLocation($ip)
    {
        if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            return [
                'status' => false,
                'message' => '无效的IP地址格式',
                'data' => null
            ];
        }

        try {
            $val = sprintf("%u", ip2long($ip));
            $ipArr = explode('.', $ip);
            $pref = intval($ipArr[0]);
            
            // 确保前缀索引在有效范围内
            if (!isset($this->prefStart[$pref]) || !isset($this->prefEnd[$pref])) {
                return [
                    'status' => false,
                    'message' => '无IP信息',
                    'data' => null
                ];
            }
            
            $low = $this->prefStart[$pref];
            $high = $this->prefEnd[$pref];
            
            $cur = ($low == $high) ? $low : $this->search($low, $high, $val);
            
            if ($cur == 100000000) {
                return [
                    'status' => false,
                    'message' => '无IP信息',
                    'data' => null
                ];
            }
            
            $location = $this->getByCur($cur);
            
            return [
                'status' => true,
                'message' => 'success',
                'data' => [
                    'ip' => $ip,
                    'location' => $location
                ]
            ];
        } catch (\Exception $e) {
            return [
                'status' => false,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }

    public function batchGetLocation(array $ips)
    {
        $results = [];
        foreach ($ips as $ip) {
            $results[$ip] = $this->getLocation($ip);
        }
        return $results;
    }

    private function getByCur($i)
    {
        $p = intval(2052 + (intval($i) * 9));

        // 确保偏移量不超出数据范围
        if ($p + 8 >= strlen($this->data)) {
            return "无信息";
        }

        $offset = $this->bytesToLong(
            $this->data[4 + $p],
            $this->data[5 + $p],
            $this->data[6 + $p],
            $this->data[7 + $p]
        );
        $length = ord($this->data[8 + $p]);
        
        // 确保读取范围有效
        if ($offset + $length > strlen($this->data)) {
            return "无信息";
        }
        
        return substr($this->data, $offset, $length);
    }

    private function search($low, $high, $k)
    {
        $M = 0;
        while ($low <= $high) {
            $mid = intval(floor(($low + $high) / 2));
            $p = intval(2052 + ($mid * 9));

            // 确保偏移量不超出数据范围
            if ($p + 3 >= strlen($this->data)) {
                break;
            }

            $endipNum = $this->bytesToLong(
                $this->data[$p],
                $this->data[$p + 1],
                $this->data[$p + 2],
                $this->data[$p + 3]
            );
            
            if ($endipNum >= $k) {
                $M = $mid;
                if ($mid == 0) {
                    break;
                }
                $high = $mid - 1;
            } else {
                $low = $mid + 1;
            }
        }
        return $M;
    }

    private function bytesToLong($a, $b, $c, $d)
    {
        $iplong = (ord($a) << 0) | (ord($b) << 8) | (ord($c) << 16) | (ord($d) << 24);
        if ($iplong < 0) {
            $iplong += 4294967296;
        }
        return $iplong;
    }

    public function __destruct()
    {
        if ($this->fp !== null) {
            fclose($this->fp);
        }
    }
}