<?php 
namespace gaode\request;
use think\Exception;
use helper\URL;
class Geocode {
    private $_config=null;
    public $province='';
    public $city='';
    public $area='';
    public $address='';
    public $lng='';
    public $lat='';
    public function __construct($config)
    {
        $this->_config=$config;
        if (!$this->_config->key)
            throw new Exception('KEY不能为空');
    }
    public function geo()
    {
        if (!$this->address&&(!$this->province||!$this->city||!$this->area))
            throw new Exception('请设置省市区或结构化地址');
        $param=[
            'key'       => $this->_config->key,
            'address'   => $this->province.$this->city.$this->area.$this->address
        ];
        if ($this->city)
            $param['city']=$this->city;
        $ret=URL::get($this->_config->url.$this->_config->getGeocodeGeoUrl(),$param);
        if ($ret) {
            $retData=json_decode($ret);
            if ($retData) {
                if ($retData->status && $retData->infocode==10000) {
                    if (empty($retData->geocodes[0])) {
                        throw new Exception('无结果');
                    }else{
                        return $retData->geocodes[0];
                    }
                }else{
                    throw new Exception($retData->info.'['.$retData->infocode.']');
                }
            }
        }
        throw new Exception('请求失败');
    }
    public function regeo()
    {
        if (!$this->lng||!$this->lat)
            throw new Exception('经纬度不能为空');
        $param=[
            'key'       => $this->_config->key,
            'location'  => implode(',',[$this->lng,$this->lat])
        ];
        $ret=URL::get($this->_config->url.$this->_config->getGeocodeRegeoUrl(),$param);
        if ($ret) {
            $retData=json_decode($ret);
            if ($retData) {
                if ($retData->status && $retData->infocode==10000) {
                    if (empty($retData->regeocodes[0])) {
                        throw new Exception('无结果');
                    }else{
                        return $retData->regeocodes[0];
                    }
                }else{
                    throw new Exception($retData->info.'['.$retData->infocode.']');
                }
            }
        }
        throw new Exception('请求失败');
    }
}