<?php 

class tuniu_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->HT = $this->load->database('HT', TRUE);
        $this->INFO = $this->load->database('INFO', TRUE);
    }
	
	//传入主订单翰特订单号COLI_ID（161014006M），获取子订单中火车订单的COLD_SN
	function get_biz_cold($cols_id) {
        $sql = "SELECT COLD_SN
            FROM BIZ_ConfirmLineDetail bcld 
            WHERE bcld.COLD_COLI_SN=(
              SELECT COLI_SN FROM BIZ_ConfirmLineInfo bcli WHERE bcli.COLI_ID=?)
            AND bcld.DeleteFlag=0 AND bcld.COLD_ServiceType='2'";
        $query = $this->HT->query($sql, $cols_id);
        return $query->result();
    }
	
	//传入COLI_ID，获取外联名
	function get_operatorinfo($cols_id) {
        $sql = "
			   SELECT
					   Name,
					   OPI_Name,
					   OPI_Email,
					   tel,
					   Mobile,
					   Email
				FROM   OperatorInfo
				left join agenter_user
				on AU_OPI_SN = OPI_SN
				WHERE  OPI_SN = (
						   SELECT COLI_OPI_ID
						   FROM   BIZ_ConfirmLineInfo bcli
						   WHERE  bcli.COLI_ID = ?
					   )
					   and agenter in ('cht', 'train_vac', 'jp', 'train_it', 'vc', 'ru')
        ";
        $query = $this->HT->query($sql, $cols_id);
        return $query->result();
    }
	
	//传入子订单COLD_SN，获取子订单对应的乘客信息
    function biz_people($cold_sn) {
        $sql = "
                SELECT bbp.BPE_SN
                    ,bbp.BPE_FirstName
                    ,bbp.BPE_MiddleName
                    ,bbp.BPE_LastName
                    ,bbp.BPE_GuestType
                    ,bbp.BPE_Passport
              FROM   BIZ_BookPeople bbp
              WHERE  EXISTS(
                         SELECT TOP 1 1
                         FROM   BIZ_BookPeopleList bbpl
                         WHERE  bbpl.BPL_BPE_SN = bbp.BPE_SN
                                AND bbpl.BPL_COLD_SN = ?
                     )          
              ";
        $query = $this->HT->query($sql, $cold_sn);
        return $query->result();
    }
	
	//传入COLD_SN，获取火车车次等信息
    function get_biz_foi($cold_sn) {
        $sql = "
            SELECT FOI_COLD_SN,
                   FlightsNo,
                   Cabin,
				   Aircraft,
                   DepartureCity,
                   ArrivalCity,
                   DepartureDate,
                   DepartureTime,
                   ArrivalTime,
                   adultcost,
				   FOI_SelectedSeat,
				   FOI_TrainNetOrderNo,
				   FOI_SaleDate,
				   (
                               SELECT TOP 1 TRS_StationCN
                               FROM   TrainStation
                               WHERE  TRS_Code = DepartAirport
                           )  AS DepartAirport_cn
                          ,(
                               SELECT TOP 1 TRS_StationCN
                               FROM   TrainStation
                               WHERE  TRS_Code = ArrivalAirport
                           )  AS ArrivalAirport_cn
            FROM   BIZ_FlightsOrderInfo
            WHERE  FOI_COLD_SN = ?
            ";
        $query = $this->HT->query($sql, $cold_sn);
        return $query->result();
    }
	
	 //传入COLD_SN，获取BIZ_JuheOrderList是否存在此子订单，用来判断是否提交过给聚合
    function get_biz_jol($cold_sn) {
        $sql = "SELECT top 1 JOL_SN FROM BIZ_JuheOrderList WHERE JOL_COLD_SN= ?";
        $query = $this->HT->query($sql, $cold_sn);
		if($query->num_rows() == 0){
			return true;
		}else{
			return false;
		}	
    }
	
	public function get_order($pagesize=2,$page=0,$where="1=1"){
		$data=new StdClass();
		//获取总条数
		$sql="SELECT COUNT(*) AS count FROM TuniuOrderList
					 LEFT JOIN 
				   		 Tourmanager.dbo.BIZ_ConfirmLineInfo 
				   ON
				   		Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM Tourmanager.dbo.BIZ_ConfirmLineDetail WHERE COLD_SN=substring(tol_retailOrderId,0,charindex('_',tol_retailOrderId)))
				   WHERE 
			   		  {$where}
			   ";
		$query = $this->INFO->query($sql);
		$count=$query->result();
		$data->count=$count[0]->count;
		
		$sql="SELECT TOP {$pagesize} TuniuOrderList.tol_subtime,
					 TuniuOrderList.tol_orderId,
					 TuniuOrderList.tol_returnCode,
					 TuniuOrderList.tol_retailOrderId,
					 TuniuOrderList.tol_Status,
					 TuniuOrderList.tol_errorMsg,
					 TuniuOrderList.tol_fromStationName,
					 TuniuOrderList.tol_toStationName,
					 TuniuOrderList.tol_cheCi,
					 TuniuOrderList.tol_orderAmount,
					 TuniuOrderList.tol_isauto,
					 TuniuOrderList.tol_sendmail,
					 Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_ID,
					 Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_WebCode
			   FROM 
			 		 TuniuOrderList
			   LEFT JOIN 
			   		 Tourmanager.dbo.BIZ_ConfirmLineInfo 
			   ON
			   		Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM Tourmanager.dbo.BIZ_ConfirmLineDetail WHERE COLD_SN=substring(tol_retailOrderId,0,charindex('_',tol_retailOrderId)))
			   WHERE 
			   		TuniuOrderList.tol_orderId NOT IN(SELECT TOP {$page} TuniuOrderList.tol_orderId FROM TuniuOrderList ORDER BY TuniuOrderList.tol_sn DESC)		
			   	AND
			   		{$where}
			   ORDER BY TuniuOrderList.tol_sn DESC";
		$query = $this->INFO->query($sql);
		$data->list=$query->result();
		return $data;

	}
	
	 function biz_order_detail($cold_sn) {
        $sql = "        
                    SELECT TOP 1 bfoi.FOI_SN
                          ,bfoi.FOI_COLD_SN
                          ,bfoi.DepartAirport
                          ,bfoi.ArrivalAirport
                          ,bfoi.FlightsNo
                          ,bfoi.Aircraft
                          ,bfoi.DepartureDate
                          ,(
                               SELECT TOP 1 TRS_StationCN
                               FROM   TrainStation
                               WHERE  TRS_Code = DepartAirport
                           )  AS DepartAirport_cn
                          ,(
                               SELECT TOP 1 TRS_StationCN
                               FROM   TrainStation
                               WHERE  TRS_Code = ArrivalAirport
                           )  AS ArrivalAirport_cn,
                           FOI_TrainNetOrderNo,
                           bfoi.adultcost
                    FROM   BIZ_FlightsOrderInfo bfoi
                    WHERE  bfoi.FOI_COLD_SN = ?
                 ";
        $query = $this->HT->query($sql, $cold_sn);
        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return false;
        }
    }
	
	 //传入一组BPE_SN获取乘客信息
    function in_bpesn_people_info($bpe_sn){
        $sql = "
                SELECT bbp.BPE_SN
                    ,bbp.BPE_FirstName
                    ,bbp.BPE_MiddleName
                    ,bbp.BPE_LastName
                    ,bbp.BPE_GuestType
                    ,bbp.BPE_Passport
                    ,bbp.BPE_PassportType
              FROM   BIZ_BookPeople bbp
              WHERE  BPE_SN in(".$bpe_sn.")          
              ";
        $query = $this->HT->query($sql);
        return $query->result();
    }
	
	//添加途牛订单记录
    function tuniu_add_biz_jol($data,$isauto){
		if($isauto){
			$isauto = 1;
		}else{
			$isauto = 0;
		}
		$sql="
			  INSERT INTO TuniuOrderList(
				  tol_subTime,
				  tol_cheCi,
				  tol_fromStationName,
				  tol_fromStationCode,
				  tol_toStationName,
				  tol_toStationCode,
				  tol_retailOrderId,
				  tol_orderId,
				  tol_status,
				  tol_errorMsg,
				  tol_isauto
				  )
			  VALUES(getdate(),?,?,?,?,?,?,?,?,?,?)
		   ";
      $query = $this->INFO->query($sql,array($data->tol_cheCi,$data->tol_fromStationName,$data->tol_fromStationCode,$data->tol_toStationName,$data->tol_toStationCode,$data->tol_retailOrderId,$data->tol_orderId,$data->tol_status,$data->tol_errorMsg,$isauto));
      return $query;
    }
	
	
	//途牛预定处理
    function book_tuniu_order($data){
        $sql = "
            UPDATE TuniuOrderList
				set
                    tol_orderId          	= '{$data['orderId']}',
                    tol_returnCode          = '{$data['returnCode']}',
					tol_status				= '2',
                    tol_errorMsg			= '{$data['errorMsg']}',
                    --tol_fromStationCode     = '{$data['fromStationCode']}',
                    --tol_fromStationName     = '{$data['fromStationName']}',
                    --tol_toStationCode       = '{$data['toStationCode']}',
                    --tol_toStationName       = '{$data['toStationName']}',
                    --tol_cheCi           	= '{$data['cheCi']}',
                    tol_orderAmount         = '{$data['orderAmount']}',
					tol_booktxt				= '{$data['backtxt']}'
            WHERE  
                    tol_retailOrderId       = '{$data['retailOrderId']}'
                    ";
                    
        $query = $this->INFO->query($sql);
        return $query;
     }
	
	//确认出票更新
	public function confirm_tuniu_order($data){
		$sql = "
            UPDATE TuniuOrderList
				set
                    tol_orderId          	= '{$data['orderId']}',
                    tol_returnCode          = '{$data['returnCode']}',
					tol_status				= '4',
                    tol_errorMsg			= '{$data['errorMsg']}',
					tol_confirmtxt			= '{$data['confirmtxt']}'
            WHERE  
                    tol_retailOrderId       = '{$data['retailOrderId']}'
                    ";
                    
        $query = $this->INFO->query($sql);
        return $query;
	}
	
	//退票更新
	public function return_tuniu_order($data){
		$sql = "
            UPDATE TuniuOrderList
				set
                    tol_returnCode          = '{$data['returnCode']}',
					tol_status				= '7',
                    tol_errorMsg			= '{$data['errorMsg']}',
					tol_returntxt			= '{$data['returntxt']}'
            WHERE  
                    tol_retailOrderId       = '{$data['retailOrderId']}'
                    ";
                    
        $query = $this->INFO->query($sql);
        return $query;
	}
	
	//抢票更新
	public function grab_tuniu_order($data){
		$sql = "
            UPDATE TuniuOrderList
				set
					tol_returnCode          = '{$data['returnCode']}',
					tol_status				= '9',
					tol_errorMsg            = '{$data['errorMsg']}',
					tol_fromStationCode		= '{$data['fromStationCode']}',
					tol_fromStationName		= '{$data['fromStationName']}',
					tol_toStationCode		= '{$data['toStationCode']}',
					tol_toStationName		= '{$data['toStationName']}',
					tol_cheCi				= '{$data['cheCi']}',
                    tol_orderAmount			= '{$data['orderAmount']}',
					tol_booktxt				= '{$data['booktxt']}'
					
            WHERE  
                    tol_retailOrderId       = '{$data['retailOrderId']}'
                    ";
                    
        $query = $this->INFO->query($sql);
        return $query;
	}
	
	//取消抢票更新
	public function cancelgragticket($data){
		$sql = "
            UPDATE TuniuOrderList
				set
					tol_errorMsg    		= '{$data['errorMsg']}',
					tol_returnCode          = '{$data['returnCode']}',
					tol_status				= '8',
					tol_orderId				= '{$data['orderId']}'
            WHERE  
                    tol_retailOrderId       = '{$data['retailOrderId']}'
                    ";
                    
        $query = $this->INFO->query($sql);
        return $query;
	}
	
	//获取途牛订单信息
	public function get_tuniuorder_info($retailOrderId,$orderId){
		$sql = 'select tol_booktxt from TuniuOrderList where tol_retailOrderId = ? and tol_orderId =?';
		$query = $this->INFO->query($sql,array($retailOrderId,$orderId));
        return $query->result();
	}
	
	//BIZ_TrainOrderCost,我的支付
	//BIZ_FlightsOrderInfo.FOI_TrainNetOrderNo,更新取票号
	public function add_grab_order($data){
		$sql="SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN=?";
		$query=$this->HT->query($sql,$data->TOC_COLD_SN);
		$query=$query->result();
		$CCSN=$query[0]->COLD_COLI_SN;
		//删除多余支付记录
		$sql = "delete from BIZ_TrainOrderCost where TOC_COLI_SN = '{$CCSN}' and TOC_TicketCost is null";
		$query=$this->HT->query($sql);
		$sql="IF EXISTS(
					select * from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN' and (FOI_TrainNetOrderNo is null or FOI_TrainNetOrderNo = '' or FOI_TrainNetOrderNo like '%$data->FOI_TrainNetOrderNo%')) 
					UPDATE BIZ_FlightsOrderInfo
					SET
						FOI_TrainNetOrderNo='$data->FOI_TrainNetOrderNo'
					WHERE
						FOI_COLD_SN='$data->TOC_COLD_SN'
					ELSE 
						UPDATE BIZ_FlightsOrderInfo
					SET
						FOI_TrainNetOrderNo=(select FOI_TrainNetOrderNo from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN') + '&' + '$data->FOI_TrainNetOrderNo'
					WHERE
						FOI_COLD_SN='$data->TOC_COLD_SN'";
						
			$this->HT->query($sql);
			
			$sql="IF NOT EXISTS(
						SELECT TOP 1 1 FROM BIZ_TrainOrderCost
						WHERE TOC_COLD_SN = ? AND TOC_Memo like ?
					) 
					INSERT INTO BIZ_TrainOrderCost(
								TOC_Memo,
								TOC_CreateDate,
								TOC_COLI_SN,
								TOC_COLD_SN,
								TOC_TrainNumber,
								TOC_DepartureDate,
								TOC_TicketCost,
								TOC_WL,
								TOC_OtherCost
								)
							VALUES(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),null),(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),1)";
			$query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%",$data->TOC_Memo." 途牛抢票出票",$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->TOC_TicketCost,$data->TOC_Memo." 手续费",$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->poundage));
			return $query;
	}
	
	public function add_return_order($data){
		$sql="SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN=?";
		$query=$this->HT->query($sql,$data->TOC_COLD_SN);
		$query=$query->result();
		$CCSN=$query[0]->COLD_COLI_SN;
		
		$sql="IF NOT EXISTS(
						SELECT TOP 1 1 FROM BIZ_TrainOrderCost
						WHERE TOC_COLD_SN = ? AND TOC_Memo like ?
					) 
					INSERT INTO BIZ_TrainOrderCost(
								TOC_Memo,
								TOC_CreateDate,
								TOC_COLI_SN,
								TOC_COLD_SN,
								TOC_TrainNumber,
								TOC_TicketCost,
								TOC_WL
								)
							VALUES(?,getdate(),{$CCSN},?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}))";
			$query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%","途牛退票费 ".$data->TOC_Memo,$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_TicketCost));	
		return $query;	
	}
	
	public function update_status($data){
		$sql = "update 
					TuniuOrderList
				set
					tol_status	   = '9',
					tol_returnCode = '{$data['returnCode']}',
					tol_errorMsg   = '{$data['errorMsg']}'
				where
					tol_retailOrderId = '{$data['retailOrderId']}'
				";
		$query = $this->INFO->query($sql);
        return $query;
	}
	
	public function get_transaction_record(){
		$sql = "select * from TuniuExcel";
		$query = $this->INFO->query($sql);
        return $query->result();
	}
	
	public function get_order_info($order){
		$sql = "SELECT tol_retailOrderId,tol_orderId FROM TuniuOrderList WHERE tol_orderId = '{$order}'";
		$query = $this->INFO->query($sql);
        return $query->result();
	}
	
	public function get_coli_id($cold_sn){
		$sql = "select * from BIZ_ConfirmLineInfo where coli_sn = (select cold_coli_sn from BIZ_ConfirmLineDetail where COLD_SN = '{$cold_sn}')";
		$query = $this->HT->query($sql);
		return $query->result();
	}
	
	function get_gri_no($coli_id){
      $sql="SELECT GRI_No FROM GroupInfo 
              WHERE GRI_SN=(
                  SELECT COLI_GRI_SN FROM BIZ_ConfirmLineInfo WHERE COLI_ID=?
                )
      ";
      $query = $this->HT->query($sql, $coli_id);
      return $query->result();
    }
	
	public function test(){
		$sql = "delete from TuniuOrderList where tol_sn in (18,20)";
		$query = $this->INFO->query($sql);
        return $query;
	}
	
}	

?>