<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class zsb_api_model extends MY_Model{


	private $host = 'http://newrent.house365.com';
	private $apiSource = 'PC';// 访问API使用的公用source
	private $apiVersion = '1.0.0';// 访问API使用的公用版本号
	private $token = 'ZSB_API';


	private $apiUrl = array(
		'getToken'=>'/api/zsb-app/api-token',//获取令牌
		'realInfo'=>'/zsbapi/real-manage/get-real-info',//获取状态
		'openReal'=>'/zsbapi/real-manage/open-real',//开通放心看
		'realCheckPay'=>'/zsbapi/real-manage/real-check-pay',//支付检查
		'realHouseRemit'=>'/zsbapi/real-manage/real-house-remit',//放心看提现
		'setRealHouse'=>'/zsbapi/real-manage/set-real-house',//放心看设置
		'cancleRealHouse'=>'/zsbapi/real-manage/cancle-real-house',//放心看设置
        'reportRecord'=>'/zsbapi/house/report-record',//举报记录
        'reportRecordAppeal'=>'/zsbapi/house/report-record-appeal',//申诉记录展示
        'realHouseAppeal'=>'/zsbapi/house/real-house-appeal',//房源举报申诉
	);


	public function __construct()
	{
		parent::__construct(1,1,1);
		$this->load->model('broker_model');
		$this->user_arr = $this->broker_model->get_user_session();
	}

	/**
	 * 返回租售宝API地址
	 * @param string $key
	 * @return string
	 */
	protected function getZsbApiUrl($key = '')
	{
		return isset($this->apiUrl[$key]) ? $this->apiUrl[$key] : '';
	}

	public function getApiFullUrl($key = '')
	{
		if (empty($key)) return '';
		$param['source'] = $this->apiSource;
		$param['version'] = $this->apiVersion;
		$param['city'] = GB_CITY;
		$url = $this->host.''.$this->getZsbApiUrl($key). '?' . http_build_query($param);
		return $url;
	}
	/*
	* 发起请求
	*/
	public function getRequrstData($key,$param = array()){
		$url = $this->getApiFullUrl($key);
		$token = $this->getToken();
		$aHeader = array('token:'.$token);
		$response = $this->httpRequest($url,$aHeader,$param);
		$response = json_decode($response,true);
		return $response;
	}



	function httpRequest($sUrl, $header = array(), $aData = array()){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_URL, $sUrl);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($aData));
		$sResult = curl_exec($ch);
		if($sError=curl_error($ch)){
			return false;
		}
		curl_close($ch);
		return $sResult;
	}

	public function getToken(){

		$uid = $this->user_arr['uid'];
		$key = $this->token.'_'.$uid;
		$token = $this->mc->get($key);
		if($token){
			return $token;
		}
		$url = $this->getApiFullUrl('getToken');
		$param['uid'] =  $uid;
		$param['city'] = GB_CITY;
		$data = $this->httpRequest($url,array(),$param);
		if(!$data){
			return array('result'=>0,'msg'=>'接口返回失败');
		}
		$data = json_decode($data,true);
		if(!$data['result']){
			$msg = iconv('utf-8','gbk',$data['msg']);
			return array('result'=>0,'msg'=>$msg);
		}
		$token = $data['data']['token'];
		$this->mc->set($key,$token,12*3600);
		return $token;
	}


}