<?php

class BIZ_train_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->HT = $this->load->database('HT', TRUE);
		$this->INFO = $this->load->database('INFO', TRUE);
    }
	
	//新增或更新价格
	public function addOrUpdate($TPL_Train_No,$TPL_Train_Code,$TPL_From_Station_Code,$TPL_To_Station_Code,$TPL_Price){
		$sql = "IF NOT EXISTS(
                        SELECT 1
                        FROM   TrainPriceList
                        WHERE  TPL_Train_Code = '$TPL_Train_Code'
                               AND TPL_From_Station_Code = '$TPL_From_Station_Code'
                               AND TPL_To_Station_Code = '$TPL_To_Station_Code'
                   )  BEGIN
                                INSERT INTO TrainPriceList
                                  (
                                   TPL_Train_No,
								   TPL_Train_Code,
                                   TPL_From_Station_Code,
                                   TPL_To_Station_Code,
                                   TPL_Price,
                                   TPL_Datetime,
								   TPL_Source
                                  )
                                VALUES
                                  (
                                    '$TPL_Train_No','$TPL_Train_Code','$TPL_From_Station_Code','$TPL_To_Station_Code','$TPL_Price',GETDATE(),'juhe'
                                  )   
								END  
				ELSE
					BEGIN
						UPDATE TrainPriceList
						SET    TPL_Train_No			   = '$TPL_Train_No',
							   TPL_Price               = '$TPL_Price',
							   TPL_Datetime            = GETDATE(),
							   TPL_Source			   = 'juhe'
						WHERE  TPL_Train_Code            = '$TPL_Train_Code'
							 AND  TPL_From_Station_Code     = '$TPL_From_Station_Code'
							AND   TPL_To_Station_Code       = '$TPL_To_Station_Code'
					END				
								";
		$query = $this->INFO->query($sql);
        return $query;				
	}
	
	//获取价格
	public function get_price($fromStationCode,$toStationCode,$trainCode){
		$sql = "SELECT 
					TPL_Price 
				FROM 
					TrainPriceList 
				WHERE 
					TPL_Train_Code = '$trainCode'
				AND 
					TPL_From_Station_Code = '$fromStationCode'
				AND	
					TPL_To_Station_Code = '$toStationCode'";
		$query = $this->INFO->query($sql);		
		return $query->row();
	}
	
	
    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
                    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
              FROM   BIZ_BookPeople bbp
              WHERE  BPE_SN in(".$bpe_sn.")          
              ";
        $query = $this->HT->query($sql);
        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();
    }

    //添加聚合订单记录，BIZ_JuheOrderList
    function add_biz_jol($data){
      $sql="
          INSERT INTO BIZ_JuheOrderList(
                JOL_SubTime,
              JOL_COLD_SN,
              JOL_JuheOrder,
              JOL_Status,
              JOL_RebackMsg,
              JOL_FromStation,
              JOL_ToStation,
              JOL_FromStationCode,
              JOL_ToStationCode,
              JOL_TrainCode,
              JOL_BackTxt
              )
          VALUES(getdate(),?,?,?,?,?,?,?,?,?,?)  
       ";
      $query = $this->HT->query($sql, array($data->JOL_COLD_SN,$data->JOL_JuheOrder,$data->JOL_Status,$data->JOL_RebackMsg,$data->JOL_FromStation,$data->JOL_ToStation,$data->JOL_FromStationCode,$data->JOL_ToStationCode,$data->JOL_TrainCode,$data->JOL_BackTxt
        ));
      return $query;
    }
    /* 以下为get_ht_order优化代码 */

    //传入主订单翰特订单号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();
    }

    //传入COLD_SN，获取火车车次等信息
    function get_biz_foi($cold_sn) {
        $sql = "
            SELECT FOI_COLD_SN,
                   FlightsNo,
                   Cabin,
                   DepartureCity,
                   ArrivalCity,
                   DepartureDate,
                   DepartureTime,
                   ArrivalTime,
                   adultcost
            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);
        return $query->result();
    }

    //传入COLI_ID，获取外联名
    function get_operatorinfo($cols_id) {
        $sql = "
            SELECT OPI_Name
            FROM   OperatorInfo
            WHERE  OPI_SN = (
                       SELECT COLI_OPI_ID
                       FROM   BIZ_ConfirmLineInfo bcli
                       WHERE  bcli.COLI_ID = ?
                   )
        ";
        $query = $this->HT->query($sql, $cols_id);
        return $query->result();
    }

    /* 以上为get_ht_order优化代码 */

    //修改BIZ_JuheOrderList
    function update_biz_jol($where,$data){
      return $this->HT->where($where)->update("BIZ_JuheOrderList", $data);
    }

    //获取站点简码
    function get_train_station_code($where){
       $data=$this->HT->where($where)->select("TRS_Code")->from("TrainStation")->get(); 
       return $data->result(); 
    }

    //接收聚合订单号，获取翰特订单号，即BIZ_ConfirmLineInfo的COLI_ID
    function jh_order_get_coli_id($jh_order){
      $sql="SELECT COLI_ID FROM BIZ_ConfirmLineInfo bcli WHERE bcli.COLI_SN=
              (SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail bcld WHERE bcld.COLD_SN=
                (SELECT JOL_COLD_SN FROM BIZ_JuheOrderList bjol WHERE bjol.JOL_JuheOrder= ? )) 
            ";
      $query = $this->HT->query($sql, $jh_order);
      return $query->result();
    }
    //通过COLI_ID获取团名 即 GroupInfo的GRI_No 
    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();
    }
    //通过COLI_ID获取我的支付 BIZ_TrainOrderCost
    function get_train_order_cost($coli_id){
      $sql="SELECT TOC_Memo,TOC_TrainNumber,TOC_DepartureDate,TOC_TicketCost
            FROM BIZ_TrainOrderCost btoc 
            WHERE btoc.TOC_COLI_SN=
              (SELECT COLI_SN FROM BIZ_ConfirmLineInfo bcli 
                  WHERE bcli.COLI_ID=?)";
      $query = $this->HT->query($sql, $coli_id);
      return $query->result();
    }

    //-----------------------------自动出票 begin-----------
    //用于自动出票，传入主订单翰特订单号COLI_SN，获取子订单中火车订单的COLD_SN和COLD_SPFS(寄送票标示，大于1的为寄送)
    public function get_cold_sn($COLI_SN){
      $sql="SELECT COLD_SN,COLD_SPFS
          FROM BIZ_ConfirmLineDetail bcld 
          WHERE bcld.COLD_COLI_SN=?
          AND bcld.DeleteFlag=0 AND bcld.COLD_ServiceType='2'";
      $query = $this->HT->query($sql,$COLI_SN);
      return $query->result();
    }  
    //用于自动出票,传入主订单翰特订单号 COLI_ID ，获取客人的姓名和邮箱
    public function get_guest_info($COLI_ID){
      $sql = "SELECT GUT_LastName,GUT_Email FROM BIZ_GUEST bg WHERE bg.GUT_SN =        
              ( SELECT COLI_GUT_SN FROM BIZ_ConfirmLineInfo bcli WHERE bcli.COLI_ID = ?)
            ";
      $query = $this->HT->query($sql,$COLI_ID);
      return $query->result();
    }
    //通过 JOL_JuheOrder 获取 BIZ_JuheOrderList 获取聚合订单详情
    public function get_biz_jol_info($cold_sn,$jol_jo){
      $sql = "SELECT top 1 
                JOL_SN,
                JOL_COLD_SN,
                JOL_JuheOrder,
                JOL_SubTime,
                JOL_Status,
                JOL_RebackMsg,
                JOL_FromStation,
                JOL_ToStation,
                JOL_FromStationCode,
                JOL_ToStationCode,
                JOL_TrainCode,
                JOL_Price,
                JOL_PayTime,
                JOL_BackTxt
               FROM BIZ_JuheOrderList 
                WHERE JOL_COLD_SN = ? AND JOL_JuheOrder = ? 
            ";
      $query = $this->HT->query($sql,array($cold_sn,$jol_jo));
      return $query->result();      
    }
    // 传入coli_sn获取订单号
    public function coli_sn_get_coli_id($coli_sn){
      $sql="SELECT COLI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN = ? ";
      $query = $this->HT->query($sql,array($coli_sn));
      return $query->result();       
    }
    // 传入 cold_sn 获取订单号
    public function cold_sn_get_coli_id($cold_sn){
      $sql="SELECT COLI_ID FROM BIZ_ConfirmLineInfo
             WHERE COLI_SN = (
                SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN = ?
              )
          ";
      $query = $this->HT->query($sql,array($cold_sn));
      return $query->result();       
    }
    //-----------------------------自动出票 end-----------
	
	 function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) {
        $toName = str_replace("'","''",$toName);
        $body = str_replace("'","''",$body);
        $sql = "INSERT INTO Email_AutomaticSend 
                  ( 
                    M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web,  
                    M_FromName, M_State 
                  ) 
                VALUES 
                  (  
                    ?, ?, N'{$toName}', ?, N'{$subject}', N'{$body}', ?, ?, 0
                  ) ";	
        $query = $this->HT->query($sql, array($fromName, $fromEmail, $toEmail, 'cht', 'information'));
        echo $query;
		
		//return $query;
	 }
}
