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

class addorders extends CI_Controller{
	
	public function __construct(){
        parent::__construct();
		$this->load->model("BIZ_train_model");
		$this->load->model("train_system_model");
		$this->load->helper('train');
		$this->db_train_zw = $this->config->item('db_train_zw');
        $this->train_zw = $this->config->item('train_zw');
		$this->black_list = $this->config->item('black_list');
		$this->isauto = 0;
		$this->istanding = 'false';
	}
	
	public function index(){
		exit('hello world');
	}
	
	//问题订单处理
	public function error_orders_submit(){
		$this->isauto = 4;
		//获取所有问题订单
		$errorOrdersList = $this->BIZ_train_model->getErrorOrdersList();
		
		foreach ($errorOrdersList as $items){
			$bpe_sn = '';
			$coldSn = $items->cold_sn;
			$people_arr = $this->BIZ_train_model->biz_people($coldSn);
			foreach($people_arr as $people_info){
				$bpe_sn .= $people_info->BPE_SN.',';
			}
			$bpe_sn = substr($bpe_sn,0,strlen($bpe_sn)-1);
			//发送请求
			$this->booktickets($coldSn,$bpe_sn,'','juhe');
		}
	}
	
	//自动出票,2024-1-30改用新方法
	public function auto_pay_ticket(){
		//log_message('error','auto ticket');
		date_default_timezone_set('Asia/Shanghai');
		//判断账户余额，如果小于1000自动退出。
		$post_data = array("key"=>JUHE_TRAIN_API_KEY); 
        $back_data = GetPost_http("http://op.juhe.cn/trainTickets/balance.php",$post_data);
		$price = json_decode($back_data)->result;
		print_r('账户余额：'.$price);
		if($price < 1000){
			exit('账户余额不足');
		}
		//筛选出能自动出票的订单
		$auto_pool = $this->BIZ_train_model->auto_check_ticket();
		
		//创建一个不允许自动出票的国际火车票数组
		$nation_train = array('K19', 'K23', 'Z8701', 'Z8702', 'Z97', 'Z98', 'Z99', 'Z100', 'K9795');
		
		//创建黑名单
		$black_list = $this->config->item('black_list');
		$string = '';
		foreach($auto_pool as $item){
			$this->isauto = 1;
			$bpe_sn = '';
			$back_message = '';
			$cold_sn = $item->COLD_SN;
			$coli_id = $item->coli_id;
			$auto_flag = 1;
			
			$people_arr = $this->BIZ_train_model->biz_people($cold_sn);
			$train_info = $this->BIZ_train_model->biz_order_detail($cold_sn);
			
			if($item->COLD_SPFS > 1){
				//寄送票
				$auto_flag = 0;
				$back_message .= '-邮寄不自动出票';
			}
			
			//乘客人数大于5人不出票
			if(count($people_arr) > 5){
				$auto_flag = 0;
				$back_message .= '-乘客人数大于5不自动出票';
			}
			
			//护照号如果在黑名单的就不自动出票
			foreach($people_arr as $people_info){
				if(in_array($people_info->BPE_Passport,$black_list)){
					$auto_flag = 0;
					$back_message .= '-此用户为黑名单用户，不自动出票';
				}
				
				if(strlen($people_info->BPE_Passport) >= 18){
					$auto_flag = 0;
					$back_message .= '-护照位数大于18不自动出票';
				}
				
				$bpe_sn .= $people_info->BPE_SN.',';
			}
			$bpe_sn = substr($bpe_sn,0,strlen($bpe_sn)-1);
			
			//不是国内支付宝的付款方式的订单需要受到1000元单价限制
			if($item->GAI_Type != '15015' && $item->COLI_State != '8'){
				if($train_info->adultcost > 1000){
					$auto_flag = 0;
					$back_message .= '-单价大于1000不自动出票'; 
				}
			}
			
			//如果为国际火车票就不出票
			if(in_array($train_info->FlightsNo, $nation_train)){
				$auto_flag = 0;
				$back_message .= '-国际火车票不自动出票';
			}
			
			//无座的订单不做出票
			if($train_info->Aircraft == 'WZ'){
				$auto_flag = 0;
				$back_message .= '-无座不自动出票';
			}
			
			//香港火车不自动出票
			if($train_info->DepartAirport == 'XJA'){
				$auto_flag = 0;
				$back_message .= '-香港火车不自动出票';
			}
			
			$DepartureDate = strtotime($train_info->DepartureDate);
			$time = time();
			$depart_diff = ($DepartureDate - $time) / 86400;
			
			if($train_info->ArrivalAirport == 'XJA' && $train_info->adultcost > 500 && $depart_diff > 5){
				$auto_flag = 0;
				$back_message .= '-内地香港火车金额大于500超过五天不自动出票';
			}
			//print_r($train_info);

			//如果刚好是第三十天的订单
			if(($item->COLI_State == '8' || $item->COLI_State == '63')){
				$this->isauto = 3;
				$time_obj = $this->BIZ_train_model->get_saletime($train_info->DepartAirport_cn);
				//print_r($time_obj);
				if(!empty($time_obj)){
					$saletime = strtotime($time_obj->TST_saletime);
					//echo $saletime;
					$sale_diff = (time() - $saletime) / 3600;
					if($sale_diff > 1){
						$auto_flag = 0;
						$back_message .= '-超过抢票时间';
					}else if($sale_diff <0){
						$auto_flag = 0;
						$back_message .= '-未到抢票时间';
					}
				}	
			}
			
			if($auto_flag == 0){
				$string .= '<tr><td>汉特订单号：'.$coli_id.'('.$cold_sn.')'.$back_message.'</td></tr>';
			}else{
				//单个订单提交
				echo $cold_sn.'<br>';
				$this->booktickets($cold_sn,$bpe_sn,'','juhe');
				//$string .= '<tr><td>汉特订单号：'.$coli_id.'('.$cold_sn.')可以自动出票</td></tr>';
			}
		}
		print_r('<table border="1">'.$string.'</table>');
	}

	//自动出票2.0 2024-1-30 zp
	public function auto_pay_ticket_2(){
		date_default_timezone_set('Asia/Shanghai');

		set_time_limit(180);

		//筛选出能自动出票的订单
		$auto_pool = $this->BIZ_train_model->auto_check_ticket_2();


		// $DepartureDate = strtotime(date('Y-m-d',strtotime("2024-5-9"))); //只取日期部分
		// $now = strtotime(date('Y-m-d'));
		// $depart_diff = ($DepartureDate - $now) / 86400;
		// $saletime = strtotime("17:00");  
		// $sale_diff = (time() - $saletime) / 3600;

		//创建一个不允许自动出票的国际火车票数组
		$nation_train = array('K19', 'K23', 'Z8701', 'Z8702', 'Z97', 'Z98', 'Z99', 'Z100', 'K9795','D87');

		//创建黑名单
		$black_list = $this->config->item('black_list');
		$string = '';
		foreach($auto_pool as $item){
			$this->isauto = 1;
			$bpe_sn = '';
			$back_message = '';
			$cold_sn = $item->COLD_SN;
			$coli_id = $item->coli_id;
			$auto_flag = 1;
			
			$people_arr = $this->BIZ_train_model->biz_people($cold_sn);
			$train_info = $this->BIZ_train_model->biz_order_detail($cold_sn);
			
			//乘客人数大于10人不出票
			if(count($people_arr) > 10){
				$auto_flag = 0;
				$back_message .= '-乘客人数大于10不自动出票';
			}
			
			//护照号如果在黑名单的就不自动出票
			foreach($people_arr as $people_info){
				if(in_array($people_info->BPE_Passport,$black_list)){
					$auto_flag = 0;
					$back_message .= '-此用户为黑名单用户，不自动出票';
				}
				
				if(strlen($people_info->BPE_Passport) >= 18){
					$auto_flag = 0;
					$back_message .= '-护照位数大于18不自动出票';
				}
				
				$bpe_sn .= $people_info->BPE_SN.',';
			}
			$bpe_sn = substr($bpe_sn,0,strlen($bpe_sn)-1);
			
			//不是已付款状态的，票价高于5000不出票，以防意外
			if($item->COLI_State != '8'){
				if($train_info->adultcost > 5000){
					$auto_flag = 0;
					$back_message .= '-没支付单价大于5000不自动出票'; 
				}
			}
			
			//如果为国际火车票就不出票
			if(in_array($train_info->FlightsNo, $nation_train) || strlen($train_info->DepartAirport)>3 || strlen($train_info->ArrivalAirport)>3){
				$auto_flag = 0;
				$back_message .= '-国际火车票不自动出票';
			}
			
			//无座的订单不做出票
			if($train_info->Aircraft == 'WZ'){
				$auto_flag = 0;
				$back_message .= '-无座不自动出票';
			}
			
			
			$DepartureDate = strtotime(date('Y-m-d',strtotime($train_info->DepartureDate))); //只取日期部分
			$now = strtotime(date('Y-m-d'));
			$depart_diff = ($DepartureDate - $now) / 86400;

			//如果刚好是第15天的订单(12306的15天预售是算当天的，所以时间差是14天)
			if($depart_diff==14){
				//$this->isauto = 1;
				$time_obj = $this->BIZ_train_model->get_saletime($train_info->DepartAirport_cn);
				//print_r($time_obj);
				if(!empty($time_obj)){
					$saletime = strtotime($time_obj->TST_saletime);
				}else{
					$saletime = strtotime("12:00");  //如果没有设置预售时间，默认8点
				}
				//echo $saletime;
				$sale_diff = (time() - $saletime) / 3600;
				if($sale_diff > 12){
					$auto_flag = 0;
					$back_message .= '-超过抢票时间';
				}else if($sale_diff <0){
					$auto_flag = 0;
					$back_message .= '-未到抢票时间';
				}					
					
				//$time = strtotime(time());
				// $autolasttime = $item->ts_autolasttime;
				// if(($timestamp = strtotime($autolasttime)) !== false) {
				// 	$time_diff = ($time - strtotime($autolasttime)) / 3600;
				// 	if ($time_diff < 1){
				// 		$auto_flag = 0;
				// 		$back_message .= '-预售期每小时只能提交一次';
				// 	}
				// }
			}


			//只能3次抢票
			if ($item->ts_autotimes > 3){
				$auto_flag = 0;
				$back_message .= '-抢票次数已到3次';
			}

			
			if($auto_flag == 0){
				$string .= '<tr><td>汉特订单号：'.$coli_id.'('.$cold_sn.')'.$back_message.'</td></tr>';
				if($depart_diff==14){

				}else{
					log_message('error','自动出票错误信息：'.'<table border="1">'.$string.'</table>');				
				}
				
			}else{
				//单个订单提交
				//echo $cold_sn.'<br>';
				log_message('error','自动出票提交：'.$coli_id.'('.$cold_sn.')');		

				$this->booktickets($cold_sn,$bpe_sn,'','ctrip');  //调用出票
				//$string .= '<tr><td>汉特订单号：'.$coli_id.'('.$cold_sn.')可以自动出票</td></tr>';
			}
		}
		print_r('<table border="1">'.$string.'</table>');

	}
	
	//创建一个方法用于接收所有的出票请求
	public function booktickets($cold_sn=null,$bpe_sn=null,$selectseat=null,$type=null){
		if(empty($cold_sn) && empty($bpe_sn)){
			//接收子表订单号
			$cold_sn = $this->input->get_post('order');
			//接收客人表sn
			$bpe_sn = $this->input->get_post("people");
			//接收选座字符串
			$selectseat = $this->input->get_post("selectseat");
			//接收出票接口
			$type = $this->input->get_post("type");
			//接受是否有站票
			$this->istanding = $this->input->get_post("istanding");
		}
		
		//测试数据
		/*$cold_sn = '488121613';
		$bpe_sn = '473183645,473183646,473183647';
		$selectseat = '';
		$type = 'juhe';*/

		if(!is_numeric($cold_sn)){
            $reback["mes"]="订单号是数字";
            echo json_encode($reback);
            return false; 
        }
		
		if(empty($bpe_sn)){
            $reback["mes"]="请选择乘客";
            echo json_encode($reback);
            return false; 
        }
		
		$data['train'] = $this->BIZ_train_model->biz_order_detail($cold_sn);
        $data['people_list']=$this->BIZ_train_model->in_bpesn_people_info($bpe_sn);
		$coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($cold_sn)['0']->COLI_ID;
		
		if(empty($this->BIZ_train_model->get_operatorInfo($coli_id))){
			$data['email'] = 'vivi@hainatravel.com';
		}else{
			$data['email'] = $this->BIZ_train_model->get_operatorInfo($coli_id)['0']->OPI_Email;
		}
		
		if($selectseat == ''){
			$selectseat = '';
			$train_select = $data['train']->FOI_SelectedSeat;
			$obj = explode(',',$train_select);
			foreach($obj as $value){
				$selectseat .= $value;
			}
		}
		
		if (empty($data['train'])) {
            //显示错误,找不到车次
            $reback["mes"]="找不到车次";
            echo json_encode($reback);
            return false;
        }
		
		if (empty($data['people_list'])) {
            //显示错误，找不到用户信息
            $reback["mes"]="找不到乘客信息";
            echo json_encode($reback);
            return false;
        }
		
		if (count($data['people_list']) > 10) {
            //显示错误，用户超过五个
            $reback["mes"]="乘客不能超过十个";
            echo json_encode($reback);
            return false;
        }

		// print_r(json_encode($data));
		// echo("<hr/>");
		// echo($selectseat);
		// echo("<hr/>");
		// echo($cold_sn);
		// die();
		
		switch ($type){
			case 'juhe':
				$this->juheModel($data,$selectseat,$cold_sn);
				break;
			case 'tuniu':	
				$this->tuniuModel($data,$selectseat,$cold_sn);
				break;
			case 'ctrip':
				$this->ctripModel($data,$selectseat,$cold_sn);
				break;
			case 'lanhai':
				$this->lanhaiModel($data,$selectseat,$cold_sn,$bpe_sn); //澜海多传用户SN列表
				break;
		}
	}
	
	function juheModel($data=null,$selectseat=null,$cold_sn=null){
		$zwcode = $this->db_train_zw[$data['train']->Aircraft]; //座位简码
        $zwname = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; //座位名称
		
		//进行提交字符串的拼接
		$passengers = "";
		foreach ($data['people_list'] as $key => $item) {
            //乘客姓名
            $passengersename = $item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName;
            //将特殊字符转换为正常字符以便于出票
			$passengersename = chk_sp_name($passengersename);
			//乘客类型
            switch ($item->BPE_GuestType) {
                case 1:
                    $piaotype = 1;
                    $piaotypename = "成人票";
                    break;
                case 2:
                    $piaotype = 2;
                    $piaotypename = "儿童票";
                    break;
                default://外国人应该就两种票吧
                    $piaotype = 1;
                    $piaotypename = "成人票";
                    break;
            }
			
			//证件类型
			switch ($item->BPE_PassportType){
				case 'Chinese ID':
					$passporttypeseid = "1";
					$passporttypeseidname = "二代身份证";
					break;
				case 'MainlandTravel Permit from Hong Kong and Macau':
					$passporttypeseid = "C";
					$passporttypeseidname = "港澳通行证";
					break;
				case 'Travel Permit from Taiwan':
					$passporttypeseid = "G";
					$passporttypeseidname = "台湾通行证";
					break;
				default :
					$passporttypeseid = "B";
					$passporttypeseidname = "护照";
					break;
			}
			
			switch ($item->BPE_SEX){
				case '100003':
					$sex = 'F';
					break;
				case '100001':
					$sex = 'M';
					break;
			}
			
            $passportseno = str_replace(' ','',$item->BPE_Passport);
			
			//添加一个判断护照号是否在黑名单
			if(in_array($passportseno,$this->black_list)){
				$reback["mes"] = "乘客为黑名单用户";
				echo json_encode($reback);
				return false;
			}
			
			if($passporttypeseid == 'G'){
				$passengers .= ',{"passengerid":' . (++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"'.$data["train"]->adultcost.'","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '","gatValidDateEnd":"'.$item->BPE_PassExpdate.'","gatBornDate":"'.$item->BPE_BirthDate.'","sexCode":"'.$sex.'","email":"'.$data['email'].'","phoneNum":"13097735982"}';
			}elseif($passporttypeseid == 'B'){
				$passengers .= ',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"'.$data["train"]->adultcost.'","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '","countryCode":"US","email":"'.$data['email'].'","phoneNum":"13097735982"}';
			}else{
				$passengers .= ',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"'.$data["train"]->adultcost.'","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '","phoneNum":"13097735982","email":"'.$data['email'].'"}';
			}
            
        }
		
		$passengers .= "]";
		$passengers = substr($passengers, 1);
		$passengers = "[" . $passengers;

		$is_accept_standing = 'no';
		if($this->istanding == 'true'){
			$is_accept_standing = 'yes';
		}
		
		if(empty($selectseat)){
			 $post_data=array(
                "key"=>JUHE_TRAIN_API_KEY,
                "user_orderid"=>$cold_sn,//自定义订单号
                "train_date"=>substr($data["train"]->DepartureDate, 0, 10),
                "is_accept_standing"=>$is_accept_standing,
                "from_station_name"=>$data["train"]->DepartAirport_cn,
                "from_station_code"=>$data["train"]->DepartAirport,
                "to_station_code"=>$data["train"]->ArrivalAirport,
                "to_station_name"=>$data["train"]->ArrivalAirport_cn,
                "passengers"=>$passengers,
                "checi"=>$data["train"]->FlightsNo
            );	
		}else{
			$post_data=array(
                "key"=>JUHE_TRAIN_API_KEY,
                "user_orderid"=>$cold_sn,//自定义订单号
                "train_date"=>substr($data["train"]->DepartureDate, 0, 10),
                "is_accept_standing"=>$is_accept_standing,
                "choose_seats"=>$selectseat,
                "from_station_name"=>$data["train"]->DepartAirport_cn,
                "from_station_code"=>$data["train"]->DepartAirport,
                "to_station_code"=>$data["train"]->ArrivalAirport,
                "to_station_name"=>$data["train"]->ArrivalAirport_cn,
                "passengers"=>$passengers,
                "checi"=>$data["train"]->FlightsNo
            );	
		}
		
		//发起请求
		$add_data = new stdClass();
		$back_json = GetPost_http('http://op.juhe.cn/trainTickets/submit',$post_data);
		$back_data = json_decode($back_json);
		
		if(!$back_data->error_code){
            $add_data->ordernumber = $back_data->result->orderid;
            $reback["status"] = 1;
            $reback["order"] = $back_data->result->orderid;
            $reback["mes"] = "订单提交成功，等待回调";                             
        }else{ 
            $add_data->ordernumber=null;
            $reback["mes"] = $back_json;
            $add_data->status = "e";
        }
		
		//本地订单入库
		$add_data->cold_sn = $cold_sn;
		$add_data->returncode = $back_data->error_code;
		$add_data->status = '2';
		$add_data->errormsg = '预定中';
		$add_data->checi = $data['train']->FlightsNo;
		$add_data->fromstationame = $data['train']->DepartAirport_cn;
		$add_data->fromstationcode = $data['train']->DepartAirport;
		$add_data->tostationame = $data['train']->ArrivalAirport_cn;
		$add_data->tostationcode = $data['train']->ArrivalAirport;
		$add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate));
		$add_data->startime = date('H:i',strtotime($data['train']->DepartureTime));
		$add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime));
		$add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; 
		$add_data->channel = 'juhe';
		$add_data->isauto = $this->isauto;
		
		$this->train_system_model->add_orders($add_data);
		echo json_encode($reback);
        return false;
		
	}
	
	//途牛模块
	function tuniuModel($data,$selectseat,$cold_sn){
		$this->load->library('Des');
		$zwcode = $this->db_train_zw[$data['train']->Aircraft]; //座位简码
        $zwname = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; //座位名称
		
		$passengers="";
        //$cold_sn = $cold_sn.'_'.time();
		
		//拼接车次信息
        $tuniu_data = '{';
        $tuniu_data .= '"retailOrderId":"'.$cold_sn.'",';
        $tuniu_data .= '"cheCi": "'.$data['train']->FlightsNo.'", ';
        $tuniu_data .= '"fromStationCode": "'.$data['train']->DepartAirport.'", ';
        $tuniu_data .= '"fromStationName": "'.$data['train']->DepartAirport_cn.'", ';
        $tuniu_data .= '"toStationCode": "'.$data['train']->ArrivalAirport.'", ';
        $tuniu_data .= '"toStationName": "'.$data['train']->ArrivalAirport_cn.'", ';
        $tuniu_data .= '"trainDate": "'.substr($data["train"]->DepartureDate, 0, 10).'", ';
        $tuniu_data .= '"callBackUrl": "http://www.mycht.cn/info.php/apps/train/tuniu_callback/book",';
        $tuniu_data .= '"hasSeat": true,';
        $tuniu_data .= '"contact": "陈宇超",';
        $tuniu_data .= '"phone": "18877381547",';
		$tuniu_data .= '"isChooseSeats": true,';
		$tuniu_data .= '"chooseSeats":"'.$selectseat.'",';
		
		//循环乘客
        $passengers = '';
        foreach ($data['people_list'] as $key => $item) {
            $passengers .= '{'; 
            $passengers .= '"passengerId":'.$key.',';
            $passengers .= '"ticketNo":"null",';
            //乘客姓名
            $passengersename = str_replace(' ','',$item->BPE_FirstName) . str_replace(' ','',$item->BPE_MiddleName) . str_replace(' ','',$item->BPE_LastName);
            //将特殊字符转换为正常字符以便于出票
			$passengersename = chk_sp_name($passengersename);
            $passengers .= '"passengerName":"'.$passengersename.'",';
            $passportseno = str_replace(' ','',$item->BPE_Passport);
            
            $passengers .= '"passportNo":"'.$passportseno.'",';

            //证件类型
			switch ($item->BPE_PassportType){
				case 'Chinese ID':
					$passporttypeseid = "1";
					$passporttypeseidname = "二代身份证";
					break;
				case 'MainlandTravel Permit from Hong Kong and Macau':
					$passporttypeseid = "C";
					$passporttypeseidname = "港澳通行证";
					break;
				case 'Travel Permit from Taiwan':
					$passporttypeseid = "G";
					$passporttypeseidname = "台湾通行证";
					break;
				default :
					$passporttypeseid = "B";
					$passporttypeseidname = "护照";
					break;
			}
			
			//乘客类型
            switch ($item->BPE_GuestType) {
                case 1:
                    $piaotype = 1;
                    $piaotypename = "成人票";
                    break;
                case 2:
                    $piaotype = 2;
                    $piaotypename = "儿童票";
                    break;
                default://外国人应该就两种票吧
                    $piaotype = 1;
                    $piaotypename = "成人票";
                    break;
            }
			
            $passengers .= '"passportTypeId":"'.$passporttypeseid.'",';
            $passengers .= '"passportTypeName":"'.$passporttypeseidname.'",';

            //票类型
            $passengers .= '"piaoType":"'.$item->BPE_GuestType.'",';
            $passengers .= '"piaoTypeName":"'.$piaotypename.'",';
            
            //座位类型piaoTypeName
            $passengers .= '"zwCode":"'.$zwcode.'",';
            $passengers .= '"zwName":"'.$zwname.'",';

            $passengers .= '"cxin":"null",';
            $passengers .= '"price":"'.$data['train']->adultcost.'",';
            $passengers .= '"reason": 0';
            $passengers .= '},';
        }   
		
		$passengers = substr($passengers,0,strlen($passengers)-1);
        $passengers = '['.$passengers.']';
        $tuniu_data .= '"passengers": '.$passengers.'}';
		
		//print_r($tuniu_data);
		
		$crypt = new DES();
		$mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY);
		$post_data = '{ 
            "apiKey": "'.TUNIU_KEY.'", 
            "sign": "'.create_sign().'", 
            "timestamp": "'.date('Y-m-d H:i:s',time()).'", 
            "data": "'.$mstr.'" 
        }';	
		
		$url = TUNIU_URL.'/train/book';	
		$book_back_json = GetPost_http($url,$post_data,'POST','json');	
		$book_back_data = json_decode($book_back_json);

		$orderId = $book_back_data->data->orderId;
		$retailOrderId = $book_back_data->data->retailOrderId;
		
		if($book_back_data->success == 1){
			$confirm_url = TUNIU_URL.'/train/confirm';
			$sign = 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"
				}
			}';	
			//请求出票
			$confirm_back_json = GetPost_http($confirm_url,$post_data,'POST','json');
			$confirm_back_data = json_decode($confirm_back_json);
			$reback["status"] = 1;
            $reback["order"] = $orderId;
            $reback["mes"] = "订单提交成功，等待回调";                  
        }else{ 
           // $reback["mes"] = $confirm_back_json;
           // $add_data->status = "e";
        }
		
		//本地订单入库
		$add_data = new stdClass();
		$add_data->cold_sn = $retailOrderId;
		$add_data->ordernumber = $orderId;
		$add_data->returncode = $confirm_back_data->returnCode;
		$add_data->status = '2';
		$add_data->errormsg = '预定中';
		$add_data->checi = $data['train']->FlightsNo;
		$add_data->fromstationame = $data['train']->DepartAirport_cn;
		$add_data->fromstationcode = $data['train']->DepartAirport;
		$add_data->tostationame = $data['train']->ArrivalAirport_cn;
		$add_data->tostationcode = $data['train']->ArrivalAirport;
		$add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate));
		$add_data->startime = date('H:i',strtotime($data['train']->DepartureTime));
		$add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime));
		$add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; 
		$add_data->channel = 'tuniu';
		$add_data->isauto = $this->isauto;
		
		$this->train_system_model->add_orders($add_data);
		echo json_encode($reback);
        return false;
	}
	
	//携程模块
	function ctripModel($data,$selectseat,$cold_sn){
		$zwcode = $this->db_train_zw[$data['train']->Aircraft]; //座位简码
        $zwname = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; //座位名称
		$microtime = get_microtime();
		$OrderNumber = SHUNTU_ORDERUSER.$microtime;  //自生成订单号

		//生成接口请求头参数
		$TimeStamp = date("Y-m-d H:i:s");
		$serviceName = "train.addTrainOrder"; //每个接口都有自己名称
		$companyId = COMPANYID;
		$key = CTRIPKEY;

		$strSign = $TimeStamp.$serviceName.$companyId.$key; //加密前的令牌
		$Sign = md5($strSign);
		$url = CTRIPURL."/addTrainOrder";

		//拼接发送的报文
		$PostData = new stdClass();

		$PostData->authentication = new stdClass();
		$PostData->authentication->timeStamp = $TimeStamp;
		$PostData->authentication->serviceName = $serviceName;
		$PostData->authentication->companyId = $companyId;
		$PostData->authentication->messageIdentity = $Sign;
		
		$PostData->trainOrderInfo = new stdClass();
		$PostData->trainOrderInfo->companyId = $companyId;
		$PostData->trainOrderInfo->orderType = 2;
		$PostData->trainOrderInfo->orderTicketType = 0;
		$PostData->trainOrderInfo->companyOrderId = $OrderNumber;	
		$PostData->trainOrderInfo->isReservationOrder = null;
		$PostData->trainOrderInfo->leakCutOffTime = null;
		
		$PostData->trainOrderInfo->orderInfo = new stdClass();
		$PostData->trainOrderInfo->orderInfo->orderTime = $TimeStamp;		
		$PostData->trainOrderInfo->orderInfo->ticketList['0'] = new stdClass();
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->fromStationName = $data['train']->DepartAirport_cn;
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->toStationName = $data['train']->ArrivalAirport_cn;
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->ticketTime = date('Y-m-d H:i',strtotime($data['train']->DepartureTime));
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->trainNo = $data['train']->FlightsNo;
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->allAcceptTrainNo = ''; //备选车次，抢票时必传
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->acceptDepartDates = ''; //备选日期，抢票时必传
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->arrivalDateTime = date('Y-m-d H:i',strtotime($data['train']->ArrivalTime));
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->ticketPrice = $data['train']->adultcost;
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->seatName = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]];
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->selectedSeat = $selectseat;
		$is_accept_standing = '';
		if($this->istanding == 'true'){
			$is_accept_standing = '无座';
		}
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->acceptSeat = $is_accept_standing;
		
		$AdultNum = 0;
		$ChildNum = 0;
		$i = 0;
		$passagersdata = array();
		foreach ($data['people_list'] as $PassagerInfo){
			//乘客类型
			switch ($PassagerInfo->BPE_GuestType) {
                case 1:
                    $PiaoType = 1;
                    $PiaoTypeName = "成人票";
					$AdultNum++;
                    break;
                case 2:
                    $PiaoType = 2;
                    $PiaoTypeName = "儿童票";
					$ChildNum++;
                    break;
                default://外国人应该就两种票吧
                    $PiaoType = 1;
                    $PiaoTypeName = "成人票";
                    break;
            }

			//证件类型
			switch ($PassagerInfo->BPE_PassportType){
				case 'Chinese ID':
					$PassportTypeseId = 1;
					$PassportTypeseidName = "二代身份证";
					break;
				case 'MainlandTravel Permit from Hong Kong and Macau':
					$PassportTypeseId = 7;
					$PassportTypeseidName = "回乡证";
					break;
				case 'Travel Permit from Hong Kong / Macau':
					$PassportTypeseId = 7;
					$PassportTypeseidName = "回乡证";
					break;
				case 'Travel Permit from Taiwan':
					$PassportTypeseId = 8;
					$PassportTypeseidName = "台湾通行证";
					break;
				default :
					$PassportTypeseId = 2;
					$PassportTypeseidName = "护照";
					break;
			}
			$passagersdata[$i] = new stdClass();
			$passagersdata[$i]->passengerType = $PiaoType;
			$passagersdata[$i]->certificateType = $PassportTypeseId;
			$passagersdata[$i]->certificateNo = des_encrypt($PassagerInfo->BPE_Passport,$key);;
			$passagersdata[$i]->certificateName = chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName);
			$passagersdata[$i]->birthday =date('Y-m-d',strtotime($PassagerInfo->BPE_BirthDate));
			$passagersdata[$i]->realName = chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName);
			$passagersdata[$i]->identityLimitDate = date('Y-m-d',strtotime($PassagerInfo->BPE_PassExpdate));
			$passagersdata[$i]->countryCode = "";
			$passagersdata[$i]->contactMobile = "";
			$passagersdata[$i]->contactEmail = "";
			if (!empty($PassagerInfo->BPE_Nationality)){
				 $regionCode =  $PassagerInfo->BPE_Nationality;
				 if ($regionCode =="TW" || $regionCode=="HK" || $regionCode=="MO"){
					$passagersdata[$i]->regionCode = "CN";
				 }
				 else if ($regionCode=="UK" || $regionCode=="GB"){
					$passagersdata[$i]->regionCode = "GB";  //英国传GB
				 
				 }else{
					$passagersdata[$i]->regionCode = $regionCode;   //国家简码 美国us ,中国cn
				 }
				
			}
			
			$i++;
		}
		
		//乘客人信息
		$PostData->trainOrderInfo->orderInfo->ticketList['0']->passengerList = $passagersdata;
		$PostData->trainOrderInfo->orderInfo->frontSeatFlag = 0;
		$PostData->trainOrderInfo->orderInfo->orderRemark = "";		
		
		$PostData->trainOrderInfo->contactUser = new stdClass();
		$PostData->trainOrderInfo->contactUser->contactUserId = '';
		$PostData->trainOrderInfo->contactUser->contactName = 'vivi';
		$PostData->trainOrderInfo->contactUser->companyId = $companyId;
		$PostData->trainOrderInfo->contactUser->countryCode = "86";
		$PostData->trainOrderInfo->contactUser->contactMobile = des_encrypt('18877331805',$key) ;


		$PostData->trainOrderInfo->extraService = new stdClass();
		$PostData->trainOrderInfo->extraService->noVerifyFlag = 1;
		$PostData->trainOrderInfo->extraService->lowerBerthFlag = 0;
		$PostData->trainOrderInfo->extraService->lowerBerthCount = 0;
		$PostData->trainOrderInfo->extraService->grabTicketRate = 1;
		
		//本地添加记录
		$add_data = new stdClass();
		$add_data->cold_sn = $cold_sn;
		$add_data->ordernumber = $OrderNumber;
		$add_data->returncode = '';
		$add_data->status = '2';
		$add_data->errormsg = '预定中';
		$add_data->checi = $data['train']->FlightsNo;
		$add_data->fromstationame = $data['train']->DepartAirport_cn;
		$add_data->fromstationcode = $data['train']->DepartAirport;
		$add_data->tostationame = $data['train']->ArrivalAirport_cn;
		$add_data->tostationcode = $data['train']->ArrivalAirport;
		$add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate));
		$add_data->startime = date('H:i',strtotime($data['train']->DepartureTime));
		$add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime));
		$add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; 
		$add_data->channel = 'ctrip';
		$add_data->isauto = $this->isauto;	
		//出票次数
		$countAuto = $this->train_system_model->get_autotimes($cold_sn);
		$add_data->ts_autotimes = $countAuto->countauto + 1; //出票次数+1
		$add_data->lanhaiData = ""; //途牛默认澜海数据为空

		//存储到数据库
		$this->train_system_model->add_orders($add_data);	
		
		// print_r(json_encode($PostData));
		// die();

		$ResponseJson = GetPost_http($url,json_encode($PostData,JSON_UNESCAPED_UNICODE),'json');		
		$ResponseData = json_decode($ResponseJson);

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

		//预定请求成功后执行支付
		if($ResponseData->returnCode == 1){
			//直接获取返回的需要支付的总价，不再计算订单总价
			//$total_price = $AdultNum * $data['train']->adultcost + $ChildNum * $data['train']->childcost;
			$total_price = $ResponseData->returnData->orderPayDetail->orderAmount;

			if ($total_price>0){
				log_message('error','下单成功返回信息：'.$ResponseJson);
				//执行支付
				$this->payorders($OrderNumber,$total_price);
				$reback["status"] = 1;
				$reback["order"] = $OrderNumber;
				$reback["mes"] = "订单提交成功，等待回调";
			}else{
				$reback["status"] = 1;
				$reback["returndata"] = $ResponseData;
				$reback["mes"] = "订单提交成功，但是返回的订单总价错误。无法完成支付";
			}

			

		}else{
			//log_message('error','下单失败提交数据记录：'.json_encode($PostData,JSON_UNESCAPED_UNICODE));

			$reback["mes"] = $ResponseJson;
            $add_data->status = "e";

			//更新订单
			$msgData = new stdClass();
			$msgData->bookcallback = $ResponseJson;
			$msgData->OrderStatus = "1";
			$msgData->ErrorMsg = $ResponseData->returnMessage;
			$msgData->ordernumber = $OrderNumber;
			$msgData->addOrderData = json_encode($PostData,JSON_UNESCAPED_UNICODE); //失败了记录提交的订单数据
			$this->train_system_model->update_orders_msg($msgData);

		}
			
		echo json_encode($reback,JSON_UNESCAPED_UNICODE);
	}
	
	//请求支付
	public function payorders($CtripOrder,$Price){
		if(empty($CtripOrder) && !is_numeric($Price)){
			exit('传参错误！');
		}

		//生成接口请求头参数
		$TimeStamp = date("Y-m-d H:i:s");
		$serviceName = "train.companyPayOrder"; //每个接口都有自己名称
		$companyId = COMPANYID;
		$key = CTRIPKEY;

		// /** 测试服务器 */
		// $companyId = "1503141150";
		// $key = "hajkrtba";

		$strSign = $TimeStamp.$serviceName.$companyId.$key; //加密前的令牌
		$Sign = md5($strSign);
		$url = CTRIPURL."/companyPayOrder";
	
		//生成报文
		$PostData = new stdClass();

		$PostData->authentication = new stdClass();
		$PostData->authentication->timeStamp = $TimeStamp;
		$PostData->authentication->serviceName = $serviceName;
		$PostData->authentication->companyId = $companyId;
		$PostData->authentication->messageIdentity = $Sign;
		
		$PostData->orderPayInfo= new stdClass();
		$PostData->orderPayInfo->companyId = $companyId;
		$PostData->orderPayInfo->companyOrderId = $CtripOrder;
		$PostData->orderPayInfo->payedPrice = $Price;
		$PostData->orderPayInfo->payTime = $TimeStamp;
		$PostData->orderPayInfo->tradeNumber = $CtripOrder;
		
		//$Url = 'http://apiproxy.ctrip.com/apiproxy/soa2/13680/PartnerPayOrder';

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

		
		$ResponseJson = GetPost_http($url,json_encode($PostData),'json');
		$ResponseData = json_decode($ResponseJson);

		$msgData = new stdClass();
		$msgData-> bookcallback = $ResponseJson;
		$msgData->ordernumber = $CtripOrder;	

		if ($ResponseData->returnCode==1){
			$msgData->OrderStatus = "3";
			$msgData->ErrorMsg = $ResponseData->returnMessage;
		}else{
			$msgData->OrderStatus = "1";
			$msgData->ErrorMsg = $ResponseData->returnMessage;
		}
		
		//更新订单
		$this->train_system_model->update_orders_msg($msgData);

		// $reback["mes"] = $ResponseJson;
		// print_r(json_encode($reback,JSON_UNESCAPED_UNICODE)) ;
		
		//echo '支付';
		//print_r($ResponseData);
		//支付同步回调信息 {"Status":"SUCCESS","PartnerName":"guilintravel","OrderNumber":"guilintravel1546071576","OperationDateTime":"2018-12-29 16:19:37","RetCode":0,"ResponseStatus":{"Timestamp":"\/Date(1546071577236+0800)\/","Ack":"Success","Errors":[],"Extension":[]}}
	}

	//澜海请求出票
	function lanhaiModel($data,$selectseat,$cold_sn,$bpe_sn){
		$microtime = get_microtime();
		$OrderNumber = SHUNTU_ORDERUSER.$microtime;  //自生成订单号

		//生成接口请求头参数
		$mainOrderId = $OrderNumber;
		$timestamp = $microtime;
		$appId = LANHAI_appId;
		$url = LANHAI_URL."api/open/push/order";

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

		//本地添加记录
		$add_data = new stdClass();
		$add_data->cold_sn = $cold_sn;
		$add_data->ordernumber = $OrderNumber;
		$add_data->returncode = '';
		$add_data->status = '2';
		$add_data->errormsg = '预定中';
		$add_data->checi = $data['train']->FlightsNo;
		$add_data->fromstationame = $data['train']->DepartAirport_cn;
		$add_data->fromstationcode = $data['train']->DepartAirport;
		$add_data->tostationame = $data['train']->ArrivalAirport_cn;
		$add_data->tostationcode = $data['train']->ArrivalAirport;
		$add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate));
		$add_data->startime = date('H:i',strtotime($data['train']->DepartureTime));
		$add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime));
		$add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; 
		$add_data->channel = 'lanhai';
		$add_data->isauto = $this->isauto;	
		//出票次数
		$countAuto = $this->train_system_model->get_autotimes($cold_sn);
		$add_data->ts_autotimes = $countAuto->countauto + 1; //出票次数+1

		//澜海数据
		$lanhaiData = new stdClass();
		$lanhaiData->selectseat = $selectseat;
		$lanhaiData->bpe_sn = $bpe_sn;
		$add_data->lanhaiData = json_encode($lanhaiData,JSON_UNESCAPED_UNICODE);

		//存储到数据库
		$this->train_system_model->add_orders($add_data);	

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

		$ResponseJson = GetPost_http($url,json_encode($PostData,JSON_UNESCAPED_UNICODE),'json');		
		$ResponseData = json_decode($ResponseJson);

		// print_r($ResponseJson);
		// die();

		//预定请求成功后执行支付
		if($ResponseData->code == 0 && $ResponseData->success){

		
			$reback["status"] = 1;
			$reback["order"] = $OrderNumber;
			$reback["mes"] = "订单提交成功，请等待澜海出票。在出票信息返回之前，千万不要改动汉特里面的订单数据，以免照成出票数据和订单数据不一致！！！！！".$ResponseData->msg ;

		}else{
			$reback["status"] = 0;
			$reback["order"] = $OrderNumber;
			$reback["mes"] = "订单提交失败，".$ResponseData->msg."。订单发送数据:".json_encode($PostData) ;
			
            $add_data->status = "e";

			//更新订单
			$msgData = new stdClass();
			$msgData->bookcallback = $ResponseJson;
			$msgData->OrderStatus = "1";
			if (isset($ResponseData->returnMessage)){
				$msg = $ResponseData->returnMessage;
			}else{
				$msg = "没有错误信息！";
			}
			$msgData->ErrorMsg = $msg;
			$msgData->ordernumber = $OrderNumber;
			$msgData->addOrderData = json_encode($PostData,JSON_UNESCAPED_UNICODE); //失败了记录提交的订单数据
			$this->train_system_model->update_orders_msg($msgData);

		}

		echo json_encode($reback,JSON_UNESCAPED_UNICODE);
	}
}


//订单提交返回数据
/*
{
    "returnCode": 1,
    "returnMessage": "SUCCESS",
    "returnData": {
        "serviceName": "train.addTrainOrder",
        "companyId": "1503141150",
        "companyOrderId": "HN1681460139569",
        "operationDateTime": "2023-04-14 16:15:56",
        "orderPayDetail": {
            "orderAmount": 12.00,
            "ticketAmount": 6,
            "serveAmount": 0,
            "extraServeFees": [
                {
                    "feeAmount": 6.00,
                    "feeType": 141
                }
            ]
        }
    },
    "ResponseStatus": {
        "Timestamp": "/Date(1681460156763+0800)/",
        "Ack": "Success",
        "Errors": [],
        "Build": null,
        "Version": null,
        "Extension": [
            {
                "Id": "CLOGGING_TRACE_ID",
                "Version": null,
                "ContentType": null,
                "Value": "7715658886832531034"
            },
            {
                "Id": "RootMessageId",
                "Version": null,
                "ContentType": null,
                "Value": "100031671-0a6d18d7-467072-1571193"
            }
        ]
    }
}

*/