<?php
class tuniuprice_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->INFO = $this->load->database('INFO', TRUE);
    }
	
	//新增或更新缓存
	public function addOrUpdate($tpc_from_station,$tpc_to_station,$tpc_content){
		$sql = "IF NOT EXISTS(
                        SELECT 1
                        FROM   TrainPriceCache
                        WHERE 
								tpc_from_station = '$tpc_from_station'
                               AND tpc_to_station = '$tpc_to_station'
                   )  BEGIN
                                INSERT INTO TrainPriceCache
                                  (
                                   tpc_from_station,
                                   tpc_to_station,
                                   tpc_content,
                                   tpc_datetime,
								   tpc_source
                                  )
                                VALUES
                                  (
                                   '$tpc_from_station','$tpc_to_station','$tpc_content',GETDATE(),'tuniu'
                                  )   
								END  
				ELSE
					BEGIN
						UPDATE TrainPriceCache
						SET    tpc_from_station		   = '$tpc_from_station',
							   tpc_to_station          = '$tpc_to_station',
							   tpc_content			   = '$tpc_content',
							   tpc_datetime            = GETDATE(),
							   tpc_source			   = 'tuniu'
						WHERE  
								tpc_from_station     = '$tpc_from_station'
							AND   tpc_to_station       = '$tpc_to_station'
					END				
								";
		$query = $this->INFO->query($sql);
        return $query;				
	}
	
	//获取缓存的火车信息
	//如果读取到缓存是7天以前的数据就不返回任何数据，并且将其删除。
	public function get_train_cache($tpc_from_station,$tpc_to_station){
		$sql = "SELECT 
						* 
				FROM 
					TrainPriceCache 
				WHERE 
					tpc_from_station = '$tpc_from_station'
				AND	
					tpc_to_station = '$tpc_to_station'";
		$query = $this->INFO->query($sql);
		return $query->row();
	}
	
	//获取价格
	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();
	}
}
?>