<?php
/**
 * 地理区域模型
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.com>
 */

namespace Common\Model;
use Think\Model;
class AreaModel extends Model{
    /**
     * 初始化地区信息
     * @return array
     */
    public function init(){
		$data=$this->area_site();
        $sess=session('member_info');
        $address_info = checkuseraddress();
        if($sess['id'] > 0 && empty($address_info)){
			$wh['uid']=$sess['id']; 
			$wh['status']=1;  
			$address_info=M('MemberAddress')->where($wh)->field('province,city,district')->find(); 
		}
        if(empty($address_info) && !is_weixin()){
			$iptype='taobao';//'UTFWry.dat';
            $IpLocation = new \Org\Net\IpLocation($iptype); // 实例化类 参数表示IP地址库文件			
            $ip = get_client_ip();
            $result = $IpLocation->getlocation($ip);
			if(str_exists($iptype,'.dat')){
                $map=array();$map['status']=1;
                $area_list=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();
				foreach($area_list as $k=>$v){
					if(strpos('a'.$result['country'] ,$v['name'])>0){
						$area=explode(',',$k);
						if(!empty($v['pid']))$address_info['province']=$v['pid'];
						if(!empty($v['id']))$address_info['city']=$v['id'];
						if(!empty($address_info))$address_info['district']=0;
					}
				}
			}else{
				$city=strlen($result['country'])>6?strtr($result['country'],array('省'=>'','市'=>'','县'=>'','区'=>'','自治区'=>'',)):$result['country'];
                $map=array();
                $map['status']=1;
                $map['name']=array('like','%'.$city.'%');
                $cityinfo=M('Area')->where($map)->field('id,pid,name')->cache(true)->find();
				if($cityinfo){
					if(!empty($cityinfo['pid']))$address_info['province']=$cityinfo['pid'];
					if(!empty($cityinfo['id']))$address_info['city']=$cityinfo['id'];
					if(!empty($address_info))$address_info['district']=0;
				}

			}
            if(!empty($address_info))checkuseraddress($address_info);
        }
		$map=$area_arr=array();
		if(!empty($address_info['province']))$area_arr[]=$address_info['province'];
		if(!empty($address_info['city']))$area_arr[]=$address_info['city'];
		if(!empty($address_info['district']))$area_arr[]=$address_info['district'];
		if($area_arr){
            $map=array();
            $map['status']=1;
            $map['name']=array('in',$area_arr);
            $area_info=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();
            
			if($area_info){
				foreach($area_info as $av){$area_infos[$av['id']]=$av;}
			}
			if(!empty($area_infos[$address_info['province']]))$return['address_info_format']['province'] =$area_infos[$address_info['province']];
			if(!empty($area_infos[$address_info['city']]))$return['address_info_format']['city'] =$area_infos[$address_info['city']];
			if(!empty($area_infos[$address_info['district']]))$return['address_info_format']['district'] =$area_infos[$address_info['district']];
		}
        $return['address_info'] = $address_info;
        return $return;
    }
    /**
     * 格式化地区信息
     * @param array $data 地区数据
     * @param int $type 格式化类型 1省级 0其他级
     * @return array
     */
    public function area_format($data,$type=0){
        $address_info = checkuseraddress();
        if($type<1)$data[0] = $data;
        foreach($data as $key=>$val){
            foreach($val as $k=>$v){
                if(in_array($v['i'],array_values($address_info))){
                    $data[$key][$k]['select'] = 1;
                }
            }
        }
        if($type<1)return $data[0];
        return $data;
    }
    /**
     * 改变地区信息
     * @param int $id 地区id
     * @param int $tabid 区域等级id 2省级 3市级 4区县级
     * @param str $parents 通用父级节点
     * @return array
     */
    public function change_areacache($id,$tabid,$parents){
        if(empty($id)||empty($tabid))return false;
        $data = get_arearegion_cache(0);$parents = trim($parents);
        $address_info = checkuseraddress();//获取定位信息
        $return['status'] = 1;
        if($data[$id]){
            $html = '<dl class="clearfix">';
            foreach($data[$id] as $k=>$v){
                $class = '';
                if(!is_numeric($k))continue;
                if(isset($address_info['city'])||isset($address_info['district'])){
                    if($address_info['city']==$v['i']||$address_info['district']==$v['i']){$class='class="on"';}
                }
                $html .= '<dd><a href="javascript:;" '.$class.' onclick="getarearegion(this,'.$v['i'].','.($tabid+1).','."'".$parents."'".')">'.$v['n'].'</a></dd>';
            }
            $html .= '</dl>';
            $return['data'] = $html;
        }
        if($tabid==2)$address_info['province'] = $id;
        if($tabid==3)$address_info['city'] = $id;
        if($tabid==4)$address_info['district'] = $id;
        checkuseraddress($address_info);
        return $return;
    }
    /**
     * 改变地区信息 mobile首页
     * @param int $id 地区id
     * @return array
     */
    public function change_mobile_index_areacache($id){
        if(empty($id))return false;
        $this->change_site($id);
        $province=idtoname($id,'Area','pid');
        if($province)$address_info['province'] = $province;
        $address_info['city'] = $id;
        checkuseraddress($address_info);
        $return['status'] = 1;
        return $return;
    }
    //切换城市分站
    public function change_site($id){
        if(!$id)return false;
        $site=idtoname($id,'Area','*');
        $siteinfo=session('siteinfo');
        $siteinfo['city']=$site['name'];
        $siteinfo['province']=$site['pid'];
        $siteinfo['city_id']=$id;
        $siteinfo['district']=0;
        session('siteinfo',$siteinfo);
    }
    /**
     * 改变地区信息 mobile
     * @param int $id 地区id
     * @param int $level 区域等级id 2省级 3市级 4区县级
     * @return array
     */
    public function change_areacache_mobile($id,$level){

        if(empty($id)||empty($level))return false;
        $html = '';
        $data = get_arearegion_cache(0);
        $address_info = checkuseraddress();//获取定位信息
        if($data[$id]){
            $return['status'] = 1;
            foreach($data[$id] as $k=>$v){
                if(!is_numeric($k))continue;
                $html.='<li onClick="intProvince(' . ($level+1) . ',' . $v['i'] . ');">' . $v['n'] . '</li>';
            }
        }
        $datanames = $this->now_area_names();
        $return['datanames'] = 0;
        if($datanames)$return['datanames'] = $datanames;
        $return['data'] = $html;
        if($level==2)$address_info['province'] = $id;
        if($level==3)$address_info['city'] = $id;
        if($level==4)$address_info['district'] = $id;
        checkuseraddress($address_info);
        return $return;
    }
    /**
     * 获取当前定位名称拼接 mobile
     * @return str
     */
    public function now_area_names(){
        $address_info = checkuseraddress();
        if(!isset($address_info))return false;
        $return['address_info'] = $address_info;
        $field = "name";
        if($address_info['province']){
            $strnames =idtoname($address_info['province'],'Area',$field);
        }
        if($address_info['city']){
            $strnames .= $result['cityname'] = idtoname($address_info['city'],'Area',$field);
        }
        if($address_info['district']){
            $strnames .=idtoname($address_info['province'],'district',$field);
        }
        $result['strnames'] = $strnames;
        return $result;
    }
	
	//new 加
	//
	//存储城市分站信息
	public function area_site(){		
		$siteinfo=session('siteinfo');
		if($siteinfo){return $siteinfo;}
		$iptype='taobao';//'UTFWry.dat';
		$IpLocation = new \Org\Net\IpLocation($iptype); // 实例化类 参数表示IP地址库文件		
        $ip = get_client_ip();
		$area_info = $IpLocation->getlocation($ip);
		$sitedata=array();

		if(str_exists($iptype,'.dat')){
            $map=array();$map['status']=1;
            $site_list=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();
			foreach ($site_list as $key => $value) {
				$site_list['name'] = $value['name'];
				$site_list['city_id'] = $value['id'];
				$site_list['province'] = $value['pid'];
				if($site_list['city_id'] == 130){
					$site_list['is_default'] = 1;
				}else{
					$site_list['is_default'] = 0;
				}
				if($site_list['level'] == 3){
					$site_list['district'] = $value['id'];
				}else{
					$site_list['district'] = 0;
				}
				
			}
			$default=array();
			foreach($site_list as $k=>$v){
				$name=strlen($v['name'])>6?strtr($v['name'],array('省'=>'','市'=>'','区'=>'','县'=>'','自治区'=>'')):$v['name'];
				if(str_exists($area_info['country'],$name)){
					$sitedata=$v;
	            }
	            if($v['is_default'])$default=$v;
			}
		}else{
			$city=strlen($area_info['country'])>6?strtr($area_info['country'],array('省'=>'','市'=>'','县'=>'','区'=>'','自治区'=>'',)):$area_info['country'];
            $map=array();$map['status']=1;
            $map['name']=array('like','%'.$city.'%');
            $siteinfo=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();

			$siteinfo['name'] = $siteinfo['name'];
			$siteinfo['city_id'] = $siteinfo['id'];
			$siteinfo['province'] = $siteinfo['pid'];
			if($siteinfo['level'] == 3){
				$siteinfo['district'] = $siteinfo['id'];
			}else{
				$siteinfo['district'] = 0;
			}

			if($siteinfo){
				$sitedata=$siteinfo;
			}else{
			 
                $map=array();$map['status']=1;
                $map['id']=130;
                $default=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();
				$default['name'] = $default['name'];
				$default['city_id'] = $default['id'];
				$default['province'] = $default['pid'];
				if($default['level'] == 3){
					$default['district'] = $default['id'];
				}else{
					$default['district'] = 0;
				}
			}
		}
		if(empty($sitedata))$sitedata=$default;
		$info=array();
		$info['site_id']=$sitedata['id'];
		$info['site_name']=$sitedata['name'];
		$info['province']=$sitedata['province'];
		$info['city_id']=$sitedata['city_id'];
		$info['district']=$sitedata['district'];
              
		$info['city']=idtoname($sitedata['city_id'],'Area','name');
		$info['district_name']=idtoname($sitedata['district'],'Area','name');
		session('siteinfo',$info);
		return $info;
	}
	//加载城市分站数据
	public function get_index_area_cache() {
		$return=array();
        $map=array();$map['status']=1;
        $allarea=M('Area')->where($map)->field('id,pid,name,letter')->cache(true)->select();
        $areainfo=$pidarea=$province_idsarr=array();
        foreach($allarea as $v){
            $pidarea[$v['pid']][]=$v;
            $areainfo[$v['id']]=$v;
            if($v['pid']==1)$province_idsarr[]=$v['id'];
        }
		$area_site=$province_ids=array();
		foreach($province_idsarr as $kk=>$vv){
			$province_ids[$kk]=$areainfo[$vv];
			$list=$pidarea[$vv];
			foreach($list as $kkk=>$vvv){
				$area_site[$vv][$vvv['id']]['i']=$vvv['id'];
				$area_site[$vv][$vvv['id']]['n']=$vvv['name'];
			}
		}
		$newarr = array();
	    foreach($province_ids as $v){
	        $v['letter']=$this->replaceBOM($v['letter']);
			$newarr['letter'][$v['letter']][$v['id']]['i'] = $v['id'];//带拼音省级分类
			$newarr['letter'][$v['letter']][$v['id']]['n'] = $v['name'];
		}
		$tree=$newarr['letter'];
        $city_tree = $area_site;
        ksort($tree);
		$return['json_city']=json_encode($city_tree);
		$return['json_provinces']=json_encode($tree);
        return $return;
	}
    private function replaceBOM($contents){
    	$charset[1]=substr($contents,0,1);
    	$charset[2]=substr($contents,1,1);
    	$charset[3]=substr($contents,2,1);
    	if(ord($charset[1])==239&&ord($charset[2])==187&&ord($charset[3])==191){
    		$rest=substr($contents,3);
    		return $rest;
    	}else{
    		return $contents;
    	}
    }
	/**
	 * geoCoding,坐标/地址转换
	 * @param  array  $params 请求参数
	 * @param  string $type   1,坐标转换地址 2,地址转换坐标
	 * @return array  $data   响应数据
	 */
	public function geocoding($param,$type=1){
		if(empty($param))return false;
		$ak=C('BAIDU_WEB_KEY');
		$url="http://api.map.baidu.com/reverse_geocoding/v3/";
	    if($type==1){
			$params=array();
			$params['location']=$param['ypoint'].','.$param['xpoint'];
			$params['output']='json';
			$params['extensions_poi']=1;
			//$params['poiType']='小区';
			$params['ak']=$ak;
	    }else{
		   $params=array();
			$params['output']='json';
			$params['extensions_poi']=1;
			//$params['city']=$param['city'];
			//if($param['address'])$params['address']=$param['address'];
			$params['ak']=$ak;
	    }

		$data=$this->http($url,$params);
		$info=json_decode($data,true);
		$geo=array();
		if($info['status']==0 && $type=1){
			$geo['xpoint']=$info['result']['location']['lng'];
			$geo['ypoint']=$info['result']['location']['lat'];
			$geo['address']=$info['result']['formatted_address'];
			$geo['city']=$info['result']['addressComponent']['city'];
			$geo['district']=$info['result']['addressComponent']['district'];
			$geo['street']=$info['result']['addressComponent']['street'];
			$geo['temp_name']=$info['result']['pois']['name'];
			$geo['init']=1;
			session('geo',$geo);
		}
		return $info;
	}
	/**
	 * 发送HTTP请求方法，目前只支持CURL发送请求
	 * @param  string $url    请求URL
	 * @param  array  $params 请求参数
	 * @param  string $method 请求方法GET/POST
	 * @return array  $data   响应数据
	 */
	protected function http($url, $params, $method = 'GET', $header = array(), $multi = false) {
		$opts = array(
			CURLOPT_TIMEOUT			 => 30,
			CURLOPT_RETURNTRANSFER	 => 1,
			CURLOPT_SSL_VERIFYPEER	 => false,
			CURLOPT_SSL_VERIFYHOST	 => false,
			CURLOPT_HTTPHEADER		 => $header
		);
		/* 根据请求类型设置特定参数 */
		switch (strtoupper($method)) {
			case 'GET':
				$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
				break;
				
			case 'POST':
				//判断是否传输文件
				$params = $multi ? $params : http_build_query($params);
				$opts[CURLOPT_URL] = $url;
				$opts[CURLOPT_POST] = 1;
				$opts[CURLOPT_POSTFIELDS] = $params;
				break;
			default:
				// E('不支持的请求方式！');
		}
		/* 初始化并执行curl请求 */
		$ch = curl_init() ;
		curl_setopt_array($ch, $opts);
		$data = curl_exec($ch);
		$error = curl_error($ch);
		curl_close($ch);
		if ($error) {
			// E('请求发生错误：' . $error);
		}
		return $data;
	}
}
?>