<?php

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

/** 
 * 
 * 国内机票api
 * 
 */
class Flighttool extends CI_Controller {

    public $FlightNO_OBJ; //机票数据
    public $FDNO_OBJ;     //机票价格折扣
    private $cache_adapter = 'wincache'; //缓存driver

    public function __construct() {
        parent::__construct();
        $this->load->library('Flightapi');
        set_time_limit (0);
        //$this->output->enable_profiler(TRUE);
    }

    //$form_city    起飞城市三字码 如：SHA
    //$to_city      抵达城市三字码 如：BJS
    //$flight_date  起飞日期  格式“2015-01-25”
    //$search_price 查询价格折扣标识 0：航班查询  1：返回价格折扣缓存
    //$trip_type    往返标识 1：单程  2：往返  3：联程
    //$return_date  返程日期  格式“2015-01-25”
    public function ota_flight($form_city,$to_city,$flight_date,$search_price=0,$trip_type='1',$return_date=false) 
    {
        $form_city=strtoupper($form_city);
        $to_city=strtoupper($to_city);
        $flight_date=date('Y-m-d',strtotime($flight_date));
        $return_date!=false? $return_date = date('Y-m-d',strtotime($return_date)) : NULL;
        
        //返回缓存的价格,不再执行查询操作
        $this->load->driver('cache', array('adapter' => $this->cache_adapter, 'backup' => 'file'));
        $cache_id = md5(strtotime($flight_date).'_'.strtolower($form_city).'_'.strtolower($to_city).'_'.strtolower($trip_type).'_'.mb_strtolower($return_date));
        if ($search_price==1) {
            if ($f_cache = $this->cache->get($cache_id)){
                echo json_encode($f_cache);
                return;
            }
        }

        //如果传进来的是机场三字码，则在语言包里查询所属城市三字码
        $DepartPort=$ArrivePort=false;
        $org_form_city=$form_city;
        $org_to_city=$to_city;
        $this->lang->load('city_code', 'english');
        $citycode = $this->lang->line('city_code');
        //根据机场三字码获取城市三字码，一同传递给携程接口
        if (isset($citycode["$form_city"]) && $citycode["$form_city"]!=$form_city) {
            $DepartPort=$form_city;
            $form_city=$citycode["$form_city"];
        }
        if (isset($citycode["$to_city"]) && $citycode["$to_city"]!=$to_city) {
            $ArrivePort=$to_city;
            $to_city=$citycode["$to_city"];
        }

        if ($form_city=='HKG' or $form_city=='MFM' or $to_city=='HKG' or $to_city=='MFM') {
            $result=$this->get_international_flight($form_city,$to_city,$flight_date,false);
            //获取返程数据
            if ($result!=false && $return_date!=false) {
                $result2 = $this->get_international_flight($to_city,$form_city,$return_date,false);
                $result->FlightNO = array_merge($result->FlightNO,$result2->FlightNO);
                $result->FDNO = array_merge($result->FDNO,$result2->FDNO);
            }
        }
        else
        {
            $result=$this->get_data_by_ctrip($form_city,$to_city,$flight_date,$trip_type,$return_date,$DepartPort,$ArrivePort);
            //若去携程没有返回数据，则抓取艺龙的接口数据
            if (!$result) 
            {
                $result=$this->get_data_by_elong($form_city,$to_city,$flight_date);
                //获取返程数据
                if ($return_date!=false) {
                    $result2 = $this->get_data_by_elong($to_city,$form_city,$return_date);
                    $result->FlightNO = array_merge($result->FlightNO,$result2->FlightNO);
                    $result->FDNO = array_merge($result->FDNO,$result2->FDNO);
                }
            }
        }

        //若查询的是半年内数据则调用携程接口，否则调用去哪儿的接口。
        //去哪儿接口严重不稳定
        /*$date_bound=$flight_date;
        if ($return_date) $date_bound=$return_date;
        $date_bound=strtotime($date_bound);
        $max_date_bound=time()+160*24*60*60;
        
        //调用去哪儿接口获取航班数据
        if ($date_bound>$max_date_bound) 
        {
            //获取去哪儿机票数据,去哪儿使用的是机场三字码，不是城市三字码
            $api_method="get_data_by_qunar";
            $result=$this->get_data_by_qunar($org_form_city,$org_to_city,$flight_date);
            if (empty($result->FlightNO)) {
                //若去哪儿没有返回数据，则抓取艺龙的接口数据
                $result=$this->get_data_by_elong($form_city,$to_city,$flight_date);
                $api_method="get_data_by_elong";
            }
            //获取返程数据
            if ($return_date!=false) {
                if($api_method=="get_data_by_qunar"){
                    $form_city=$org_form_city;
                    $to_city=$org_to_city;
                }
                $result2 = $this->$api_method($to_city,$form_city,$return_date);
                $result->FlightNO = array_merge($result->FlightNO,$result2->FlightNO);
                $result->FDNO = array_merge($result->FDNO,$result2->FDNO);
            }
        }
        //调用携程接口获取航班数据
        else
        {
            $result=$this->get_data_by_ctrip($form_city,$to_city,$flight_date,$trip_type,$return_date,$DepartPort,$ArrivePort);
        }*/
		
		$datass=array();
        foreach ($result->FDNO as $v) {
            $datass[]=$v;
        }
        $result->FDNO=$datass;

        $FlightNO_OBJ->FlightNO = $result->FlightNO;
        $FDNO_OBJ->FDNO = $result->FDNO;
        //缓存价格折扣数据
        $this->cache->save($cache_id,$FDNO_OBJ,60*10);

        if ($search_price==1) {
            echo json_encode($FDNO_OBJ);
        }elseif($search_price==0){
            echo json_encode($FlightNO_OBJ);
        }else{
            echo json_encode($result);
        }
    }

    public function get_data_by_ctrip($form_city,$to_city,$flight_date,$trip_type,$return_date,$DepartPort,$ArrivePort) 
    {
        //单程
        if ($trip_type=='1') {
            $search_type='S';
        }
        //往返
        elseif ($trip_type=='2') {
            $search_type='D';
        }
        //联程
        else{
            $search_type='M';
        }
        
        //查询携程的机票数据
        $result = $this->flightapi->ctrip_flight($form_city,$to_city,$flight_date,$search_type,$return_date,$DepartPort,$ArrivePort);
        if(isset($result->FlightSearchResponse))
        {
            //转为数组格式
            if (!is_array($result->FlightSearchResponse->FlightRoutes->DomesticFlightRoute)) {
                $result->FlightSearchResponse->FlightRoutes->DomesticFlightRoute=array("0"=>$result->FlightSearchResponse->FlightRoutes->DomesticFlightRoute);
            }
            $F_az = array();
            $result->fdno = array();
            $result->FlightNO = array();
            $y_price = array();
            $temparray=array();
            $price_key=array();
            $pricekey_i=0;
            foreach ($result->FlightSearchResponse->FlightRoutes->DomesticFlightRoute as $flightroutes) {
                if (!is_array($flightroutes->FlightsList->DomesticFlightData)) {
                    $flightroutes->FlightsList->DomesticFlightData=array("0"=>$flightroutes->FlightsList->DomesticFlightData);
                }
                foreach ($flightroutes->FlightsList->DomesticFlightData as $v) {
                    //获取价格列表,用于匹配原有的折扣表
                    $result->fdnotmp->cabindesc = $v->SubClass;          //序号
                    $result->fdnotmp->cabintype = $v->DisplaySubclass;   //显示舱位
                    $result->fdnotmp->bcabintype = $v->Class;            //舱位类型
                    $result->fdnotmp->discountRate = '';                 //折扣
                    $result->fdnotmp->moneytype = 'CNY';                 //价格类型
                    $result->fdnotmp->roundprice = (string)($v->Price*2);//往返程价格
                    $result->fdnotmp->singleprice = $v->Price;           //单程价格
                    $result->fdnotmp->startdate = '';                    //有效时间
                    $result->fdnotmp->enddate = '';
                    $result->fdnotmp->airline = $v->AirlineCode;         //航空公司简码
                    $result->fdnotmp->flight = $v->Flight;               //航班号
                    $result->fdnotmp->rule = '';                         //规则，无意义
                    $result->fdnotmp->fueltax = '';
                    $result->fdnotmp->cstar = $v->DPortCode;             //出发机场
                    $result->fdnotmp->cdest = $v->APortCode;             //到达机场

                    if (!isset($temparray[$v->Flight.$v->DisplaySubclass])) {
                        $temparray[$v->Flight.$v->DisplaySubclass]=$result->fdnotmp;
                    }elseif ($temparray[$v->Flight.$v->DisplaySubclass]->singleprice<$result->fdnotmp->singleprice) {
                        $temparray[$v->Flight.$v->DisplaySubclass]=$result->fdnotmp;
                        unset($result->fdno[$price_key[$v->Flight.$v->DisplaySubclass]]);
                    }else{
                        unset($result->fdnotmp);
                        continue;
                    }
                    $price_key[$v->Flight.$v->DisplaySubclass]=$pricekey_i++;


                    $result->fdno[]=$result->fdnotmp;
                    unset($result->fdnotmp);

                    //获取Y舱价格,用于计算折扣
                    if ($v->Class=='Y' and !isset($y_price[$v->AirlineCode])) {
                        $y_price[$v->AirlineCode] = $v->StandardPrice;
                    }

                    //按照航班号重新组装数据
                    if (!isset($result->FlightNO[$v->Flight])) {
                        $result->FlightNOtmp->airlinecode = $v->AirlineCode;
                        $result->FlightNOtmp->flight = $v->Flight;
                        $result->FlightNOtmp->cstar = $v->DPortCode;
                        $result->FlightNOtmp->cdest = $v->APortCode;
                        $result->FlightNOtmp->dTerm = $v->DPortBuildingID;
                        $result->FlightNOtmp->aTerm = $v->APortBuildingID;
                        $result->FlightNOtmp->tstar = str_replace('T', ' ', $v->TakeOffTime);
                        $result->FlightNOtmp->tdest = str_replace('T', ' ', $v->ArriveTime);
                        $result->FlightNOtmp->fmodel = $v->CraftType;
                        $result->FlightNOtmp->fmeals = is_object($v->MealType)?'0':'1';
                        $result->FlightNOtmp->flip = $v->StopTimes;
                        $result->FlightNOtmp->fliet = '';
                        $result->FlightNOtmp->fcook = '';
                        $result->FlightNOtmp->f_az = '';
                        $result->FlightNOtmp->s_az = '';
                        $result->FlightNOtmp->fcn = $v->AdultTax;
                        $result->FlightNOtmp->fyq = $v->AdultOilFee;
                        $result->FlightNOtmp->fcny = '';
                        $result->FlightNOtmp->fmile = '';
                        $result->FlightNO[$v->Flight] = $result->FlightNOtmp;
                        unset($result->FlightNOtmp);
                    }

                    //拼接余票字符串F_az 如：2A---8-A--AAA------------4
                    if (!isset($F_az_arr[$v->Flight])) {
                        $F_az_arr[$v->Flight]=array('A'=>'-','B'=>'-','C'=>'-','D'=>'-','E'=>'-','F'=>'-','G'=>'-','H'=>'-','I'=>'-','J'=>'-','K'=>'-','L'=>'-','M'=>'-','N'=>'-','O'=>'-','P'=>'-','Q'=>'-','R'=>'-','S'=>'-','T'=>'-','U'=>'-','V'=>'-','W'=>'-','X'=>'-','Y'=>'-','Z'=>'-');
                    }
                    if($v->Quantity==10) $v->Quantity='A';
                    $F_az_arr[$v->Flight][$v->DisplaySubclass]=$v->Quantity;
                    $F_az[$v->Flight]=implode($F_az_arr[$v->Flight]);
                }
            }

            //设置每一趟航班的Y舱价格、余票字符串、发站到站的航站楼标识
            $Term_array = $this->lang->line('PortBuilding_code');
            foreach ($result->FlightNO as $k=>$f) {
                $f->fcny=(string)floor($y_price[$f->airlinecode]);
                $f->f_az=$F_az[$f->flight];
                $f->dTerm= isset($Term_array[$f->dTerm])?$Term_array[$f->dTerm]:'';
                $f->aTerm= isset($Term_array[$f->aTerm])?$Term_array[$f->aTerm]:'';
                //重新以数字下标组装数组
                $result->FlightNO[]=$f;
                unset($result->FlightNO[$k]);
            }

            //折扣=舱位价格/Y舱价格*100
            $cabintype_temp=array();
            $y_fdno=array();
            $fdno_count=count($result->fdno);
            $price_count=count($result->fdno);
            foreach ($result->fdno as $j=>$price) {
                $price->discountRate=(string)ceil(($price->singleprice/$y_price[$price->airline])*100);
                //屏蔽头等舱特价票
                if ($price->bcabintype=='F' and $price->discountRate<250) {
                    unset($result->fdno[$j]);
                }

                if ($price->cabintype=='Y') {
                    $cabintype_temp[$price->flight]=1;
                }
                if ($fdno_count>1) {
                    if ($j>0 && $j<$fdno_count) {
                        $y_fdno[]=$result->fdno[$j-1];
                        if ($result->fdno[$j-1]->flight!=$price->flight && !isset($cabintype_temp[$result->fdno[$j-1]->flight])) {
                            //伪造一个Y舱数据给接口
                            $fdno_p_temp=$result->fdno[$j-1];
                            $fdno_p_temp->cabintype='Y';
                            $fdno_p_temp->bcabintype='Y';
                            $fdno_p_temp->cabindesc='Y';
                            $fdno_p_temp->discountRate="100";
                            $fdno_p_temp->singleprice=(string)ceil($y_price[$result->fdno[$j-1]->airline]);
                            $fdno_p_temp->roundprice=(string)($fdno_p_temp->singleprice*2);
                            //$y_fdno[]=$fdno_p_temp;
                            unset($fdno_p_temp);
                        }
                        
                    }
                    if(($fdno_count-1)==$j){
                        $y_fdno[]=$result->fdno[$j];
                        if (!isset($cabintype_temp[$price->flight])) {
                            //伪造一个Y舱数据给接口
                            $fdno_p_temp=$price;
                            $fdno_p_temp->cabintype='Y';
                            $fdno_p_temp->bcabintype='Y';
                            $fdno_p_temp->cabindesc='Y';
                            $fdno_p_temp->discountRate="100";
                            $fdno_p_temp->singleprice=(string)ceil($y_price[$price->airline]);
                            $fdno_p_temp->roundprice=(string)($fdno_p_temp->singleprice*2);
                            //$y_fdno[]=$fdno_p_temp;
                            unset($fdno_p_temp);
                        }
                    }
                }elseif ($fdno_count==1){
                    $y_fdno[]=$price;
                    if (!isset($cabintype_temp[$price->flight])) {
                            //伪造一个Y舱数据给接口
                            $fdno_p_temp=$price;
                            $fdno_p_temp->cabintype='Y';
                            $fdno_p_temp->bcabintype='Y';
                            $fdno_p_temp->cabindesc='Y';
                            $fdno_p_temp->discountRate="100";
                            $fdno_p_temp->singleprice=(string)ceil($y_price[$price->airline]);
                            $fdno_p_temp->roundprice=(string)($fdno_p_temp->singleprice*2);
                            //$y_fdno[]=$fdno_p_temp;
                            unset($fdno_p_temp);
                    }
                }
                
            }
            //$result->fdno=array_merge($result->fdno,$y_fdno);
            $result->fdno=$y_fdno;

            $Flight_OBJ->FlightNO = $result->FlightNO;
            $Flight_OBJ->FDNO = $result->fdno;
        }else{
            $Flight_OBJ=false;
        }
        if (empty($Flight_OBJ->FlightNO)) {
            $Flight_OBJ=false;
        }
        return $Flight_OBJ;
    }

    public function get_data_by_qunar($form_city,$to_city,$flight_date) 
    {
        list($time1, $time2) = explode(' ', microtime());     
        $createTime = (float)sprintf('%.0f', (floatval($time1) + floatval($time2)) * 1000);
        $key = '77fcc49f53aa575506c89771cb817dd2';
        $params ='{"dptCode":"'.$form_city.'","arrCode":"'.$to_city.'","dptDate":"'.$flight_date.'"}';
        $tag = 'flight.national.supply.chailv.qb.search';
        $token = '1fd6e0564ac9bfcfd81cbd9b8afd1c56';
        $sign_str = "createTime=$createTime"."key=$key"."params=$params"."tag=$tag"."token=$token";
        $sign = mb_strtolower(md5($sign_str));
        $url = 'http://qae.qunar.com/api/router?params='.$params.'&sign='.$sign.'&tag='.$tag.'&token='.$token.'&createTime='.$createTime;
        $response = $this->get_curl($url);
        if ($response === FALSE) {
            return false;
        }
        $qunar_data=json_decode($response);
        if (!isset($qunar_data->result->data)) {
            return false;
        }
        $F_az = array();
        $fdno=array();
        $FlightNO=array();
        foreach ($qunar_data->result->data as $plane) {
            $fdnotmp = '';
            $cabindesc=substr($plane->cabin,1);
            $discountPrice=ceil(($plane->discountPrice/$plane->yprice)*100);
            if($plane->cabin=='Y') $discountPrice=100;
            $bcabintype = 'Y';
            if ($discountPrice >= 120 )
            {
                $bcabintype = 'F';
            } 
            else if ($discountPrice > 100)
            {
                $bcabintype = 'C';
            }
            $fdnotmp->cabindesc = $cabindesc ? $cabindesc : '';             //序号
            $fdnotmp->cabintype = substr($plane->cabin,0,1);             //显示舱位
            $fdnotmp->bcabintype = $bcabintype;            //舱位类型
            $fdnotmp->discountRate = $discountPrice;         //折扣
            $fdnotmp->moneytype = 'CNY';                     //价格类型
            $fdnotmp->roundprice = (string)($plane->discountPrice*2);//往返程价格
            $fdnotmp->singleprice = $plane->discountPrice;           //单程价格
            $fdnotmp->startdate = '';                        //有效时间
            $fdnotmp->enddate = '';
            $fdnotmp->airline = substr($plane->flightNum,0,2);//航空公司简码
            $fdnotmp->flight = $plane->flightNum;            //航班号
            $fdnotmp->rule = '';                             //规则，无意义
            $fdnotmp->fueltax = $plane->fuelTax;
            $fdno[]=$fdnotmp;

            //按照航班号重新组装数据
            if (!isset($FlightNO[$plane->flightNum])) {
                $FlightNOtmp = '';

                $dpthour=substr($plane->dptTime,0,2);
                $dptmin=substr($plane->dptTime,-2);
                $arrhour=substr($plane->arrTime,0,2);
                $arrmin=substr($plane->arrTime,-2);
                $plane->dptTime=$flight_date.' '.$dpthour.':'.$dptmin.':00';
                $plane->arrTime=$flight_date.' '.$arrhour.':'.$arrmin.':00';
                if ($dpthour>$arrhour) {
                    $plane->arrTime=date('Y-m-d',(strtotime($flight_date)+24*60*60)).' '.$arrhour.':'.$arrmin;
                }

                $FlightNOtmp->airlinecode = $fdnotmp->airline;//航空公司
                $FlightNOtmp->flight = $plane->flightNum;//航班号
                $FlightNOtmp->cstar = $plane->dptCode;//起飞机场
                $FlightNOtmp->cdest = $plane->arrCode;//到达机场
                $FlightNOtmp->dTerm = '';//起飞航站楼
                $FlightNOtmp->aTerm = '';//到达航站楼
                $FlightNOtmp->tstar = $plane->dptTime;//起飞时间
                $FlightNOtmp->tdest = $plane->arrTime;//到达时间
                $FlightNOtmp->fmodel = '';
                $FlightNOtmp->fmeals = '';
                $FlightNOtmp->flip = $plane->stops;
                $FlightNOtmp->fliet = '';
                $FlightNOtmp->fcook = '';
                $FlightNOtmp->f_az = '';
                $FlightNOtmp->s_az = '';
                $FlightNOtmp->fcn = $plane->constructionFee;
                $FlightNOtmp->fyq = $plane->fuelTax;
                $FlightNOtmp->fcny = $plane->yprice;
                $FlightNOtmp->fmile = $plane->distance;
                $FlightNO[$plane->flightNum] = $FlightNOtmp;
            }

            //拼接余票字符串F_az 如：2A---8-A--AAA------------4
            if (!isset($F_az_arr[$plane->flightNum])) {
                $F_az_arr[$plane->flightNum]=array('A'=>'-','B'=>'-','C'=>'-','D'=>'-','E'=>'-','F'=>'-','G'=>'-','H'=>'-','I'=>'-','J'=>'-','K'=>'-','L'=>'-','M'=>'-','N'=>'-','O'=>'-','P'=>'-','Q'=>'-','R'=>'-','S'=>'-','T'=>'-','U'=>'-','V'=>'-','W'=>'-','X'=>'-','Y'=>'-','Z'=>'-');
            }
            $F_az_arr[$plane->flightNum][$plane->cabin]=$plane->restCabin;
            $F_az[$plane->flightNum]=implode($F_az_arr[$plane->flightNum]);
        }

        foreach ($FlightNO as $k=>$f) {
            $f->f_az=$F_az[$f->flight];
            //重新以数字下标组装数组
            $FlightNO[]=$f;
            unset($FlightNO[$k]);
        }

        $Flight_OBJ->FlightNO = $FlightNO;
        $Flight_OBJ->FDNO = $fdno;
        return $Flight_OBJ;
    }

    public function get_data_by_elong($form_city,$to_city,$flight_date)
    {
        $url="http://flight.elong.com/isajax/OneWay/S?DepartCity=$form_city&ArriveCity=$to_city&DepartDate=$flight_date&SeatLevel=P&OrderBy=Price";
        $f_content = $this->get_curl($url);
        if ($f_content === FALSE) {
            return false;
        }
        $xml = json_decode($f_content);
        $F_az = array();
        $fdno=array();
        $FlightNO=array();
        foreach ($xml->value->MainLegs as $v) {
            //按照航班号重新组装数据
            if (!isset($FlightNO[$v->segs[0]->fltno])) {
                $FlightNOtmp = '';
                $FlightNOtmp->airlinecode = $v->segs[0]->corp;//航空公司
                $FlightNOtmp->flight = $v->segs[0]->fltno;//航班号
                $FlightNOtmp->cstar = $v->segs[0]->dport;//起飞机场
                $FlightNOtmp->cdest = $v->segs[0]->aport;//到达机场
                $FlightNOtmp->dTerm = $v->segs[0]->dtml;//起飞航站楼
                $FlightNOtmp->aTerm = $v->segs[0]->atml;//到达航站楼
                $FlightNOtmp->tstar = $v->segs[0]->dtime.':00';//起飞时间
                $FlightNOtmp->tdest = $v->segs[0]->atime.':00';//到达时间
                $FlightNOtmp->fmodel = $v->segs[0]->plane;
                $FlightNOtmp->fmeals = '';
                $FlightNOtmp->flip = $v->segs[0]->stop;
                $FlightNOtmp->fliet = '';
                $FlightNOtmp->fcook = '';
                $FlightNOtmp->f_az = '';
                $FlightNOtmp->s_az = '';
                $FlightNOtmp->fcn = $v->segs[0]->ofee;
                $FlightNOtmp->fyq = $v->segs[0]->tax;
                $FlightNOtmp->fcny = ceil($v->cabs[0]->price/$v->cabs[0]->disc);
                $FlightNOtmp->fmile = '';
                $FlightNO[$v->segs[0]->fltno] = $FlightNOtmp;
            }
            foreach ($v->cabs as $c) {
                $fdnotmp = '';
                $discountPrice=ceil(($c->price/$FlightNOtmp->fcny)*100);
                $bcabintype = 'Y';
                if ($discountPrice >= 120 )
                {
                    $bcabintype = 'F';
                } 
                else if ($discountPrice > 100)
                {
                    $bcabintype = 'C';
                }

                $fdnotmp->cabindesc = '';             //序号
                $fdnotmp->cabintype = $c->cab;             //显示舱位
                $fdnotmp->bcabintype = $bcabintype;            //舱位类型
                $fdnotmp->discountRate = $discountPrice; //折扣
                $fdnotmp->moneytype = 'CNY';                     //价格类型
                $fdnotmp->roundprice = (string)($c->price*2);//往返程价格
                $fdnotmp->singleprice = $c->price;           //单程价格
                $fdnotmp->startdate = '';                        //有效时间
                $fdnotmp->enddate = '';
                $fdnotmp->airline = $v->segs[0]->corp;//航空公司简码
                $fdnotmp->flight = $v->segs[0]->fltno;            //航班号
                $fdnotmp->rule = '';                             //规则，无意义
                $fdnotmp->fueltax = $v->segs[0]->tax;
                $fdnotmp->cstar = $v->segs[0]->dport;//起飞机场
                $fdnotmp->cdest = $v->segs[0]->aport;//到达机场
                $fdno[]=$fdnotmp;

                //拼接余票字符串F_az 如：2A---8-A--AAA------------4
                if (!isset($F_az_arr[$v->segs[0]->fltno])) {
                    $F_az_arr[$v->segs[0]->fltno]=array('A'=>'-','B'=>'-','C'=>'-','D'=>'-','E'=>'-','F'=>'-','G'=>'-','H'=>'-','I'=>'-','J'=>'-','K'=>'-','L'=>'-','M'=>'-','N'=>'-','O'=>'-','P'=>'-','Q'=>'-','R'=>'-','S'=>'-','T'=>'-','U'=>'-','V'=>'-','W'=>'-','X'=>'-','Y'=>'-','Z'=>'-');
                }
                $F_az_arr[$v->segs[0]->fltno][$c->cab]='A';
                $F_az[$v->segs[0]->fltno]=implode($F_az_arr[$v->segs[0]->fltno]);
            }
        }

        foreach ($FlightNO as $k=>$f) {
            $f->f_az=$F_az[$f->flight];
            //重新以数字下标组装数组
            $FlightNO[]=$f;
            unset($FlightNO[$k]);
        }

        $Flight_OBJ->FlightNO = $FlightNO;
        $Flight_OBJ->FDNO = $fdno;

        return $Flight_OBJ;
    }

    public function get_international_flight($form_city_code,$to_city_code,$flight_date,$return_date=false)
    {
        $result = $this->flightapi->international_flight($form_city_code,$to_city_code,$flight_date,$return_date, false, false);
        $result=$this->format_flight_data($result);
        $flight_list=$result['flight_list'];
        $flight_price=$result['flight_price'];
        $F_az = array();
        $fdno=array();
        $FlightNO=array();
        foreach ($result['flight_group'] as $flight) {
            if ($flight->flight_type!='Nonstop') {
                continue;
            }
            //按照航班号重新组装数据
            $FlightNOtmp = '';
            foreach ($flight->FlightSegmentList->FlightSegment as $plane) {
                $flightdetail=$flight_list['FlightID'.$plane->FlightID];
                $FlightNOtmp->flight = $flightdetail->FlightNumber;//航班号
                $FlightNOtmp->cstar = $flightdetail->DepartureAirport->PortCode;//起飞机场
                $FlightNOtmp->cdest = $flightdetail->ArrivalAirport->PortCode;//到达机场
                $FlightNOtmp->dTerm = $flightdetail->DepartureAirport->Terminal;//起飞航站楼
                $FlightNOtmp->aTerm = $flightdetail->ArrivalAirport->Terminal;//到达航站楼
                $FlightNOtmp->tstar = date('Y-m-d H:i:s',$flightdetail->TakeoffDateTime);//起飞时间
                $FlightNOtmp->tdest = date('Y-m-d H:i:s',$flightdetail->ArrivalDateTime);//到达时间
                $FlightNOtmp->fmodel = $flightdetail->EquipmentCode;
            }
            $FlightNOtmp->airlinecode = $flight->AirlineIcon;//航空公司
            $FlightNOtmp->flip = 0;//$flight->flight_type;
            $FlightNOtmp->fmeals = '';
            $FlightNOtmp->fliet = '';
            $FlightNOtmp->fcook = '';
            $FlightNOtmp->f_az = '';
            $FlightNOtmp->s_az = '';

            $first_priceUnitID=$flight->PriceList->Price[0]->PriceUnitID;
            $OriginalPriceDetail=$flight_price['PriceUnitID'.$first_priceUnitID]->PriceInfoList->PriceInfo->OriginalPriceDetail;
            $FlightNOtmp->fcn = $OriginalPriceDetail->FuelSurCharge;
            $FlightNOtmp->fyq = $OriginalPriceDetail->Tax;

            $FlightNOtmp->fcny = $OriginalPriceDetail->PublishPrice;
            $FlightNOtmp->fmile = '';
            foreach ($flight->PriceList->Price as $price) {
                $web_CabinClass=$flight_price['PriceUnitID'.$price->PriceUnitID]->web_CabinClass;
                if ($web_CabinClass!='Premium' && $web_CabinClass!='Business')
                {
                    $FlightNOtmp->fcny=$flight_price['PriceUnitID'.$price->PriceUnitID]->PriceInfoList->PriceInfo->OriginalPriceDetail->PublishPrice;
                    break;
                }
            }
            $FlightNO[$FlightNOtmp->flight] = $FlightNOtmp;

            foreach ($flight->PriceList->Price as $price) {
                $fdnotmp = '';
                $bcabintype = 'Y';
                if ($flight_price['PriceUnitID'.$price->PriceUnitID]->web_CabinClass=='Premium')
                {
                    $bcabintype = 'F';
                } 
                else if ($flight_price['PriceUnitID'.$price->PriceUnitID]->web_CabinClass=='Business')
                {
                    $bcabintype = 'C';
                }
                $singleprice=$flight_price['PriceUnitID'.$price->PriceUnitID]->PriceInfoList->PriceInfo->OriginalPriceDetail->SalePrice;
                $discountPrice=ceil(($singleprice/$FlightNOtmp->fcny)*100);

                $fdnotmp->cabindesc = '';             //序号
                $fdnotmp->cabintype = $flight_price['PriceUnitID'.$price->PriceUnitID]->BookingClass;             //显示舱位
                $fdnotmp->bcabintype = $bcabintype;            //舱位类型
                $fdnotmp->discountRate = $discountPrice; //折扣
                $fdnotmp->moneytype = 'CNY';                     //价格类型
                $fdnotmp->roundprice = (string)($singleprice*2);//往返程价格
                $fdnotmp->singleprice = $singleprice; //单程价格
                $fdnotmp->startdate = '';                        //有效时间
                $fdnotmp->enddate = '';
                $fdnotmp->airline = $FlightNOtmp->airlinecode;    //航空公司简码
                $fdnotmp->flight = $FlightNOtmp->flight;            //航班号
                $fdnotmp->rule = '';                             //规则，无意义
                $fdnotmp->fueltax = $FlightNOtmp->fyq;
                $fdno[]=$fdnotmp;

                //拼接余票字符串F_az 如：2A---8-A--AAA------------4
                if (!isset($F_az_arr[$flightdetail->FlightNumber])) {
                    $F_az_arr[$flightdetail->FlightNumber]=array('A'=>'-','B'=>'-','C'=>'-','D'=>'-','E'=>'-','F'=>'-','G'=>'-','H'=>'-','I'=>'-','J'=>'-','K'=>'-','L'=>'-','M'=>'-','N'=>'-','O'=>'-','P'=>'-','Q'=>'-','R'=>'-','S'=>'-','T'=>'-','U'=>'-','V'=>'-','W'=>'-','X'=>'-','Y'=>'-','Z'=>'-');
                }
                $F_az_arr[$flightdetail->FlightNumber][$flight_price['PriceUnitID'.$price->PriceUnitID]->BookingClass]=(is_numeric($price->seat_count) && $price->seat_count<10)?$price->seat_count:'A';
                $F_az[$flightdetail->FlightNumber]=implode($F_az_arr[$flightdetail->FlightNumber]);
            }
        }
        foreach ($FlightNO as $k=>$f) {
            $f->f_az=$F_az[$f->flight];
            //重新以数字下标组装数组
            $FlightNO[]=$f;
            unset($FlightNO[$k]);
        }
        $Flight_OBJ->FlightNO = $FlightNO;
        $Flight_OBJ->FDNO = $fdno;

        if (empty($Flight_OBJ->FlightNO)) {
            $Flight_OBJ=false;
        }
        return $Flight_OBJ;
    }
    public function format_flight_data($result)
    {
        $SearchResult=$result->IntlFlightSearchResponse->SearchResult;
        //飞机列表
        $flight_list = array();
        if (!is_array($SearchResult->FlightList->Flight)) {
            $SearchResult->FlightList->Flight=array(0=>$SearchResult->FlightList->Flight);
        }
        foreach ($SearchResult->FlightList->Flight as $flight) {
            $flight->TakeoffDateTime = strtotime(str_replace('T', ' ', $flight->TakeoffDateTime));
            $flight->ArrivalDateTime = strtotime(str_replace('T', ' ', $flight->ArrivalDateTime));
            $flight_list['FlightID' . $flight->FlightID] = $flight;
        }

        //价格列表
        $price_list = array();
        if (!is_array($SearchResult->PriceUnitList->PriceUnit)) {
            $SearchResult->PriceUnitList->PriceUnit=array(0=>$SearchResult->PriceUnitList->PriceUnit);
        }
        foreach ($SearchResult->PriceUnitList->PriceUnit as $f) {
            //表单页单独查询一趟航班时会返回两个价格，暂取第一个
            if (is_array($f->PriceInfoList->PriceInfo)) {
                $f->PriceInfoList->PriceInfo=array_shift($f->PriceInfoList->PriceInfo);
            }
            if (!is_array($f->BookingClassInfoListList->BookingClassInfoList)){
                $f->BookingClassInfoListList->BookingClassInfoList=array(0=>$f->BookingClassInfoListList->BookingClassInfoList);
            }
            foreach ($f->BookingClassInfoListList->BookingClassInfoList as $i => $value) {
                if (!is_array($value->BookingClassInfo)) {
                    $value->BookingClassInfo=array(0=>$value->BookingClassInfo);
                }
                //计算余票用的数据
                $f->BookingClass=end($value->BookingClassInfo)->BookingClass;
                $f->flight_key = count($value->BookingClassInfo)-1;
                //获取每个价格对应的展示舱等
                foreach ($value->BookingClassInfo as $j => $class_list_info) {
                    if ($i == 0 && $j == 0) {
                        $f->web_CabinClass = $class_list_info->CabinClass;
                    } else if ($f->web_CabinClass != $class_list_info->CabinClass) {
                        $f->web_CabinClass = '多舱等';
                    }
                }
            }
            $price_list['PriceUnitID'.$f->PriceUnitID] = $f;
        }

        //每架飞机每种舱位的余票列表
        $seat_count = array();
        foreach ($SearchResult->FlightList->Flight as $s) {
            foreach ($s->SeatCountList->SeatCount as $seat) {
                $seatID = 'FlightID' . $s->FlightID;
                $seat_count["$seatID"][$seat->Class] = $seat->Count;
            }
        }

        //航班组合列表
        $AirlineNameArr = array();//本次查询出现的航空公司
        $group_list=$SearchResult->FlightProductGroupList->FlightProductGroup;
        if (!is_array($group_list)) {
            $group_list=array(0=>$group_list);
        }
        foreach ($group_list as $group) {
            if (!is_array($group->FlightSegmentList->FlightSegment)) {
                $group->FlightSegmentList->FlightSegment=array(0=>$group->FlightSegmentList->FlightSegment);
            }
            $OrigDestSeqID_flag = false;//往返标识
            $endflight_key=0;//去程的抵达航班序号
            foreach ($group->FlightSegmentList->FlightSegment as $key => $segment) {
                if ($key == 0) {
                    $AirlineCode = $flight_list['FlightID'.$segment->FlightID]->Carrier->AirlineCode;
                    $group->AirlineName = $flight_list['FlightID'.$segment->FlightID]->Carrier->AirlineName;
                    $group->AirlineIcon = $AirlineCode;
                    $group->TakeoffDateTime = $flight_list['FlightID'.$segment->FlightID]->TakeoffDateTime;
                    $group->DeparturePortCode = $flight_list['FlightID'.$segment->FlightID]->DepartureAirport->PortCode;
                }
                else
                {
                    //多个航空公司提供服务 
                    if ($AirlineCode != $flight_list['FlightID' . $segment->FlightID]->Carrier->AirlineCode) {
                        $group->AirlineName = '多个航司';
                        $group->AirlineIcon = 'multi';
                    }
                    //当查询往返航班时设置往返标识
                    if (!$OrigDestSeqID_flag && $segment->OrigDestSeqID == '2'){
                        $OrigDestSeqID_flag = TRUE;
                    }
                    //计算抵达航班
                    elseif($segment->OrigDestSeqID!=2){
                        $endflight_key++;
                    }
                }
            }
            //去程航班到达时间及机场简码
            $endflight = $group->FlightSegmentList->FlightSegment[$endflight_key];
            $end_flightID = 'FlightID' . $endflight->FlightID;
            $group->ArrivalDateTime = $flight_list[$end_flightID]->ArrivalDateTime;
            $group->ArrivalPortCode = $flight_list[$end_flightID]->ArrivalAirport->PortCode;

            //中转情况
            if ($endflight_key == 0) {
                $group->flight_type = 'Nonstop';
            } else {
                $group->flight_type = $endflight_key. ' stop';
            }
            //收集本次查询出现过的航空公司
            if (!in_array($group->AirlineName, $AirlineNameArr)){
                $AirlineNameArr[] = $group->AirlineName;
            }
            //每个价格对应的余票
            if (!is_array($group->PriceList->Price)) {
                $group->PriceList->Price = array(0=>$group->PriceList->Price);
            }
            foreach ($group->PriceList->Price as $price) {
                //取票数最少的那一个
                foreach ($group->FlightSegmentList->FlightSegment as $k=>$f_list) {
                    $temp_seat_count = $seat_count['FlightID'.$f_list->FlightID][$price_list['PriceUnitID'.$price->PriceUnitID]->BookingClass];
                    if(!is_numeric($temp_seat_count)) $temp_seat_count=11;
                    if ($k==0) {
                        $price->seat_count = $temp_seat_count;
                    }else if($price->seat_count>$temp_seat_count){
                        $price->seat_count=$temp_seat_count;
                    }
                    //如果都是11说明返回的余票数是字母
                    if ($price->seat_count==11) {
                        $seat_FlightID=$group->FlightSegmentList->FlightSegment[$price_list->flight_key]->FlightID;
                        $price->seat_count=$seat_count['FlightID'.$seat_FlightID][$price_list['PriceUnitID'.$price->PriceUnitID]->BookingClass];
                    }
                }
            }
        }

        //每种价格对应的行李可携带重量
        $remark_list = array();
        foreach ($SearchResult->TextRemarkList->TextRemark as $remark) {
            $RemarkID = 'RemarkID' . $remark->RemarkID;
            $remark_list["$RemarkID"] = $remark;
        }

        $data['flight_list']  = $flight_list;
        $data['flight_price'] = $price_list;
        $data['airline_arr']  = $AirlineNameArr;
        $data['remark_list']  = $remark_list;
        $data['flight_group'] = $group_list;

        return $data;
    }

    //未转换格式的接口
    public function new_ota_search($form_city,$to_city,$flight_date,$search_type='S',$return_date=false) 
    {
        //如果传进来的是机场三字码，则在语言包里查询所属城市三字码
        $DepartPort=$ArrivePort=false;
        $this->lang->load('city_code', 'english');
        $citycode = $this->lang->line('city_code');
        if (isset($citycode["$form_city"]) && $citycode["$form_city"]!=$form_city) {
            $DepartPort=$form_city;
            $form_city=$citycode["$form_city"];
        }
        if (isset($citycode["$to_city"]) && $citycode["$to_city"]!=$to_city) {
            $ArrivePort=$to_city;
            $to_city=$citycode["$to_city"];
        }
        
        $result = $this->flightapi->ctrip_flight($form_city,$to_city,$flight_date,$search_type,$return_date,$DepartPort,$ArrivePort);
        //转为数组格式
        if (!is_array($result->FlightSearchResponse->FlightRoutes->DomesticFlightRoute)) {
            $result->FlightSearchResponse->FlightRoutes->DomesticFlightRoute=array("0"=>$result->FlightSearchResponse->FlightRoutes->DomesticFlightRoute);
        }
        $group_array = array();
        foreach ($result->FlightSearchResponse->FlightRoutes->DomesticFlightRoute as $flightroutes) {
            foreach ($flightroutes->FlightsList->DomesticFlightData as $v) {
                $group_array[$v->Flight]['Flight']                   = $v->Flight;                    //航班号
                $group_array[$v->Flight]['CraftType']                = $v->CraftType;                 //机型
                $group_array[$v->Flight]['AirlineCode']              = $v->AirlineCode;               //航空公司简码
                $group_array[$v->Flight]['DepartCityCode']           = $v->DepartCityCode;            //起飞城市简码
                $group_array[$v->Flight]['ArriveCityCode']           = $v->ArriveCityCode;            //抵达城市简码
                $group_array[$v->Flight]['TakeOffTime']              = $v->TakeOffTime;               //起飞时间
                $group_array[$v->Flight]['ArriveTime']               = $v->ArriveTime;                //到达时间
                $group_array[$v->Flight]['DPortCode']                = $v->DPortCode;                 //起飞机场简码
                $group_array[$v->Flight]['APortCode']                = $v->APortCode;                 //抵达机场简码
                $group_array[$v->Flight]['DPortBuildingID']          = $v->DPortBuildingID;           //起飞航站楼ID
                $group_array[$v->Flight]['APortBuildingID']          = $v->APortBuildingID;           //到达航站楼ID
                $group_array[$v->Flight]['APortBuildingCheckInTime'] = $v->APortBuildingCheckInTime;  //起飞航站楼CheckIn时间
                $group_array[$v->Flight]['DPortBuildingCheckInTime'] = $v->DPortBuildingCheckInTime;  //抵达航站楼CheckIn时间
                $group_array[$v->Flight]['StopTimes']                = $v->StopTimes;                 //经停次数
                $group_array[$v->Flight]['PunctualityRate']          = $v->PunctualityRate;           //准点率

                $price_group['Class']              = $v->Class;              //舱位等级
                $price_group['SubClass']           = $v->SubClass;           //子舱位
                $price_group['DisplaySubclass']    = $v->DisplaySubclass;    //显示舱位
                $price_group['Quantity']           = $v->Quantity;           //余票数量
                $price_group['Rate']               = $v->Rate;               //航班折扣
                $price_group['Price']              = $v->Price;              //航班票价
                $price_group['StandardPrice']      = $v->StandardPrice;      //标准价
                $price_group['ChildStandardPrice'] = $v->ChildStandardPrice; //儿童标准价
                $price_group['BabyStandardPrice']  = $v->BabyStandardPrice;  //婴儿标准价
                $price_group['MealType']           = $v->MealType;           //餐食类型
                $price_group['AdultTax']           = $v->AdultTax;           //成人税
                $price_group['BabyTax']            = $v->BabyTax;            //婴儿税
                $price_group['ChildTax']           = $v->ChildTax;           //儿童税
                $price_group['AdultOilFee']        = $v->AdultOilFee;        //成人燃油费用
                $price_group['BabyOilFee']         = $v->BabyOilFee;         //婴儿燃油费用
                $price_group['ChildOilFee']        = $v->ChildOilFee;        //儿童燃油费用
                $price_group['Rernote']            = $v->Rernote;            //更改说明
                $price_group['Endnote']            = $v->Endnote;            //转签说明
                $price_group['Refnote']            = $v->Refnote;            //退票说明
                $price_group['Remarks']            = $v->Remarks;            //备注

                $group_array[$v->Flight]['price_group'][]=$price_group;
            }
        }
        echo json_encode($group_array);
    }

    public function get_curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        $response = curl_exec($ch);
        return $response;
    }

    public function api_check() {
        $datestr=date('Y-m-d-H-i-s');
        //获取随机起飞抵达城市
        $city_array=array('SHA','BJS','CAN','SIA','KWL','CTU','XMN');
        shuffle($city_array);
        $from_city=$city_array[0];
        $to_city=$city_array[1];
        //随机时间
        $flight_date='2015-07-10';//date('Y-m-d',(time()+rand(1,10)*24*60*60));
        $return_date=date('Y-m-d',(time()+rand(12,20)*24*60*60));

        //请求接口
        $flight=$this->get_curl("http://202.103.68.34:9091/index.php/thirdparty/flight/flighttool/ota_search/$from_city/$to_city/$flight_date/0/1");
        $price=$this->get_curl("http://202.103.68.34:9091/index.php/thirdparty/flight/flighttool/ota_search/$from_city/$to_city/$flight_date/1/1");
        //var_dump($flight);
        //请求出错
        $xml=json_decode($flight);
        if (empty($xml->FlightNO) || isset($xml->err)) {
            $errpath=dirname(__FILE__).'/err/';
            $errfilepath=$errpath.$datestr.'.txt';
            if(!file_exists($errpath))
            {
                mkdir($errpath,0777);
            }
            $ferr_puts = fopen($errfilepath,"a+");
            fputs($ferr_puts,$from_city.$to_city.$flight_date.' '.$return_date.$flight."/r/n".$price);
            fclose($ferr_puts);
        }
        //记录日志
        $path=dirname(__FILE__).'/log5/';
        $filepath=$path.$datestr.'.txt';
        if(!file_exists($path))
        {
            mkdir($path,0777);
        }
        $fp_puts = fopen($filepath,"a+");
        echo fputs($fp_puts,$flight.$price);
        fclose($fp_puts);
    }

}