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

/**
 * 二手房400电话 
 * @author cw
*/
class Api_400 extends MY_Controller {
	
	/**
	 *所有公钥
	*/
	private $_esfkey = '365esfkey400';
	private $_num_400 = '4008196365';
	private $_timeout = 30;
	private $_cityArr = array('1' => 'nj','2'=>'sz','3'=>'wx','4'=>'cz');

    function __construct()
    {
      parent::__construct();
	  $this->load->model("esf_400_model");
    }
	
	//获取城市参数
	public function get_city_conf()
	{
		print_r(json_encode($this->_cityArr));
	}
	
	
    /**
     * 二手房400电话请求时调取电话接口
	 * num_400=4008196365&num_group=600000&phone=015850722839&code=3ddb095f0f795f539d51671d2de3d263
	 * num_400=4008196365&num_group=600001&phone=18652098575&code=0740e4aae342de9cff6a7a1364bf792c
	 * http://user.house365.com/api_400/getPhone?num_400=4008196365&num_group=600001&phone=18652098575&code=0740e4aae342de9cff6a7a1364bf792c
	 *其中flag为状态码：0表示正常，这时不用考虑errMsg，1表示系统错误，2表示400大号或小号不正确，3表示加密验证未通过，4表示参数不正确
     * @author cw
    */
    public function getPhone()
	{
      
        $referer ="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
		file_get_contents('http://api.house365.com/esf/web/njesf_400_log.php?url='.urlencode($referer));
		$num_400	= $this->input->get('num_400');
		$num_group	= $this->input->get('num_group');
		$phone		= $this->input->get('phone');
		$code		= $this->input->get('code');
		$flag		= 0;

		if(empty($num_400) || empty($num_group) || empty($phone) || empty($code))
		{
			$flag = 4;
			$errMsg = '参数不正确';
		}
		$temp = 'num_400=4008196365&num_group='.$num_group.'&phone='.$phone.'&code=365esfkey400';
	
		$mcode = md5($temp);
		if($_GET['xue']==1){
			echo $mcode;exit();
		}
		if($code == $mcode)
		{
			if($num_400 == $this->_num_400)
			{
				$short_num = intval($num_group);
				if(($short_num>=600000 && $short_num<=699999) || ($short_num>=800000 && $short_num<=899999))
				{
					$info = $this->esf_400_model->get_info_by_group($num_group);
					if(empty($info) || $info[0]['status'] != 1 || empty($info[0]['phone']))
					{
						$flag = 1;
						$errMsg = '系统错误';
					}
					else
					{
						$fromcity = $info[0]['city'];
						$calledphone = $info[0]['phone'];
					}
				}
				else
				{
					$flag = 2;
					$errMsg = '小号不正确';
				}
			}
			else
			{
				$flag = 2;
				$errMsg = '400大号错误';
			}
		}
		else
		{
			$flag = 3;
			$errMsg = '加密验证未通过';
		}

		$errMsg = mb_convert_encoding($errMsg,'utf-8','gbk');
		$data = array(
			'flag'		=> $flag,
			'fromcity'	=> $fromcity,
			'errMsg'	=> $errMsg,
			'num_400'	=> $num_400,
			'num_group'	=> $num_group,
			'phone'		=> $calledphone,
			'timeout'	=> $this->_timeout,
			'istransfer'=> $istransfer,
			'isvoice'	=> $isvoice,
			'voice'		=> $voice,
			'code'		=> $mcode
		);
		$aa=json_encode($data);
	   file_get_contents('http://api.house365.com/esf/web/njesf_400_log.php?url='.urlencode($referer."//".$aa));

		echo json_encode($data);
		//return json_encode($data);
    }
	

	/**
     * 吉亚发送400通话清单
     * @author cw
	 *	{"ID":"0","RESULTNAME":"成功"},
		{"ID":"1","RESULTNAME":"忙"},
		{"ID":"2","RESULTNAME":"无应答"},
		{"ID":"3","RESULTNAME":"客户提前挂机"},
		{"ID":"11","RESULTNAME":"客户主动放弃"},
		{"ID":"201","RESULTNAME":"无效分机号"},
		{"ID":"555","RESULTNAME":"黑名单"},
		{"ID":"777","RESULTNAME":"回呼外线失败"},
		{"ID":"1000","RESULTNAME":"非工作时间"},
		{"ID":"1002","RESULTNAME":"欠费"}
		http://user.house365.com/api_400/recoder?num_400=4008196365&num_group=600000&callphone=15152040040&calledphone=015850722839&begtime=20140924134456&endtime=20140924134550&callfee=0.24&calltime=54&fromcity=1&callResult=0&callreturn_str=成功&callcity=徐州&callprovince=江苏&istransfer=1&isvoice=0&code=662f18ac5b33e85bb777129e54df2afc
		http://user.house365.com/api_400/recoder?num_400=4008196365&num_group=600008&callphone=15850722839&calledphone=015951634202&begtime=20140930111523&endtime=20140930111821&callfee=0.54&calltime=178&callresult=3&callresult_str=客户提前挂机&callcity=南京&callprovince=江苏&istransfer=0&isvoice=&fromcity=1&code=5a2a9160197084fcb860ca6e86b37a6f
    */
	public function recoder()
	{
		$referer ="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
		file_get_contents('http://api.house365.com/esf/web/njesf_400_recoder_log.php?url='.urlencode($referer));
		$timestart = time();
        
		//$msg = '*****************************************************';
	 // $msg .= date('Y-m-d H:i:s').":".$_SERVER['REQUEST_URI']." \n";
	 // @file_put_contents('./tel_recode'.date('Y-m-d'),$msg,FILE_APPEND); 
	   // $url = "api.house365.com/esf/web/api_400.php?stc=".urlencode($_SERVER['REQUEST_URI']);
		//ECHO $url;
	//	curl_get_contents($url);
		$num_group = $this->input->get('num_group');
		$callphone = $this->input->get('callphone');
		$calledphone = $this->input->get('calledphone');
		$begtime = $this->input->get('begtime');
		$endtime = $this->input->get('endtime');
		$callfee = $this->input->get('callfee');
		$calltime = $this->input->get('calltime');
		$fromcity = $this->input->get('fromcity');
		$callResult = $this->input->get('callresult');
		$callresult_str = $this->input->get('callresult_str');
		$callcity = $this->input->get('callcity');
		$callprovince = $this->input->get('callprovince');
		$istransfer = $this->input->get('istransfer');
		$isvoice = $this->input->get('isvoice');
		$code = $this->input->get('code');
        $voiceid = $this->input->get('voiceid');
		$str = array(
			0		=> '成功',	
			1		=> '忙',	
			2		=> '无应答',	
			3		=> '客户提前挂机',	
			11		=> '客户主动放弃',	
			201		=> '无效分机号',	
			555		=> '黑名单',	
			777		=> '回呼外线失败',	
			1000	=> '非工作时间',	
			1002	=> '欠费'	
		);

		//$callreturn_str = $str[$callResult];
		$callcity = mb_convert_encoding($callcity,'gbk','utf-8');
		$callprovince = mb_convert_encoding($callprovince,'gbk','utf-8');
		$callresult_str = mb_convert_encoding($callresult_str,'gbk','utf-8');
		$calledphone = $calledphone;
		$indate = substr($begtime,0,8);
		$mcode = md5('4008196365'.$num_group.'365esfkey400');
		if($mcode != $code )
		{
			return false;
		}
		$data = array(
			'num_group'		=> $num_group,
			'callphone'		=> $callphone,
			'calledphone'	=> $calledphone,
			'begtime'		=> $begtime,
			'indate'		=> $indate,
			'endtime'		=> $endtime,
			'callfee'		=> $callfee,
			'calltime'		=> $calltime,
			'fromcity'		=> $fromcity,
			'callResult'	=> $callResult,
			'callreturn_str'=> $callresult_str,
			'callcity'		=> $callcity,
			'callprovince'	=> $callprovince,
			'istransfer'	=> $istransfer,
			'isvoice'		=> $isvoice,
            'voiceid'		=> $voiceid
		);
		
		$callid = $this->esf_400_model->save_recoder($data);
		if($callid){
            //加入统计分析库
            $data['callid'] = $callid;
			$this->esf_400_model->saveStatistics($data);

			$re['flag'] = 'ok';
			echo json_encode($re);		
			$timeend = time();
			$referer ="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
		file_get_contents('http://api.house365.com/esf/web/njesf_400_recoder_log.php?url='.urlencode($referer."##".$timestart."##".$timeend));
		}else{
			return false;
		}
	}


	/**
     * 获取400短号 type: 0 返回分配400  1 此UID已绑400  2此手机已绑400 
     * @author cw
    */
	public function get_num_group($uid,$phone,$city)
	{
		if(empty($uid) || empty($phone) || empty($city))
		{
			return false;
		}
		$num_group = 0;
		$data = array();

		$info = $this->esf_400_model->get_info_by_uid($uid);
		if($info)
		{
			$data['type']	= 1; //uid已绑定
			$data['city']	= $info[0]['city'];
			$data['status'] = $info[0]['status'];
			$data['phone']	= $info[0]['phone'];
			$data['num_group'] = $info[0]['num_group'];

			return $data;
		}

		$info = $this->esf_400_model->get_info_by_phone($phone);
		if($info)
		{
			$data['type']	= 2; //手机已绑定
			$data['uid']	= $info[0]['uid'];
			$data['city']	= $info[0]['city'];
			$data['status'] = $info[0]['status'];
			$data['phone']	= $info[0]['phone'];
			$data['num_group'] = $info[0]['num_group'];

			return $data;
		}

		$num_group = $this->esf_400_model->get_group(601000,699888);
		while(!$num_group)
		{
			$num_group = $this->esf_400_model->get_group(601000,699888);
		}

		$data['type'] = 0;
		$data['num_group'] = $num_group;

		return $data;
	}


	/**
	* 用户使用400隐私保护的信息
	*
	* @access	public
	* @param	int	$uid 用户编号
	* @param	string	$city 城市字符串参数
	* @return	array	400隐私保护的信息
	*/
	function get_telno400_by_uid( $uid , $city = '')
	{	
		$uid = intval($uid);
		
		$data = array();
		
		if($uid > 0 )
		{	
			if($city != '')
			{
				$city_flip_arr = !empty($this->_cityArr) ?
						array_flip($this->_cityArr) : array();
				$city = isset($city_flip_arr[$city]) ?
						intval($city_flip_arr[$city]) : 0;
			}

			$data = $this->esf_400_model->get_info_by_uid($uid , $city);

			if(is_array($data[0]) && !empty($data[0]))
			{	
				$data[0]['num_400'] = $this->_num_400;
				$data[0]['city_code'] = $this->_cityArr[$data[0]['city']];
			}
		}

		echo json_encode($data);
	}
	
	/**
     * 通过uid,city,短号查询信息
     * @author cw
	 * $arr = array('uid' => 1); wheret条件数组
    */
	public function update_staus($arr,$status)
	{
		$result = $this->esf_400_model->update_staus($arr,$status);
		return $result;
	}

	/**
     * 通过uid释放400号码
     * @author cw
    */
	public function release_uid($uid)
	{
		$result = $this->esf_400_model->release($uid);
		return $result;
	}

	/**
     * 预设置值,用时开启
     * @author cw
    */
	public function set_data()
	{
		return $this->esf_400_model->set_table_data();
	}

	/**
     * 预设用户400电话
     * @author bsw
    */
	public function setUserTel400(){
		$uid = $this->input->get('uid');
        $telno = $this->input->get('telno');
		$city = $this->input->get('city');

		$arrResult['result'] = 0;
		$arrResult['msg'] = '参数错误';
		$arrResult['data'] = array();

		if(!$uid || !$telno || !$city){
			 echo jsonNew($arrResult);die;
		}

		$city_num = array_search($city,$this->_cityArr);
		$tel400Info = $this->esf_400_model->get_info_by_uid($uid,'');
        
		//已经绑定了400
		if($tel400Info[0] && is_array($tel400Info[0])){
			//绑定城市即为当前城市
			if($tel400Info[0]['city'] == $city_num){
				//如果不是暂停状态，则设置为激活状态
				if($tel400Info[0]['status'] != 1){
					$arr = array('id'=>$tel400Info[0]['id']);
					$this->esf_400_model->update_staus($arr,1);
				}
				$arrResult['result'] = 1;
				$arrResult['msg'] = '已经绑定了400';
			}else{
				$arrResult['msg'] = '已经在其他城市绑定了400';
			}

		}else{
			//未分配
			$num_group = $this->esf_400_model->get_group(601000,699888);
			while(!$num_group)
			{
				$num_group = $this->esf_400_model->get_group(601000,699888);
			}
 
            $this->esf_400_model->issue($uid,'',$telno,$num_group,$city_num);

			$arrResult['result'] = 1;
			$arrResult['msg'] = '成功绑定400';
		}

		//$msg = date('y-m-d H:i:s')."::UID:".$uid."-city:".$city."-telno:".$telno."-num_group:".$num_group."-msg:".$arrResult['msg']." \n";
		//$log = 'log/tel400log';
		//@file_put_contents($log,$msg,FILE_APPEND );

		echo jsonNew($arrResult);
	}

 
}