<?php

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

class Tuniu_train extends CI_Controller{
	
	private $order_status_msg;//订单状态说明
	
	public function __construct(){
        parent::__construct();
        //header("Content-Type: text/html;charset=utf-8");
        $this->load->library('Des');
		$this->load->model("tuniu_model");
		$this->load->model("order_people_model","op");
    }
    

	//途牛出票页面
	public function index(){
		$cols_id=$this->input->post("ht_order");
		$list=new StdClass;
		if(!empty($cols_id)){
            $cold_sn=$this->tuniu_model->get_biz_cold($cols_id);
            $list->wl=$this->tuniu_model->get_operatorinfo($cols_id);
            $i=0;
            $list->info=array();
            foreach ($cold_sn as $v) {
                $list->info[$i]=new StdClass;
                $list->info[$i]->people=$this->tuniu_model->biz_people($v->COLD_SN);
                $list->info[$i]->train=$this->tuniu_model->get_biz_foi($v->COLD_SN);
                $list->info[$i]->status=$this->tuniu_model->get_biz_jol($v->COLD_SN);
                $i++;
            }
            $list->cols_id=$cols_id;
        }
		$this->load->view('bootstrap3/header');
        $this->load->view('tuniu/ht_train_order_info',$list);
        $this->load->view('bootstrap3/footer'); 
	}
	
	//订单列表
    public function ht_order_list(){
        $page_size=10;
        $page=$this->input->get("page");
        $order=$this->input->get("order");
        $where="1=1";//搜索条件
        $page_parameter="";//返回的分页条件参数
        if(empty($page) or !is_numeric($page)){
            $page=0;
        }
        if(!empty($order)){
            $where="Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_ID='{$order}' OR tol_orderId='{$order}'";
            $list["order"]=$order;
            $page_parameter="order=".$order."&";
        }
        $data=$this->tuniu_model->get_order($page_size,$page,$where);
		
        $list["data"]=$data->list;
        
        $this->load->library('pagination');

        $config['base_url'] = site_url("/apps/train/tuniu_train/ht_order_list?{$page_parameter}");
        $config['total_rows'] = $data->count;
        $config['per_page'] = $page_size;
        $config['page_query_string']=TRUE;
        $config['query_string_segment']="page";
        $config['cur_tag_open'] = '<li class="active"><a href="#">';        
        $config['cur_tag_close'] = '</a></li>';
        $config['first_tag_open']=$config['last_tag_open']=$config['next_tag_open']=$config['prev_tag_open']=$config['num_tag_open']="<li>";
        $config['first_tag_close']=$config['last_tag_close']=$config['next_tag_close']=$config['prev_tag_close']=$config['num_tag_close']="</li>";

        $this->pagination->initialize($config);
		
        $list["page_link"]=$this->pagination->create_links();

        foreach ($list["data"] as $key => $value) {
			if($value->tol_Status == '2'){
				$value->info='预定'.$value->tol_errorMsg;//普通出票
			}else if($value->tol_Status == '4'){
				$value->info='出票'.$value->tol_errorMsg;//普通出票
			}else if($value->tol_Status == '7'){
				$value->info='退票'.$value->tol_errorMsg;//普通出票和抢票通用
			}else if($value->tol_Status == '8'){
				$value->info='抢票'.$value->tol_errorMsg;//取消抢票
			}else if($value->tol_Status == '9'){
				if($value->tol_returnCode == 231000){
					$value->info='抢票成功';//抢票执行结果
				}else{
					$value->info=$value->tol_errorMsg;//抢票执行结果
				}
			}elseif($value->tol_Status == '6'){
				$value->info='抢票中';//抢票
			}elseif($value->tol_Status == '0'){
				$value->info=$value->tol_errorMsg;//站位
			}else{
				$value->info = '';
			}
            
        }  
                   
        $this->load->view('bootstrap3/header');
        $this->load->view('/tuniu/ht_order_list.html',$list);
        $this->load->view('bootstrap3/footer');
    }
	
	
    //选择乘客出票（一个或多个，不超过5个）
	public function get_sn_submit_tuniu() {
        $cold_sn = $this->input->get("order");
        $bpe_sn = $this->input->get("people");
        $coli_id = $this->input->get('coli_id');
		$selectseat = $this->input->get("selectseat");
		
        $data = array();
        $rebakc = array();//返回数据
        $rebakc["status"]=0;
        $rebakc["mes"]="";
        if(!is_numeric($cold_sn)){
            $rebakc["mes"]="订单号是数字";
            echo json_encode($rebakc);
            return false; 
        }
        if(empty($bpe_sn)){
            $rebakc["mes"]="请选择乘客";
            echo json_encode($rebakc);
            return false; 
        }

        $data['train'] = $this->tuniu_model->biz_order_detail($cold_sn);
		$data['people_list'] = $this->tuniu_model->in_bpesn_people_info($bpe_sn);
        //$data['operator'] = $this->BIZ_train_model->get_operatorinfo($coli_id);

        if (empty($data['train'])) {
            //显示错误,找不到车次
            $rebakc["mes"]="找不到车次";
            echo json_encode($rebakc);
            return false;

        }
        if (empty($data['people_list'])) {
            //显示错误，找不到用户信息
            $rebakc["mes"]="找不到乘客信息";
            echo json_encode($rebakc);
            return false;
        }

        if (count($data['people_list']) > 5) {
            //显示错误，用户超过五个
            $rebakc["mes"]="乘客不能超过五个";
            echo json_encode($rebakc);
            return false;
		}
		
        $db_train_zw = $this->config->item('db_train_zw');
        $train_zw = $this->config->item('train_zw');
        $ticketype = $this->config->item('train_piaotype');
        $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码
        $zwname = $train_zw[$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 = $this->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 'Travel Permit from Hong Kong / 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":"'.$ticketype[$item->BPE_GuestType].'",';
            
            //座位类型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);
		//die();
        $crypt = new DES();
        $mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY);
        $post_data = '{ 
            "apiKey": "'.TUNIU_KEY.'", 
            "sign": "'.$this->create_sign().'", 
            "timestamp": "'.date('Y-m-d H:i:s',time()).'", 
            "data": "'.$mstr.'" 
            }';	
        
        $url = TUNIU_URL.'/train/book';
        $back_json = $this->get_http($url,$post_data,'POST');
        $back = json_decode($back_json);//json=>obj
		//print_r($back_json);
        if($back->success == 1){
            $rebakc["mes"]="订单提交成功，等待回调";                             
        }else{ 
            $rebakc["mes"]= $bakc_json;
        }
		$add_data=new StdClass();
		$add_data->tol_retailOrderId = $cold_sn;
		if(isset($back->data->orderId)){
			$add_data->tol_orderId = $back->data->orderId;
		}else{
			$add_data->tol_orderId = '';
		}
		$add_data->tol_status = '0';
		$add_data->tol_fromStationName = $data['train']->DepartAirport_cn;
		$add_data->tol_fromStationCode = $data['train']->DepartAirport;
		$add_data->tol_toStationName = $data['train']->ArrivalAirport_cn;
		$add_data->tol_toStationCode = $data['train']->ArrivalAirport;
		$add_data->tol_errorMsg = $back->errorMsg;
		$add_data->tol_cheCi = $data['train']->FlightsNo;
		$isauto = false;
		
		$add_back_data=$this->tuniu_model->tuniu_add_biz_jol($add_data,$isauto);
		
		echo json_encode($rebakc);
		return false;
    }
    
    //取消占座
    public function cancel_book($retailOrderId,$orderId){
        $url = TUNIU_URL.'/train/cancel';
        $sign = $this->create_sign();
        $time = date('Y-m-d H:i:s',time());
		$crypt = new DES();
		$tuniu_data = '{
                    "retailOrderId":"'.$retailOrderId.'",
                    "orderId":"'.$orderId.'",
                    "callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/cancelbook"
                     }';
        $mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY);
        $post_data = '{ 
                "apiKey": "'.TUNIU_KEY.'", 
                "sign": "'.$sign.'", 
                "timestamp": "'.$time.'", 
                "data": "'.$mstr.'"
                }';	
		
        $back_data = $this->get_http($url,$post_data,'POST');
        print_r($back_data);
    }

    //确认出票
    public function confirm_ticket($retailOrderId=null,$orderId=null){
        $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 = $this->get_http($url,$post_data,'POST');
        
        print_r($back_data);
	}
    
	//退票接口
	public function cancel_ticket($retailOrderId,$orderId,$ticketNo=null){
		$url = TUNIU_URL.'/train/return';
		$sign = $this->create_sign();
		$time = date('Y-m-d H:i:s',time());
		$obj = $this->tuniu_model->get_tuniuorder_info($retailOrderId,$orderId);
		$info = json_decode($obj[0]->tol_booktxt);
		$orderNumber = $info->orderNumber;
		$str = '[';
		foreach($info->passengers as $item){
			if(empty($ticketNo)){
				$str .='{';
				$str .= '"ticketNo":"'.$item->ticketNo.'",';
				$str .= '"passengerName":"'.$item->passengerName.'",';
				$str .= '"passportTypeId":"'.$item->passportTypeId.'",';
				$str .= '"passportNo":"'.$item->passportNo.'"';
				$str .= '},';
			}else{
				if($item->ticketNo == $ticketNo){
					$str .='{';
					$str .= '"ticketNo":"'.$item->ticketNo.'",';
					$str .= '"passengerName":"'.$item->passengerName.'",';
					$str .= '"passportTypeId":"'.$item->passportTypeId.'",';
					$str .= '"passportNo":"'.$item->passportNo.'"';
					$str .= '},';
				}
			}
			
		}
		$str = substr($str,0,strlen($str)-1);
		$str .= ']';
		$data = '{
					"retailOrderId": "'.$retailOrderId.'",
					"orderId": "'.$orderId.'",
					"orderNumber": "'.$orderNumber.'",
					"callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/return_ticket",
					"tickets":'.$str.'
				  }';
		$crypt = new DES();
		$mstr = $crypt->encrypt($data,TUNIU_KEY);	  
		$post_data = '{ 
				"apiKey": "'.TUNIU_KEY.'", 
				"sign": "'.$sign.'", 
				"timestamp": "'.$time.'", 
				"data": "'.$mstr.'"
				}';	
		$back_data = $this->get_http($url,$post_data,'POST');
		
		print_r($back_data);
	}
	
	//获取途牛订单信息
	public function order(){
		$retailOrderId=$this->input->get("retailOrderId");
		$orderId=$this->input->get("orderId");
        if($retailOrderId && $orderId){
			$url = TUNIU_URL.'/train/orderStatusQuery';
			$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.'"
					}
                }';	
			$back_json = $this->get_http($url,$post_data,'POST');
			//获取异步回调信息
			$grab_callback = $this->tuniu_model->get_tuniuorder_info($retailOrderId,$orderId);
			$back_data = json_decode($back_json);
			//print_r($back_data);
			$back_data->grab_callback = $grab_callback[0]->tol_booktxt;
			//print_r($back_data);
			$this->load->view('bootstrap3/header');
			$this->load->view('tuniu/order',$back_data);
			$this->load->view('bootstrap3/footer'); 
        }else{
			exit('订单信息不完整');
		}
    }
	
	//抢票页面
	public function grab_index(){
		$cols_id=$this->input->post("ht_order");
		$list=new StdClass;
		if(!empty($cols_id)){
            $cold_sn=$this->tuniu_model->get_biz_cold($cols_id);
            $list->wl=$this->tuniu_model->get_operatorinfo($cols_id);
            $i=0;
            $list->info=array();
            foreach ($cold_sn as $v) {
                $list->info[$i]=new StdClass;
                $list->info[$i]->people=$this->tuniu_model->biz_people($v->COLD_SN);
                $list->info[$i]->train=$this->tuniu_model->get_biz_foi($v->COLD_SN);
                $list->info[$i]->status=$this->tuniu_model->get_biz_jol($v->COLD_SN);
                $i++;
            }
            $list->cols_id=$cols_id;
        }
		$this->load->view('bootstrap3/header');
        $this->load->view('tuniu/grabTicketBook',$list);
        $this->load->view('bootstrap3/footer'); 
	}
	
	//抢票接口
	public function grabTicketBook(){
		$cold_sn = $this->input->get("order");
        $bpe_sn = $this->input->get("people");
        //$coli_id = $this->input->get('coli_id');
		$deadline = $this->input->get('deadline');
		$alternate_train = $this->input->get('alternate_train');
		$alternate_seat = $this->input->get('alternate_seat');
		
        $data = array();
        $rebakc = array();//返回数据
        $rebakc["status"]=0;
        $rebakc["mes"]="";
        if(!is_numeric($cold_sn)){
            $rebakc["mes"]="订单号是数字";
            echo json_encode($rebakc);
            return false; 
        }
        if(empty($bpe_sn)){
            $rebakc["mes"]="请选择乘客";
            echo json_encode($rebakc);
            return false; 
        }
		if(empty($deadline)){
            $rebakc["mes"]="请填写截止日期";
            echo json_encode($rebakc);
            return false; 
        }
		
	
        $data['train'] = $this->tuniu_model->biz_order_detail($cold_sn);
		$data['people_list'] = $this->tuniu_model->in_bpesn_people_info($bpe_sn);
        //$data['operator'] = $this->BIZ_train_model->get_operatorinfo($coli_id);

        if (empty($data['train'])) {
            //显示错误,找不到车次
            $rebakc["mes"]="找不到车次";
            echo json_encode($rebakc);
            return false;

        }
        if (empty($data['people_list'])) {
            //显示错误，找不到用户信息
            $rebakc["mes"]="找不到乘客信息";
            echo json_encode($rebakc);
            return false;
        }

        if (count($data['people_list']) > 5) {
            //显示错误，用户超过五个
            $rebakc["mes"]="乘客不能超过五个";
            echo json_encode($rebakc);
            return false;
		}
		
        $db_train_zw = $this->config->item('db_train_zw');
        $train_zw = $this->config->item('train_zw');
        $ticketype = $this->config->item('train_piaotype');
        $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码
        $zwname = $train_zw[$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 .= '"deadLine": "'.$deadline.'", ';
		$tuniu_data .= '"reserveCheCi": null, ';
		$tuniu_data .= '"reserveZwCode": null, ';
		$tuniu_data .= '"hasSeat": true,';
        //$tuniu_data .= '"callBackUrl": "http://www.mycht.cn/info.php/apps/train/tuniu_callback/book",';
        $tuniu_data .= '"contact": "陈宇超",';
        $tuniu_data .= '"phone": "18877381547",';
		$tuniu_data .= '"grabType": "1",';
		$tuniu_data .= '"grabFrequency": "common",';
		$tuniu_data .= '"grabQueue": "common",';
		$tuniu_data .= '"grabEntryway": "single",';
		
        //循环乘客
        $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 = $this->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 'Travel Permit from Hong Kong / Macau':
					$passporttypeseid = "C";
					$passporttypeseidname = "港澳通行证";
					break;
				case 'Travel Permit from Taiwan':
					$passporttypeseid = "G";
					$passporttypeseidname = "台湾通行证";
					break;
				default :
					$passporttypeseid = "B";
					$passporttypeseidname = "护照";
					break;
			}
			
			
            $passengers .= '"passportTypeId":"'.$passporttypeseid.'",';
            $passengers .= '"passportTypeName":"'.$passporttypeseidname.'",';

            //票类型
            $passengers .= '"piaoType":"'.$item->BPE_GuestType.'",';
            $passengers .= '"piaoTypeName":"'.$ticketype[$item->BPE_GuestType].'",';
            
            //座位类型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.'}';
		
        $crypt = new DES();
        $mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY);
        $post_data = '{ 
            "apiKey": "'.TUNIU_KEY.'", 
            "sign": "'.$this->create_sign().'", 
            "timestamp": "'.date('Y-m-d H:i:s',time()).'", 
            "data": "'.$mstr.'" 
            }';	
        
        $url = TUNIU_URL.'/train/grabTicketBook';
		
        $back_json=$this->get_http($url,$post_data,'POST');
        $back=json_decode($back_json);//json=>obj
		log_message('error','抢票预定同步:'.$back_json);
        if($back->success == 1){
            $rebakc["mes"]="订单提交成功，等待回调";                             
        }else{ 
            $rebakc["mes"]= $bakc_json;
        }
		$add_data=new StdClass();
		$add_data->tol_retailOrderId = $back->data->retailOrderId;
		if(isset($back->data->orderId)){
			$add_data->tol_orderId = $back->data->orderId;
		}else{
			$add_data->tol_orderId = '';
		}
		
		$add_data->tol_fromStationName = $data['train']->DepartAirport_cn;
		$add_data->tol_fromStationCode = $data['train']->DepartAirport;
		$add_data->tol_toStationName = $data['train']->ArrivalAirport_cn;
		$add_data->tol_toStationCode = $data['train']->ArrivalAirport;
		$add_data->tol_cheCi = $data['train']->FlightsNo;
 		$add_data->tol_status = '6';
		$isauto = false;	
		$add_back_data=$this->tuniu_model->tuniu_add_biz_jol($add_data,$isauto);
		print_r($back);
		echo $cold_sn;
		echo json_encode($rebakc);
		return false;
		
	}
	
	//取消抢票
	public function cancelgrabTicket($retailOrderId,$orderId){
		$url = TUNIU_URL.'/train/cancelGrabTicket';
        $sign = $this->create_sign();
        $time = date('Y-m-d H:i:s',time());
		$tuniu_data = '{
					"orderId":"'.$orderId.'",
                    "retailOrderId":"'.$retailOrderId.'",
					"userName":null,
					"userPassword":null
                     }';
		
		$crypt = new DES();
		$mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY);
		
		$post_data = '{ 
                "apiKey": "'.TUNIU_KEY.'", 
                "sign": "'.$sign.'", 
                "timestamp": "'.$time.'", 
                "data": "'.$mstr.'" 
                }';	
        $back_data = $this->get_http($url,$post_data,'POST');
        print_r($back_data);
	}
	
	//导出途牛账单
	public function export(){
		$this->load->model("BIZ_train_model");//加载模型
		$trackcode = $this->BIZ_train_model->getTrackingCode();
		$record = $this->tuniu_model->get_transaction_record();
		/*print_r($record);
		die();*/
		//创建一个数组进行数据格式化
		$r_info = array();
		
		foreach ($record as $item){
			if(empty($item->tne_ordernumber)){
				continue;
			}
			//print_r($item);
			//订单时间
			$r_info[0] = $item->tne_jydate;
			//订单操作类型(分为付款和收款)
			$r_info[1] = $item->tne_jytype;
			//途牛订单号
			$r_info[2] = $item->tne_ordernumber;
			//订单交易金额
			if($item->tne_jytype == '付款'){
				$r_info[3] = '-'.$item->tne_jyprice;
			}else{
				$r_info[3] = $item->tne_jyprice;
			}
			//获取订单cold_sn
			$order_info = $this->tuniu_model->get_order_info($item->tne_ordernumber);
			//echo $item->tne_ordernumber.'////';
			//print_r($order_info);
			$obj = explode('_',$order_info[0]->tol_retailOrderId);
			$cold_sn = $obj[0];
			//获取订单coli_Id
			$order_obj = $this->tuniu_model->get_coli_id($cold_sn);
			//print_r($coli_id);
			$coli_id = $order_obj[0]->COLI_ID;
			$coli_sn = $order_obj[0]->COLI_SN;
			//echo $coli_id[0]->coli_id;
			//$coli_sn = $coli_id[0]->coli_sn;
			//echo $coli_id[0]->coli_sn;;
			$this->BIZ_train_model->linkTrackingCode($coli_sn,$trackcode);
			//获取团号
			$gri_no = $this->tuniu_model->get_gri_no($coli_id);//团名
			if($gri_no){
				$r_info[4] = $gri_no[0]->GRI_No;
			}
			//获取外联名
			$wl_name = $this->tuniu_model->get_operatorinfo($coli_id);	
			if($wl_name){
				$r_info[5] = $wl_name[0]->OPI_Name;
			}
			$r_info['trackcode'] = $trackcode;
			$arr[]=$r_info;
			
		}
		
		header("Content-type:application/vnd.ms-excel;charset=utf-8");
		header("Content-Disposition:attachment;filename=tuniu_train.xls");
		$string_r= $this->load->view("tuniu/train_transaction_excel",array("arr"=>$arr),TRUE);
		echo $string_r;die;
	}
	
	//发送请求函数
	public function get_http($url, $data = '', $method = 'GET') {
        $curl = curl_init(); // 启动一个CURL会话  
		curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址  
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查  
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在  
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器  
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转  
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer  
		if ($method == 'POST' && !empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求  
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
			curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json;charset=UTF-8'));
		}
		curl_setopt($curl, CURLOPT_TIMEOUT, 45); // 设置超时限制防止死循环  
		curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容  
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回  
		$tmpInfo = curl_exec($curl); // 执行操作  
		$errno = curl_errno($curl);
		if ($errno !== 0) {
			return false;
			echo $errno . curl_error($curl); //记录错误日志
		}
		curl_close($curl); //关闭CURL会话  
		return $tmpInfo; //返回数据
    }
    
    function vpost($url,$data){ // 模拟提交数据函数  
        $curl = curl_init(); // 启动一个CURL会话  
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址  
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在  
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器  
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转  
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer  
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求  
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包  
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环  
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容  
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回  
        $tmpInfo = curl_exec($curl); // 执行操作  
        if (curl_errno($curl)) {  
           $tmpInfo = 'Errno'.curl_error($curl);//捕抓异常  
        }  
        curl_close($curl); // 关闭CURL会话  
        return $tmpInfo; // 返回数据  
    }  

    //国际姓名特殊字符转换
	function chk_sp_name($name){
		$name = str_replace(
         array('á', 'é', 'í', 'ó', 'ú', 'ñ', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Ñ'),
         array('a', 'e', 'i', 'o', 'u', 'n', 'A', 'E', 'I', 'O', 'U', 'N'),
         $name
		);
		return substr(strtoupper($name),0,30);
    }
    
    //途牛接口创建请求签名
	public function create_sign(){
		$time = date('Y-m-d H:i:s',time());
		$secretKey = 'qvHMJVywEQqsd4EneHQl';
		$id = 'retailId25';
		$timeStamp = 'timestamp'.$time;
		$sign = $secretKey.$id.'apiKey'.TUNIU_KEY.$timeStamp.$secretKey;
		return strtoupper(md5($sign));
	}
}   