<?php

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

//[{"ticket_no":"E855807446107001B","passengername":"陈斯坤","passporttypeseid":"1","passportseno":"450521199406098313"}]

class Auto extends CI_Controller{
    
    private $order_status_msg;//订单状态说明
    private $key;
    private $cx_api;//查询api
    private $dp_api;//订票api
    private $qxdd_api;//取消订单api
    private $pay_api;//请求出票，支付
    private $refund_api;//线上退票
    private $status_api;//状态查询
    private $code_zw;//座次信息
    private $piaotype;//票种信息
    private $passportty;//证件类型信息

    public function __construct() 
    {
        header("Content-Type: text/html;charset=utf-8");       
        parent::__construct();
        $this->config->load('config');
        $this->order_status_msg=$this->config->item('train_order_status_msg');
        $this->key=JUHE_TRAIN_API_KEY;
        $this->cx_api=JUHE_TRAIN_CX_API;
        $this->dp_api=JUHE_TRAIN_DP_API;
        $this->qxdd_api=JUHE_TRAIN_CANCEL_API;
        $this->pay_api=JUHE_TRAIN_PAY_API;
        $this->refund_api=JUHE_TRAIN_REFUND_API;
        $this->status_api=JUHE_TRAIN_STATUS_API;
        $this->code_zw=$this->config->item('train_zw');
        $this->piaotype=$this->config->item('train_piaotype');
        $this->passportty=$this->config->item('train_passportty');

        $this->load->model("BIZ_train_model");//加载模型 
    } 

   
    //用于自动出票,接收COLI_SN
    public function auto_pay_ticket(){
        date_default_timezone_set('Asia/Shanghai');
        // $coli_sn="473013018";
        $coli_sn = $this->input->post("coli_sn");
        $list=new StdClass;
        $back_data = 1;
        
        if(!empty($coli_sn)){
            $cold_sn=$this->BIZ_train_model->get_cold_sn($coli_sn);
            $coli_id = $this->BIZ_train_model->coli_sn_get_coli_id($coli_sn);
            $i = 0;
            $list->info=array();
            foreach ($cold_sn as $v) {
                if($v->COLD_SPFS > 1){
                    //寄送票
                    $back_data = 0;
                    break; 
                }
                $list->info[$i]=new StdClass;
                $list->info[$i]->people=$this->BIZ_train_model->biz_people($v->COLD_SN);
                $list->info[$i]->train=$this->BIZ_train_model->get_biz_foi($v->COLD_SN);
                $list->info[$i]->status=$this->BIZ_train_model->get_biz_jol($v->COLD_SN);

                if(count($list->info[$i]->people) > 5){
                    $back_data = 0;
                    break;
                };
                if((strtotime($list->info[$i]->train[0]->DepartureTime) - time())/3600 < 3 or (strtotime($list->info[$i]->train[0]->DepartureTime) - time())/24/3600 >29){
                    $back_data = 0;
                    break;
                }
                if($list->info[$i]->train[0]->adultcost > 1000){
                    $back_data = 0;
                    break; 
                }
                $i++;
            }
            if($back_data == 0){
                echo 0;
                return false;
            }else{
                foreach ($cold_sn as $v) {
                    $reback = $this->submit_juhe_order($v->COLD_SN,$coli_id[0]->COLI_ID);
                    if($reback["status"] && !empty($reback["order"])){
                        $back_data .= ",".$reback["order"];
                    }
                }
            }
            $back_data = substr($back_data, 2);
            if($back_data){ //这里 $back_data 还有可能没数据，所以判断一下
                echo $back_data;
            }else{
                echo 0;
            }
            return false;
        }

    }
    //根据汉特订单明细表SN来获取车次，乘客信息，拼接成聚合提交订单的url
    public function submit_juhe_order($cold_sn,$coli_id) {
        // $cold_sn=$this->input->get("order");
        
        $data = array();
        $reback=array();//返回数据
        $reback["status"]=0;
        $reback["mes"]="";
        // $reback["order"] = "123";
        // return $reback;die;
        if(!is_numeric($cold_sn)){
            $reback["mes"]="订单号是数字";
            echo json_encode($reback);
            return false; 
        }
        $data['train'] = $this->BIZ_train_model->biz_order_detail($cold_sn);
        if (empty($data['train'])) {
            //显示错误,找不到车次
            $reback["mes"]="找不到车次";
            echo json_encode($reback);
            return false;

        }

        $data['people_list'] = $this->BIZ_train_model->biz_people($cold_sn);
        if (empty($data['people_list'])) {
            //显示错误，找不到用户信息
            $reback["mes"]="找不到乘客信息";
            echo json_encode($reback);
            return false;
        }
        if (count($data['people_list']) > 5) {
            //显示错误，用户超过五个
            $reback["mes"]="乘客不能超过五个";
            echo json_encode($reback);
            return false;
        }

        $db_train_zw = $this->config->item('db_train_zw');
        $train_zw = $this->config->item('train_zw');

        $passengers='';
        foreach ($data['people_list'] as $key => $item) {
            $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码
            $zwname = $train_zw[$db_train_zw[$data['train']->Aircraft]]; //座位名称
            //乘客姓名
            $passengersename = trim($item->BPE_FirstName) . trim($item->BPE_MiddleName) . trim($item->BPE_LastName);
            //乘客类型
            switch ($item->BPE_GuestType) {
                case 1:
                    $piaotype = 1;
                    $piaotypename = "成人票";
                    break;
                case 2:
                    $piaotype = 2;
                    $piaotypename = "儿童票";
                    break;
                default://外国人应该就两种票吧
                    $piaotype = 1;
                    $piaotypename = "成人票";
                    break;
            }
            $passporttypeseid = "B"; //护照
            $passporttypeseidname = "护照";
            $passportseno = $item->BPE_Passport;
            $passengers.=',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '"}';
        }
        $passengers.="]";
        $passengers = substr($passengers, 1);
        $passengers = "[" . $passengers;
        $url=$this->dp_api;
        $post_data=array(
                "key"=>$this->key,
                "user_orderid"=>$cold_sn,//自定义订单号
                "train_date"=>substr($data["train"]->DepartureDate, 0, 10),
                "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
            );
        // $bakc_json=$this->post_data($url,$post_data);
        $bakc=json_decode($bakc_json);//json=>obj

        $add_data=new StdClass();
        $add_data->JOL_COLD_SN=(int)$cold_sn;
        
        $add_data->JOL_Status="0";
        $add_data->JOL_RebackMsg=$bakc->reason;
        $add_data->JOL_FromStation=$data["train"]->DepartAirport_cn;
        $add_data->JOL_ToStation=$data["train"]->ArrivalAirport_cn;
        $add_data->JOL_FromStationCode=$data["train"]->DepartAirport;
        $add_data->JOL_ToStationCode=$data["train"]->ArrivalAirport;
        $add_data->JOL_TrainCode=$data["train"]->FlightsNo;
        $add_data->JOL_BackTxt=$bakc_json;
        
        if(!$bakc->error_code){
            $add_data->JOL_JuheOrder=$bakc->result->orderid;
            $reback["status"]=1;
            $reback["order"]=$bakc->result->orderid;
            $reback["mes"]="订单提交成功，等待回调";
            $this->send_mail_to_wl("订单：{$coli_id} 提交成功","翰特订单号:{$coli_id} ;聚合订单号:{$bakc->result->orderid}");                             
        }else{ 
            $add_data->JOL_JuheOrder=null;
            $reback["mes"]= $bakc_json;
            $add_data->JOL_Status="e";
            $this->send_mail_to_wl("订单：{$coli_id} 提交失败","翰特订单号:{$coli_id}");
        }
        $add_back_data=$this->BIZ_train_model->add_biz_jol($add_data);
        
        return $reback;
    }   
    public function ticket_status($coli_sn="",$jh_id=""){
        if(empty($coli_sn)){
            $coli_sn = $this->input->get("sn");
        }
        if(empty($jh_id)){
            $jh_id = $this->input->get("reback");
        }
        if(empty($coli_sn) or empty($jh_id)){
            echo "error";
            return false; 
        }
        $jh_id = explode(",", $jh_id);
        
        $cold_sn = $this->BIZ_train_model->get_cold_sn($coli_sn);
        $cols_id = $this->BIZ_train_model->coli_sn_get_coli_id($coli_sn);
        if(empty($cold_sn)){
            echo "error";
            return false;
        }else{
            $list=new StdClass;
            $list->info=array();
            foreach ($cold_sn as $key => $v) {
                $list->info[$key]=new StdClass;
                $list->info[$key]->people=$this->BIZ_train_model->biz_people($v->COLD_SN);
                $list->info[$key]->train=$this->BIZ_train_model->get_biz_foi($v->COLD_SN);
                foreach ($jh_id as $jh_id_v) {            
                    $list->info[$key]->order_info = $this->BIZ_train_model->get_biz_jol_info($v->COLD_SN,$jh_id_v);
                    if(!empty($list->info[$key]->order_info)) break;
                }
            }
        }
        $list->cols_id = $cols_id[0]->COLI_ID;
        $this->load->view("ticket_status",$list);
    }
    //发邮件给外联
    public function send_mail_to_wl($subject,$body){
        $this->load->model("Sendmail_model");        
        $fromName  = "csk";
        $fromEmail = "csk@hainatravel.com";
        $toName = "ethel";
        $toEmail = "ethel@chinahighlights.com";
        $this->Sendmail_model->SendGuest($fromName,$fromEmail,$toName,$toEmail,$subject,$body);
    }
    //发邮件给客人
    public function send_mail_to_guest($coli_id,$jh_order){
        $this->load->model("Sendmail_model");        
        $guest = $this->BIZ_train_model->get_guest_info($coli_id);
        $fromName  = "sharon";
        $fromEmail = "sharon@chinahighlights.com";
        $toName = $guest[0]->GUT_LastName;
        $toEmail = $guest[0]->GUT_Email;
        $subject = "auto pay test $jh_order";
        $body = "csk test train ticket $jh_order";
        $this->Sendmail_model->SendGuest($fromName,$fromEmail,$toName,$toEmail,$subject,$body);
    }
    //
    public function sub_callback(){
        $data_post=$this->input->post();
        // $data_post["data"]='{"from_station_name":"桂林北","from_station_code":"GBZ","to_station_name":"柳州","to_station_code":"LZZ","train_date":"2017-01-05","orderid":"111111H","user_orderid":"488015272","orderamount":null,"ordernumber":null,"checi":"K457","msg":"没有余票","status":"4","passengers":[{"passengerid":1,"passengersename":"CSK","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E132124","price":"1","zwcode":"1","zwname":"硬座"},{"passengerid":2,"passengersename":"TW","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E02030609","price":"1","zwcode":"1","zwname":"硬座"}],"refund_money":null,"sign":"a5bc2ac8ef2b3a4c1bca323c3898e748"}';
        $data=json_decode($data_post["data"]);
        
        $this->load->model("order_people_model","op");
        $update_data=new StdClass();
        $update_data->JOL_BackTxt=$data_post["data"];
        $update_data->JOL_RebackMsg=$data->msg;
        $update_data->JOL_Status=$data->status;
        $update_data->JOL_JuheOrder=$data->orderid;
        $update_data->JOL_Price=$data->passengers[0]->price;

        $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($data->user_orderid);

        $add_train_order_data = new StdClass;
        if($data->status=="2"){
            $post_data=array(
                        "key"=>$this->key,
                        "orderid"=>$data->orderid
                            );
            $back_json=$this->my_post($this->pay_api,$post_data);
            $back=json_decode($back_json);
            $update_data->JOL_BackTxt=$back_json;
            $update_data->JOL_RebackMsg=$back->reason;
        }elseif($data->status=="4"){
            //付款成功 写入TOC表
            $add_train_order_data->TOC_Memo=$data->orderid;
            $add_train_order_data->TOC_COLD_SN=$data->user_orderid;
            $add_train_order_data->TOC_TrainNumber=$data->checi;
            $add_train_order_data->TOC_DepartureDate=$data->train_date;
            $add_train_order_data->TOC_TicketCost=$data->orderamount;
            $add_train_order_data->poundage=(count($data->passengers)*2)."";//手续费，每人两块，转换成字符串
            $add_train_order_data->FOI_TrainNetOrderNo=$data->ordernumber;
            $this->op->add_train_order($add_train_order_data);   
            $this->send_mail_to_wl("订单:{$coli_id[0]->COLI_ID} 出票成功","翰特订单号:{$coli_id[0]->COLI_ID};聚合订单号:{$data->orderid}");
            $this->send_mail_to_guest($coli_id[0]->COLI_ID,$data->orderid);                      
        }elseif($data->status=="7"){
            //退票成功 写入TOC表
            $newtime="";//记录最新操作时间
            $refund_passportseno="";//退票人护照号
            $refund_money="";//退票金额
            foreach ($data->passengers as $p) {
                //找出退票人，规则：操作时间最新的
                if($p->refundTimeline){//是否有退票操作
                    //$p->refundTimeline[count($p->refundTimeline)-1] 最新操作
                    if($p->refundTimeline[count($p->refundTimeline)-1]->time > $newtime){
                        $newtime=$p->refundTimeline[count($p->refundTimeline)-1]->time;
                        $refund_passportseno=$p->refundTimeline[count($p->refundTimeline)-1]->detail->passportseno;
                        $refund_money=$p->refundTimeline[count($p->refundTimeline)-1]->detail->returnmoney;
                    }
                }
            }
            $add_train_order_data->TOC_Memo=$data->orderid." ".$refund_passportseno;
            $add_train_order_data->TOC_COLD_SN=$data->user_orderid;
            $add_train_order_data->TOC_TrainNumber=$data->checi;
            $add_train_order_data->TOC_DepartureDate=$data->train_date;
            $add_train_order_data->TOC_TicketCost=-$refund_money;
            $add_train_order_data->FOI_TrainNetOrderNo=null;//退票不用更新取票号，以此在模型里面判断是否为退票消息
            $this->op->add_train_order($add_train_order_data);
        }else{
            $this->send_mail_to_wl("订单:{$coli_id[0]->COLI_ID} 出票失败","翰特订单号:{$coli_id[0]->COLI_ID};聚合订单号:{$data->orderid};返回信息:{$data->msg}");
        }
                
        
        $this->op->update_jh_order($update_data);
        echo "success";
    }
 


    function my_post($url,$post_data){
        // $url = "http://op.juhe.cn/trainTickets/cityCode";
        // $post_from = array("stationName" => $from,"key"=>"79f03107b921ef31310bd40a1415c1cb");
        // $post_to = array("stationName" => $to,"key"=>"79f03107b921ef31310bd40a1415c1cb");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        
        curl_close($ch);
        
        $output=json_decode($output,TRUE);//json => array
        return  $output;     
    }
    function get_data($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    function post_data($url,$post_data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        
        curl_close($ch);
        
        // $output=json_decode($output,TRUE);//json => array
        return  $output;     
    }

}