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

class returnorders extends CI_Controller{
	
	public function __construct(){
        parent::__construct();
		$this->load->helper('train');
		$this->load->model("train_system_model");
		$this->load->model("Sendmail_model");
		$this->load->model('BIZ_train_model');
		$this->usercenter = 'yes';
    }
	
	public function index(){
		echo 'return tickets';
	}
	
	public function returntickets(){
		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');
		//第三方订单号(为了避免一个子订单乘客分开出票而产生错误)
		$ordernumber = $this->input->get_post('ordernumber');
		//护照姓名
		$passportname = $this->input->get_post('passportname');
		//护照号
		$passportno = $this->input->get_post('passportno');
		//判断是否为用户中心操作
		$this->usercenter = $this->input->get_post('usercenter');
		
		if(!$ordernumber || !$passportname || !$passportno){
			header("HTTP/1.1 404 Not Found");
			exit('{"reason":"传参错误","status":"404"}');
		}

		//网前提交的姓名没有做处理
		$passportname = chk_sp_name($passportname);
		
		$ticket_data = $this->train_system_model->ticketfrom($ordernumber);
		$passenger_data = $this->train_system_model->get_passenger_info($ordernumber,$passportname,$passportno);
		
		if(empty($passenger_data)){
			header("HTTP/1.1 404 Not Found");
			exit('{"reason":"乘客信息为空无法退票","status":"404"}');
			//exit('{"reason":"'.$ordernumber.",".$passportname.",".$passportno.'","status":"404"}');
			exit('');
		}
		
		$channel = $ticket_data->ts_channel;
		
		switch ($channel){
			case 'juhe':
				$this->juheModel($ticket_data,$passenger_data);
				break;
			case 'ctrip':
				$this->ctripModel($ticket_data,$passenger_data);
				break;
			case 'lanhai':
				$this->lanhaiModel($ticket_data,$passenger_data);
				break;
		}
	}
	
	function juheModel($ticket_data,$data){
		$post_data = array(
					"key"=>JUHE_TRAIN_API_KEY,
					"orderid"=>$ticket_data->ts_ordernumber
						); 
		$back_json = GetPost_http(JUHE_TRAIN_STATUS_API,$post_data);
		$back_detail_data = json_decode($back_json);
		//print_r($back_data);die();
		foreach($back_detail_data->result->passengers as $items){
			if($items->passengersename == $data->tst_realname && $items->passportseno == $data->tst_numberid){
				$ticket_no = $items->ticket_no;
			}
		}
		//发起退票
		$post_data1 = array(
						"key"=>JUHE_TRAIN_API_KEY,
						"orderid"=>$ticket_data->ts_ordernumber,
						"tickets"=>'[{"ticket_no":"'.$ticket_no.'","passengername":"'.$data->tst_realname.'","passporttypeseid":"'.strexchangeid($data->tst_ticketype).'","passportseno":"'.$data->tst_numberid.'"}]',
		); 
		//print_r($post_data1);die();
		$back_json = GetPost_http(JUHE_TRAIN_REFUND_API,$post_data1);
		//print_r($post_data1);
		
		log_message('error','聚合退票：'.$ticket_data->ts_ordernumber.'|'.$back_json);
		$back_data = json_decode($back_json);
		
		$fromName = 'trainsystem';
		$fromEmail = 'cyc@hainatravel.com';
		$coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($ticket_data->ts_cold_sn);
		$coli_id = $coli_id['0']->COLI_ID;
		$info = $this->BIZ_train_model->get_operatorInfo($coli_id);
		$toName = $info[0]->Name;
		$toEmail = $info[0]->OPI_Email;
		$Mobile = $info[0]->Mobile;
		$subject = '退票请求';
		if($back_data->error_code == '0'){
			//退票成功后发送邮件
			$body = $back_detail_data->result->ordernumber.' 提出退票,乘客:'.$data->tst_realname.', '.$back_detail_data->result->start_time.' '.$back_detail_data->result->checi;
			//发送邮件给外联
			$this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body);
			if($this->usercenter == 'yes'){
				//发送邮件给客人
				$customer_subject = 'China Train Ticket(s) Cancelation';
				$customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.', email address: '.$toEmail.', phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.';
				$customer_email = $this->BIZ_train_model->get_guest_info($coli_id);
				$customer_email = $customer_email[0]->GUT_Email;
				$this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body);
			}
			echo '{"reason":"退票成功","status":"200"}';
		}else{
			//退票失败后发送邮件
			$body = $ticket_data->ts_ordernumber.'退票失败';
			//发送邮件给外联
			$this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body);
			if($this->usercenter == 'yes'){
				//发送邮件给客人
				$customer_subject = 'China Train Ticket(s) Cancelation';
				$customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.$Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>';
				$customer_email = $this->BIZ_train_model->get_guest_info($coli_id);
				$customer_email = $customer_email[0]->GUT_Email;
				$this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body);
			}
			header("HTTP/1.1 404 Not Found");
			echo '{"reason":"退票失败","status":"404"}';
		}
	}
	
	function ctripModel($ticket_data,$passenger_data){

		//生成接口请求头参数
		$TimeStamp = date("Y-m-d H:i:s");
		$serviceName = "train.artificialTicketReturn"; //每个接口都有自己名称
		$companyId = COMPANYID;
		$key = CTRIPKEY;
		$strSign = $TimeStamp.$serviceName.$companyId.$key; //加密前的令牌
		$Sign = md5($strSign);
		$url = CTRIPURL."/artificialTicketReturn";


		$PostData = new stdClass();
		$PostData->authentication = new stdClass();
		$PostData->authentication->timeStamp = $TimeStamp;
		$PostData->authentication->serviceName = $serviceName;
		$PostData->authentication->companyId = $companyId;
		$PostData->authentication->messageIdentity = $Sign;


		$PostData->companyOrderId = $ticket_data->ts_ordernumber;
		$PostData->operator = "vivi";
		$PostData->returnServiceFee = "15"; //退票服务费
		$PostData->returnTicketList['0'] = new stdClass();
		$PostData->returnTicketList['0']->trainNo = $passenger_data->ts_checi;
		//车厢及座位分解
		$tst_seatdetail = $passenger_data->tst_seatdetail;
		$carriageNo = "";
		$seatNo = "";
		if (strpos($tst_seatdetail,"车厢")!=false){
			$arrSeat = explode("车厢",$tst_seatdetail);
			$carriageNo = $arrSeat[0];
			$seatNo = $arrSeat[1];
		}

		$PostData->returnTicketList['0']->carriageNo = $carriageNo;
		$PostData->returnTicketList['0']->seatNo = $seatNo;
		$PostData->returnTicketList['0']->longElecNo = $passenger_data->tst_LongTrainNo;
		$PostData->returnTicketList['0']->cardFirstImage = "";
		$PostData->returnTicketList['0']->cardSecondImage ="";

		// print_r(json_encode($PostData));
		// die();
		
		//发起退票请求
		$ResponseJson = GetPost_http($url,json_encode($PostData),'json');
		log_message('error','退票返回信息：'.$ResponseJson);
		$ResponseData = json_decode($ResponseJson);
		
		if($ResponseData->returnCode == 1){
			echo '{"reason":"退票成功","status":"200"}';
		}else{
			header("HTTP/1.1 404 Not Found");
			echo '{"reason":"退票失败","status":"404"}';
		}
	}

	/**
	 * 澜海退票，这里只是提交退票提交。没有具体退票信息 
	 */
	function lanhaiModel($ticket_data,$passenger_data){
		$microtime = get_microtime();

		//生成接口请求头参数
		$dataId = $passenger_data->tst_id;
		$mainOrderId = $passenger_data->tst_ordernumber;
		$timestamp = $microtime;
		$appId = LANHAI_appId;
		$url = LANHAI_URL."api/open/refund/order";

		//拼接发送的报文
		$PostData = new stdClass();
		$PostData->dataId = $dataId;
		$PostData->mainOrderId = $mainOrderId;
		$PostData->timestamp = $timestamp;
		$PostData->appId = $appId;

		// print_r(json_encode($PostData));
		// die();
		

		$ResponseJson = GetPost_http($url,json_encode($PostData),'json');		
		log_message('error','澜海退票请求返回信息：'.$ResponseJson);
		$ResponseData = json_decode($ResponseJson);

		// print_r($ResponseData);
		// die();

		//退票请求成功后执行支付
		if($ResponseData->code == 0 && $ResponseData->success){
			echo '{"reason":"退票提交成功","status":"200"}';
		}else{
			if (isset($ResponseData->msg)){
				$errMsg = $ResponseData->msg;
			}else{
				$errMsg = "";
			}
			header("HTTP/1.1 404 Not Found");
			echo '{"reason":"退票提交失败"'.$errMsg.',"status":"404"}';
		}
	}
	
	//改签退票
	public function returnreschedule(){
		//接收数据
		$orderNumber = $this->input->get_post('orderNumber');
		$username = $this->input->get_post('username');
		$userid = $this->input->get_post('userid');
		
		//判断数据是否完全
		if(empty($orderNumber) || empty($username) || empty($userid)){
			exit('参数错误');
		}
		$postData = array();
		$time = date('Y-m-d H:i:s',time());
		$postData['Authentication'] = new stdClass();
		$postData['Authentication']->TimeStamp = $time;
		$postData['Authentication']->ServiceName = 'order.partnerreturnreschedule';
		$postData['Authentication']->PartnerName = 'Ctrip.Corp';
		$MessageIdentity = md5($time.'order.partnerreschedule'.ORDERKEY);
		$postData['Authentication']->MessageIdentity = $MessageIdentity;
		
		$postData['TrainOrderService'] = new stdClass();
		$postData['TrainOrderService']->Operator = 'guilintravel';
		$postData['TrainOrderService']->OrderNumber = $orderNumber;
		$postData['TrainOrderService']->PartnerName = 'Ctrip.Corp';
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos = array();
		
		//获取乘客信息
		$passagerinfo = $this->train_system_model->get_passenger_info($orderNumber,$username,$userid);
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos = array();
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0'] = new stdClass();
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0']->eOrderNumber = $passagerinfo->ts_elecnumber;
		if($passagerinfo->ts_elecnumber == '儿童票'){
			$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0']->eOrderType = 2;
		}else{
			$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0']->eOrderType = 1;
		}
		$rescheduledetail = json_decode($passagerinfo->ts_reschedulecallback);
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0']->realName = $passagerinfo->tst_realname;
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0']->CarriageNo = $rescheduledetail->TrainOrderService->OrderInfo->RescheduleTicketInfo->RescheduleTickets->RescheduleTicket->ResCarriageNo;
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0']->seatNumber = $rescheduledetail->TrainOrderService->OrderInfo->RescheduleTicketInfo->RescheduleTickets->RescheduleTicket->ResSeatNumber;
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0']->passportName = $passagerinfo->tst_realname;
		$postData['TrainOrderService']->ReturnReschedulePassengerInfos['0']->passport = $passagerinfo->tst_numberid;
		
		$url = 'http://m.ctrip.com/restapi/soa2/11009/json/PartnerReturnRescheduleService';
		$responseJson = GetPost_http($url,json_encode($postData),'json');
		print_r($responseJson);
	}
	
	
}