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

//数据接口
define("DATAUSER","guilintravel");
define("DATAKEY","0dbf1652763c2289533e27437a971854");

//订单接口
define("ORDERUSER","guilintravel");
define("ORDERKEY","07f811fe29f04008a8fcc86e81c012b9");

//数据返回格式地址
define("JSONRETURN","http://m.ctrip.com/restapi/soa2/12976/json/");
define("XMLRETURN","http://m.ctrip.com/restapi/soa2/12976/xml/");


class ctrip_train extends CI_Controller{

	public function __construct(){
        parent::__construct();
		header('Access-Control-Allow-Origin:*');
	    header('Access-Control-Allow-Methods:POST, GET');
	    header('Access-Control-Max-Age:0');
	    header('Access-Control-Allow-Headers:x-requested-with, Content-Type');
	    header('Access-Control-Allow-Credentials:true');
		$this->load->helper('ctrip');
		$this->load->model("ctrip_model");
		date_default_timezone_set('PRC');

    }

	public function index(){
		exit('hello ctrip');
	}

	//查询车次余票
	public function search(){
		//接收参数
		$date = $this->input->get_post('date');
		$from = $this->input->get_post('from');
		$to = $this->input->get_post('to');
		$TrainNo = $this->input->get_post('TrainNo');

		if(!$date || !$from || !$to){
			header("HTTP/1.1 404 Not Found");
			exit('{"httpstatus":404,"data":{"seven":false,"cache":false,"result":[],"map":{}}}');
		}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;
			}

			//转换三字码为中文
			$FromName = $this->ctrip_model->ReplaceCodeToName($from);
			$ToName = $this->ctrip_model->ReplaceCodeToName($to);


			if(!$FromName || !$ToName){
				header("HTTP/1.1 404 Not Found");
				exit('{"httpstatus":404,"data":{"seven":false,"cache":false,"result":[],"map":{}}}');
			}else{
				$FromName = $FromName->station_name;
				$ToName = $ToName->station_name;
			}

			//生成请求链接
			$TimeStamp = time();
			$Sign = md5($TimeStamp.DATAKEY);

			$url = JSONRETURN.'SearchS2S/?From='.urlencode($FromName).'&To='.urlencode($ToName).'&DepartDate='.$date.'&User='.DATAUSER.'&TimeStamp='.$TimeStamp.'&Sign='.$Sign;

			$api_start_time = microtime(true);

			//获取数据
			$ResponseJson = post_ctrip($url,'','GET');

			$api_end_time = microtime(true);

			$ResponseData = json_decode($ResponseJson);
			$api_responsive_time = $api_end_time - $api_start_time;

			if(empty($ResponseData->Trains)){
				log_message('error','ctrip_trian|status:trains is empty |相应时间:'.$api_responsive_time);
			}else{
				log_message('error','ctrip_trian|status:'.$ResponseData->ResponseStatus->Ack.'|相应时间:'.$api_responsive_time);
			}

			//定义返回的json
			$ReturnData = new stdClass();
			$ReturnData->httpstatus = 200;
			$ReturnData->data = new stdClass();
			$ReturnData->data->seven = $iseven;
			$ReturnData->data->cache = $isCache;
			$ReturnData->data->result = array();
			$ReturnData->data->map = new stdClass();
			$obj = array();
			$i = 0;
			$PriceStr = '';

			//数据解析
			if(!empty($ResponseData->Trains)){
				foreach ($ResponseData->Trains as $TrainInfo){
					$obj[$TrainInfo->FromTelcode] = $TrainInfo->FromStationName;
					$obj[$TrainInfo->ToTelcode] = $TrainInfo->ToStationName;
					$SeaType = '';
					//余数初始化为空
					$gjrwNum = $rwNum = $rzNum = $tdzNum = $wzNum = $yzNum = $edzNum = $ydzNum = $swzNum = $ywNum = $dwNum = $ydwNum = $edzNum = null;
					foreach($TrainInfo->Seats as $Seats){
						//从香港出发的 D/G 火车加价3%
						if($from == 'XJA'){
							if(stripos($TrainInfo->TrainNo, "G") !== false || stripos($TrainInfo->TrainNo, "D") !== false){
								$Seats->Price = $Seats->Price * 1.03;
							}
						}

						if($Seats->SeatName == '高级软卧上'){
							$gjrwXiaPrice = $Seats->Price * 10;
							$SeaType .= '"6":"'.$gjrwXiaPrice.'","A6":"¥'.$Seats->Price.'",';
							$gjrwNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '软卧上'){
							$rwPrice = $Seats->Price * 10;
							$SeaType .= '"4":"'.$rwPrice.'","A4":"¥'.$Seats->Price.'",';
							$rwNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '一等双软上'){
							$SeaType .= '"YDW":"¥'.$Seats->Price.'",';
							$ydwNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '软座'){
							$rzPrice = $Seats->Price * 10;
							$SeaType .= '"2":"'.$rzPrice.'","A2":"¥'.$Seats->Price.'",';
							$rzNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '特等座'){
							$SeaType .= '"P":"¥'.$Seats->Price.'",';
							$tdzNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '无座'){
							$SeaType .= '"WZ":"¥'.$Seats->Price.'",';
							$wzNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '硬座'){
							$yzPrice = $Seats->Price * 10;
							$SeaType .= '"1":"'.$yzPrice.'","A1":"¥'.$Seats->Price.'",';
							$yzNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '二等座'){
							$SeaType .= '"O":"¥'.$Seats->Price.'",';
							$edzNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '一等座'){
							$SeaType .= '"M":"¥'.$Seats->Price.'",';
							$ydzNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '商务座'){
							$swzPrice = $Seats->Price * 10;
							$SeaType .= '"9":"'.$swzPrice.'","A9":"¥'.$Seats->Price.'",';
							$swzNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '硬卧上'){
							$ywPrice = $Seats->Price * 10;
							$SeaType .= '"3":"'.$ywPrice.'","A3":"¥'.$Seats->Price.'",';
							$ywNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '二等双软上'){
							$SeaType .= '"EDW":"¥'.$Seats->Price.'",';
							$erwNum = $Seats->TicketLeft;
						}

						if($Seats->SeatName == '动卧上'){
							$SeaType .= '"F":"¥'.$Seats->Price.'",';
							$dwNum = $Seats->TicketLeft;
						}

						$PriceStr = $SeaType.'"train_no":'.'"'.$TrainInfo->TrainNo.'"';
					}


					//对返回的数据进行容错处理
					$gjrwNum = isset($gjrwNum) ? ticket_exchange($gjrwNum,$iseven) : '';
					$rwNum = isset($rwNum) ? ticket_exchange($rwNum,$iseven) : '';
					$rzNum = isset($rzNum) ? ticket_exchange($rzNum,$iseven) : '';
					$tdzNum = isset($tdzNum) ? ticket_exchange($tdzNum,$iseven) : '';
					$wzNum = isset($wzNum) ? ticket_exchange($wzNum,$iseven) : '';
					$ywNum = isset($ywNum) ? ticket_exchange($ywNum,$iseven) : '';
					$yzNum = isset($yzNum) ? ticket_exchange($yzNum,$iseven) : '';
					$edzNum = isset($edzNum) ? ticket_exchange($edzNum,$iseven) : '';
					$ydzNum = isset($ydzNum) ? ticket_exchange($ydzNum,$iseven) : '';
					$swzNum = isset($swzNum) ? ticket_exchange($swzNum,$iseven) : '';
					$dwNum = isset($dwNum) ? ticket_exchange($dwNum,$iseven) : '';
					$ydwNum = isset($ydwNum) ? ticket_exchange($ydwNum,$iseven) : '';
					$erwNum = isset($erwNum) ? ticket_exchange($erwNum,$iseven) : '';


					$runMin = $TrainInfo->DurationMinutes % 60;
					$runHour = ($TrainInfo->DurationMinutes - $runMin) / 60;

					$ReturnData->data->result[$i] = '|预定|'.$TrainInfo->Train12306No.'|'.$TrainInfo->TrainNo.'|'.$TrainInfo->FromStationName.'|'.$TrainInfo->ToStationName.'|'.$TrainInfo->FromTelcode.'|'.$TrainInfo->ToTelcode.'|'.$TrainInfo->StartTime.'|'.$TrainInfo->ArriveTime.'|'.$runHour.':'.$runMin.'|'.$TrainInfo->CanWebBuy.'||'.date('Ymd',strtotime($date)).'||||||||'.$gjrwNum.'||'.$rwNum.'|'.$rzNum.'|'.$tdzNum.'|'.$wzNum.'||'.$ywNum.'|'.$yzNum.'|'.$edzNum.'|'.$ydzNum.'|'.$swzNum.'|'.$dwNum.'|||'.$ydwNum.'|'.$erwNum;

					$data = '{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{'.$PriceStr.'},"messages":[],"validateMessages":{}}';
					$ReturnData->data->price[$i] = $data;
					$i++;
				}
			}
			//print_r($ResponseData);die();
			$ReturnData->data->map = (object)$obj;
			print_r(json_encode($ReturnData));
		}
	}

	//查询经停站
	public function getstopstation(){
		//接收参数
		$DepartDate = $this->input->get_post('DepartDate');
		$TrainNo = $this->input->get_post('TrainNo');

		if(!$DepartDate || !$TrainNo){
			exit('传参错误！');
		}else{
			//生成请求链接
			$TimeStamp = time();
			$Sign = md5($TimeStamp.DATAKEY);

			$url = JSONRETURN.'GetStopStations/?DepartDate='.$DepartDate.'&TrainNo='.$TrainNo.'&User='.DATAUSER.'&TimeStamp='.$TimeStamp.'&Sign='.$Sign;

			$ResponseJson = post_ctrip($url,'','GET');
			$ResponseData = json_decode($ResponseJson);

			//构造12306格式
			$ReturnData = array();
			$ReturnData['validateMessagesShowId'] = '_validatorMessage';
			$ReturnData['status'] = true;
			$ReturnData['httpstatus'] = 200;
			$ReturnData['data'] = array();
			$i = 0;
			$Last_num = count($ResponseData->StopStations);
			foreach($ResponseData->StopStations as $items){
				if($i == 0){
					$ReturnData['data']['data'][$i]['start_station_name'] = $items->StationName;
					$ReturnData['data']['data'][$i]['station_train_code'] = $TrainNo;
					$ReturnData['data']['data'][$i]['end_station_name'] = $ResponseData->StopStations[$Last_num-1]->StationName;
				}
				$ReturnData['data']['data'][$i]['arrive_time'] = $items->ArrivalTime;
				$ReturnData['data']['data'][$i]['station_name'] = $items->StationName;
				$ReturnData['data']['data'][$i]['start_time'] = $items->StartTime;
				$ReturnData['data']['data'][$i]['stopover_time'] = $items->StopMinutes;
				$ReturnData['data']['data'][$i]['station_no'] = $items->StationNo;
				$ReturnData['data']['data'][$i]['isEnabled'] = true;
				$i++;
			}
			$ReturnData['messages'] = array();
			$ReturnData['validateMessages'] = new stdClass();
			print_r(json_encode($ReturnData));
		}
	}

	//获取所有站点信息
	public function getallstation(){
		//生成请求参数
		$TimeStamp = time();
		$Sign = md5($TimeStamp.DATAKEY);

		$url = JSONRETURN.'/GetAllStations/?&User='.DATAUSER.'&TimeStamp='.$TimeStamp.'&Sign='.$Sign;

		$ResponseJson = post_ctrip($url,'','GET');

		$ResponseData = json_decode($ResponseJson);

		$data = array();
		foreach ($ResponseData->Stations as $items){
			$data['StationName'] = isset($items->StationName) ? checkNull($items->StationName) : '';
			$data['PinYin'] = isset($items->PinYin) ? checkNull($items->PinYin) : '';
			$data['Telecode'] = isset($items->Telecode) ? checkNull($items->Telecode) : '';
			$data['Address'] = isset($items->Address) ? checkNull($items->Address) : '';
			$data['Geography'] = isset($items->Geography) ? checkNull($items->Geography) : '';
			$this->ctrip_model->AddOrUpdate($data);
		}
	}

	//查询中转方案
	public function gettraintrainsfer(){
		$FromCode = $this->input->get_post('FromCode');
		$ToCode = $this->input->get_post('ToCode');
		$DepartDate = $this->input->get_post('DepartDate');

		if(!$FromCode || !$ToCode || !$DepartDate){
			exit('传参错误！');
		}else{
			$TimeStamp = time();
			$Sign = md5($TimeStamp.DATAKEY);

			$FromName = $this->ctrip_model->ReplaceCodeToName($FromCode);
			$ToName = $this->ctrip_model->ReplaceCodeToName($ToCode);

			$From = $FromName->station_name;
			$To = $ToName->station_name;

			$url = JSONRETURN.'GetTrainTransfer?User='.DATAUSER.'&TimeStamp='.$TimeStamp.'&Sign='.$Sign.'&From='.urlencode($From).'&To='.urlencode($To).'&DepartDate='.$DepartDate;


			$ResponseJson = post_ctrip($url,'','GET');
			$ResponseData = json_decode($ResponseJson);
			if (!isset($ResponseData->TransferLines)) {
				$ResponseData->TransferLines = [];
			}
			$priceAddSeats = ['软卧','硬卧'];
			foreach ($ResponseData->TransferLines as $methodsItems){
				foreach($methodsItems->Trains as $trainsItems){
					foreach ($trainsItems->Seats as $seatsItems){
						if(in_array($seatsItems->SeatName,$priceAddSeats)){
							$seatsItems->Price = ceil($seatsItems->Price * 1.2);
						}
					}
				}
			}
			// print_r(json_encode($ResponseData));
			return $this->output->set_content_type('application/json')->set_output(json_encode($ResponseData));
		}
	}
}
