<?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.1';// 访问API使用的公用版本号
	private $token = 'ZSB_API';
    private $host_preview = 'http://newrenttest.house365.com';
    private $signKey = '63DBC5C8E29B1D75AC8CE2676FE7C5F3AABED64B';


	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', // 校验是否确认登录
        'scan_login' => '/zsbapi/qr-code-login/uc-scan-login', // 扫码登录校验
        'uc_login' => '/zsbapi/broker/uc-login', // 登录
        'uc_update' => '/zsbapi/broker/uc-update', // 更新经纪人信息
        'change_uc_phone' => '/zsbapi/broker/change-uc-phone', // 更改经纪人手机号码
        'add_change_price_log' => '/api/tf-app/add-house-price-log', // 添加房源修改价格日志
        'get_sms_code' => '/zsbapi/broker/get-sms-code', // 获取登录短信验证码
        'code_login' => '/zsbapi/broker/fz-code-login', // 验证码登录
	);


	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;
	}

    /**
     * 生成sign
     * @param  array  $param
     * @return string
     * @author mellon
     */
    public function getSign($param = array())
    {
        if (!is_array($param)) {
            return '';
        }
        ksort($param);
        foreach ($param as $key => $item) {
            if (!empty($item) && !is_array($item)) {
                $newArr[] = $key.'='.$item;
            }
        }
        $stringA = implode("&", $newArr);
        $stringSignTemp = $stringA."&key=".$this->signKey;
        $stringSignTemp = md5($stringSignTemp);
        $sign = sha1($stringSignTemp);
        return $sign;
    }
}