<?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 $host_preview = 'http://newrent.house365.com';


	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',//房源举报申诉
        'vr_check'=>'/zsbapi/broker/vr-add-before',//VR申请校验
        'vr_add'=>'/zsbapi/broker/vr-add',//VR申请提交
        'vr_cancel'=>'/zsbapi/broker/vr-cancel',//VR申请取消
        'uploadPic' => '/ajax-action/upload-file', // 上传图片接口
        'login_qr_code' => '/zsbapinj/qr-code-login/login-qr-code', // 登录二维码
        'user_by_qr_code' => '/zsbapinj/qr-code-login/login-qr-code-data', // 校验是否确认登录
	);


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

        //预发布环境，更改请求域名
        $user_agent = empty($_SERVER['HTTP_USER_AGENT'])?'':$_SERVER['HTTP_USER_AGENT'];
        if($user_agent == 'preview_release'){
            $this->host = $this->host_preview;
        }
	}

	/**
	 * 返回租售宝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;
	}

    /**
     * @author Livfer
     * @param $key string 接口key
     * @param $filename string 文件名
     * @param $path string 临时文件路径
     * @param string $type  string 文件类型
     * @return array|bool|mixed|string
     */
    public function requestFile($key,$filename,$path,$type='text/plain')
    {
        $url = $this->getApiFullUrl($key);
        $token = $this->getToken();
        $header = array('token:'.$token);

        $response = $this->postUploadFile($url,$header,$filename,$path,$type);
        $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;
	}

    /**
     * 上传文件
     * @author Livfer
     * @param $url string 接口地址
     * @param $header array 头
     * @param $filename string 上传文件名
     * @param $tmpName string 临时文件名
     * @param string $type string 文件类型
     * @return bool|string
     */
    function postUploadFile($url,$header,$filename,$tmpName,$type = 'text/plain')
    {
        $data = array(
            'file_name'=>'@'.realpath($tmpName).";type=".$type.";filename=".$filename,
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        if($sError=curl_error($ch)){
            return false;
        }
        curl_close($ch);
        return $response;
    }

	public function getToken(){

		$uid = $this->user_arr['uid'];
		$key = $this->token.'_'.$uid;
        if($_COOKIE['clear']){
            $this->mc->delete($key);
        }
		$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,600);
		return $token;
	}


}