<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
//途牛apiurl
define("TUNIU_URL","https://open.tuniu.cn");
//途牛apikey
define("TUNIU_KEY","AILvoDj8El7KCSMe25");



class Tuniu_train extends CI_Controller{
	
	public function __construct(){
        // header("Content-Type: text/html;charset=utf-8");
        parent::__construct();
		date_default_timezone_set('PRC'); 
		$this->load->helper('tuniu');
		$this->load->library('Des');
		$this->load->model("tuniuprice_model");
    }
	
	//创建请求签名
	public function create_sign(){
		$time = date('Y-m-d H:i:s',time());
		$secretKey = 'hxRkFRKaYCScaJRRO2db';
		$id = 'retailId25';
		$timeStamp = 'timestamp'.$time;
		$sign = $secretKey.$id.'apiKey'.TUNIU_KEY.$timeStamp.$secretKey;
		return strtoupper(md5($sign));
	}
	
	//index
	public function index(){
		echo 'hi,tuniu';
	}
	
	//获取余票
    public function search($date=null,$fromStation=null,$toStation=null){
		set_time_limit(0); 
		if(!$date || !$fromStation || !$toStation){
			exit('传参错误！');
		}else{
			//做超过预售期的处理查询
			$isCache = false;
			$iseven = false;
			$cachedata = false;
			$now_time = time();
			$differ = (strtotime($date) - $now_time) / 86400;
			if($differ > 29){
				$date = date('Y-m-d',strtotime('+7day'));
				$iseven = true;
			}
			
			//途牛报文拼接
			$sign = $this->create_sign();
			$url = TUNIU_URL.'/train/search';
			$time = date('Y-m-d H:i:s',time());
			$post_data = '{ 
					"apiKey": "'.TUNIU_KEY.'", 
					"sign": "'.$sign.'", 
					"timestamp": "'.$time.'", 
					"data": { "trainDate": "'.$date.'", "fromStation": "'.$fromStation.'", "toStation": "'.$toStation.'", "trainCode": "" } 
					}';	
			//设置请求接口时间		
			$api_start_time = microtime(true);		
			
			$back_data = post_tuniu($url,$post_data,$method = 'POST');
			//$back_data = null;
			//接口结束时间
			$api_end_time = microtime(true);
			
			//计算响应时间
			$api_responsive_time = $api_end_time - $api_start_time;
			
			if(!empty($back_data)){
				$tn_info = json_decode($back_data);
				$retrun_code = $tn_info->returnCode;
				$return_msg = $tn_info->errorMsg;
			}else{
				$retrun_code = '404';
				$return_msg = '途牛接口未响应';
			}
			
			if(isset($tn_info->data)){
				if(empty(json_decode($back_data)->data)){
					$isCache = true;
				}else{
					$this->tuniuprice_model->addOrUpdate($fromStation,$toStation,$back_data);
				}
			}else{
				$isCache = true;
			}
			
			if($isCache){
				if($differ <= 5){
					$back_data = null;
				}else{
					$trainCache = $this->tuniuprice_model->get_train_cache($fromStation,$toStation);
					if(!empty($trainCache)){
						$back_data = $trainCache->tpc_content;
						$cachedata = true;
					}else{
						$back_data = null;
						$cachedata = false;
					}
				}	
			}
			
			if($cachedata){
				$cacheuse = '使用缓存';
			}else{
				$cacheuse = '缓存为空';
			}
			
			//记录数据格式 |出发站|到达站|发车时间|接口响应时间|接口返回代码|接口返回信息|是否调用缓存
			log_message('error','tuniutrain|'.$fromStation.'|'.$toStation.'|'.$date.'|'.$api_responsive_time.'|'.$retrun_code.'|'.$return_msg.'|'.$cacheuse);
			
			//途牛数据格式转换
			$return_data = new stdClass();
			$return_data->httpstatus = 200;
			$return_data->data = new stdClass(); 
			$return_data->data->seven = $iseven;
			$return_data->data->cache = $isCache;
			$return_data->data->result = array();
			$return_data->data->map = new stdClass();
			
			$obj = array();
			$i = 0;
			$pricestr = '';
			if(!empty(json_decode($back_data)->data)){
				foreach (json_decode($back_data)->data as $value){
					$obj[$value->fromStationCode] = $value->fromStationName;
					$obj[$value->toStationCode] = $value->toStationName;
					$seat_type = '';
					if(isset($value->gjrwXiaPrice)){
						if(is_numeric($value->gjrwXiaPrice)){
							$gjrwXiaPrice = $value->gjrwXiaPrice * 10;
							$seat_type .= '"6":"'.$gjrwXiaPrice.'","A6":"¥'.$value->gjrwXiaPrice.'",'; 
						}
					}
					if(isset($value->qtxbPrice)){
						if(is_numeric($value->qtxbPrice)){
							$seat_type .= '"H":"¥'.$value->qtxbPrice.'",';
						}
					}
					if(isset($value->rwPrice)){
						if(is_numeric($value->rwPrice)){
							$rwPrice = $value->rwPrice * 10;
							$seat_type .= '"4":"'.$rwPrice.'","A4":"¥'.$value->rwPrice.'",'; 
						}
					}
					if(isset($value->rzPrice)){
						if(is_numeric($value->rzPrice)){
							$rzPrice = $value->rzPrice * 10;
							$seat_type .= '"2":"'.$rzPrice.'","A2":"¥'.$value->rzPrice.'",'; 
						}
					}
					if(isset($value->tdzPrice)){
						if(is_numeric($value->tdzPrice)){
							$seat_type .= '"P":"¥'.$value->tdzPrice.'",';
						}
					}
					if(isset($value->wzPrice)){
						if(is_numeric($value->wzPrice)){
							$wzPrice = $value->wzPrice * 10;
							$seat_type .= '"WZ":"¥'.$value->wzPrice.'",'; 
						}
					}
					if(isset($value->ywPrice)){
						if(is_numeric($value->ywPrice)){
							$ywPrice = $value->ywPrice * 10;
							$seat_type .= '"3":"'.$ywPrice.'","A3":"¥'.$value->ywPrice.'",'; 
						}
					}
					if(isset($value->yzPrice)){
						if(is_numeric($value->yzPrice)){
							$yzPrice = $value->yzPrice * 10;
							$seat_type .= '"1":"'.$yzPrice.'","A1":"¥'.$value->yzPrice.'",'; 
						}
					}
					if(isset($value->edzPrice)){
						if(is_numeric($value->edzPrice)){
							$seat_type .= '"O":"¥'.$value->edzPrice.'",'; 
						}
					}
					if(isset($value->ydzPrice)){
						if(is_numeric($value->ydzPrice)){
							$seat_type .= '"M":"¥'.$value->ydzPrice.'",'; 
						}
					}
					if(isset($value->swzPrice)){
						if(is_numeric($value->swzPrice)){
							$swzPrice = $value->swzPrice * 10;
							$seat_type .= '"9":"'.$swzPrice.'","A9":"¥'.$value->swzPrice.'",'; 
						}
					}
					$pricestr = $seat_type.'"train_no":'.'"'.$value->trainNo.'"';
					
					//对返回的数据进行容错处理
					$value->gjrwNum = isset($value->gjrwNum) ? ticket_exchange($value->gjrwNum,$iseven) : '';
					$value->rwNum = isset($value->rwNum) ? ticket_exchange($value->rwNum,$iseven) : '';
					$value->rzNum = isset($value->rzNum)?ticket_exchange($value->rzNum,$iseven) : '';
					$value->tdzNum = isset($value->tdzNum)?ticket_exchange($value->tdzNum,$iseven) : '';
					$value->wzNum = isset($value->wzNum)?ticket_exchange($value->wzNum,$iseven) : '';
					$value->ywNum = isset($value->ywNum)?ticket_exchange($value->ywNum,$iseven) : '';
					$value->yzNum = isset($value->yzNum)?ticket_exchange($value->yzNum,$iseven) : '';
					$value->edzNum = isset($value->edzNum)?ticket_exchange($value->edzNum,$iseven) : '';
					$value->ydzNum = isset($value->ydzNum)?ticket_exchange($value->ydzNum,$iseven) : '';
					$value->swzNum = isset($value->swzNum)?ticket_exchange($value->swzNum,$iseven) : '';
					$value->dwNum = isset($value->dwNum)?ticket_exchange($value->dwNum,$iseven) : '';
					$value->runTime = isset($value->runTime)?$value->runTime : '';
					
					//余票字符串
					$return_data->data->result[$i] = '|预定|'.$value->trainNo.'|'.$value->trainCode.'|'.$value->fromStationName.'|'.$value->toStationName.'|'.$value->fromStationCode.'|'.$value->toStationCode.'|'.$value->startTime.'|'.$value->arriveTime.'|'.$value->runTime.'|'.$value->canBuyNow.'||'.date('Ymd',strtotime($value->trainStartDate)).'||||||||'.$value->gjrwNum.'||'.$value->rwNum.'|'.$value->rzNum.'|'.$value->tdzNum.'|'.$value->wzNum.'||'.$value->ywNum.'|'.$value->yzNum.'|'.$value->edzNum.'|'.$value->ydzNum.'|'.$value->swzNum.'|'.$value->dwNum.'||';
					$data = '{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{'.$pricestr.'},"messages":[],"validateMessages":{}}';
					$return_data->data->price[$i] = $data;
					$i++;
				}
			}
			$return_data->data->map = (object)$obj;
			print_r(json_encode($return_data));
		}
    }
	
	//获取价格
	/*
	fromStationCode：出发站三字码
	toStationCode:终点站三字码
	trainCode:车次
	*/
	public function get_price($fromStationCode=null,$toStationCode=null,$trainCode=null){
		if(!$fromStationCode || !$toStationCode || !$trainCode){
			exit('传参错误！');
		}else{
			$return_data = $this->tuniuprice_model->get_price($fromStationCode,$toStationCode,$trainCode);
			print_r(json_decode($return_data->TPL_Price));
		}
	}
	
	//占座下单
	public function book_ticket(){
		header('Content-Type:application/json;charset=UTF-8');
		$sign = $this->create_sign();
		$url = TUNIU_URL.'/train/book';
		$time = date('Y-m-d H:i:s',time());
		$data = '{
					"retailOrderId": "w123", 
					"cheCi": "K1137", 
					"fromStationCode": "GBZ",
					"fromStationName":"桂林北",
					"toStationCode":"NNZ",
					"toStationName":"南宁",
					"trainDate":"2017-09-25",					
					"callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/book",
					"hasSeat":true,
					"contact":"陈宇超",
					"phone":"18877381547",	
					"passengers":[{
						"passengerId":1,
						"ticketNo": null,
						"passengerName": "陈宇超",
						"passportNo": "450302199208131039",
						"passportTypeId": "1",
						"passportTypeName": "二代身份证",
						"piaoType": "1",
						"piaoTypeName": "成人票",
						"zwCode": "4",
						"zwName": "软卧",
						"cxin": null,
						"price": "166.5",
						"reason": 0
					}]
					}';
		$crypt = new DES();
		$mstr = $crypt->encrypt($data,TUNIU_KEY);
		$post_data = '{ 
				"apiKey": "'.TUNIU_KEY.'", 
				"sign": "'.$sign.'", 
				"timestamp": "'.$time.'", 
				"data": "'.$mstr.'" 
				}';	
		//print_r($url);		
		print_r($post_data);
		$back_data = post_tuniu($url,$post_data,$method = 'POST');
		print_r($back_data);
	}
	
	//取消占座
	public function cancel_book($retailOrderId,$orderId){
		$url = TUNIU_URL.'/train/cancel';
		$sign = $this->create_sign();
		$time = date('Y-m-d H:i:s',time());
		$data = 
		$post_data = '{ 
				"apiKey": "'.TUNIU_KEY.'", 
				"sign": "'.$sign.'", 
				"timestamp": "'.$time.'", 
				"data": {
					"retailOrderId":"'.$retailOrderId.'",
					"orderId":"'.$orderId.'",
					"callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/cancelbook"
				}
				}';	
		 $back_data = post_tuniu($url,$post_data,$method = 'POST');
		 print_r($back_data);
	}
	
	//确认出票
	public function confirm_ticket($retailOrderId,$orderId){
		$url = TUNIU_URL.'/train/confirm';
		$sign = $this->create_sign();
		$time = date('Y-m-d H:i:s',time());
		$post_data = '{ 
				"apiKey": "'.TUNIU_KEY.'", 
				"sign": "'.$sign.'", 
				"timestamp": "'.$time.'", 
				"data": {
					"retailOrderId":"'.$retailOrderId.'",
					"orderId":"'.$orderId.'",
					"callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/confirm"
				}
				}';	
		 $back_data = post_tuniu($url,$post_data,$method = 'POST');
		 print_r($back_data);
	}
	
	//退票
	public function cancel_ticket($retailOrderId,$orderId){
		$url = TUNIU_URL.'/train/return';
		$sign = $this->create_sign();
		$time = date('Y-m-d H:i:s',time());
		$data = '{
					"retailOrderId": "'.$retailOrderId.'",
					"orderId": "'.$orderId.'",
					"orderNumber": "E551561213",
					"callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/return_ticket",
					"tickets":[{
						"ticketNo": "TN_aaac40ec06d72851",
						"passengerName": "陈宇超",
						"passportTypeId": "1",
						"passportNo": "450302199208131039"
					}]
				  }';
		$crypt = new DES();
		$mstr = $crypt->encrypt($data,TUNIU_KEY);	  
		$post_data = '{ 
				"apiKey": "'.TUNIU_KEY.'", 
				"sign": "'.$sign.'", 
				"timestamp": "'.$time.'", 
				"data": "'.$mstr.'"
				}';	
		 $back_data = post_tuniu($url,$post_data,$method = 'POST');
		 print_r($back_data);
	}
	
	//查询经停站
	public function queryStaions($time,$trainNo){
		$sign = $this->create_sign();
		$url = TUNIU_URL.'/train/queryStations';
		$time = date('Y-m-d H:i:s',time());
		$post_data = '{ 
				"apiKey": "'.TUNIU_KEY.'", 
				"sign": "'.$sign.'", 
				"timestamp": "'.$time.'", 
				"data": { 
					"trainDate": "'.$time.'",
					"trainCode": "'.$trainNo.'"
					} 
				}';	
		$back_data = post_tuniu($url,$post_data,$method = 'POST');
		print_r($back_data);		
	}
	
	//车站三字码查询
	public function telecodeQuery(){
		$sign = $this->create_sign();
		$url = TUNIU_URL.'/train/telecodeQuery';
		$time = date('Y-m-d H:i:s',time());
		$post_data = '{ 
				"apiKey": "'.TUNIU_KEY.'", 
				"sign": "'.$sign.'", 
				"timestamp": "'.$time.'", 
				"data": null
				}';
		$back_data = post_tuniu($url,$post_data,$method = 'POST');
		print_r($back_data);		
	}
	
	//身份验证
	public function validate(){
		//$name = $this->input->post('name');
		//$identityType = $this->input->post('identityType');
		//$identifyCard = $this->input->post('identifyCard');
		$sign = $this->create_sign();
		$url = TUNIU_URL.'/train/validate';
		$time = date('Y-m-d H:i:s',time());
		$post_data = '{ 
				"apiKey": "'.TUNIU_KEY.'", 
				"sign": "'.$sign.'", 
				"timestamp": "'.$time.'", 
				"data": { "name": "", "identityType": "", "identifyCard": ""} 
				}';		
		$back_data = post_tuniu($url,$post_data,$method = 'POST');
		print_r($back_data);
	}
}   