<?php

/**
 * 流量日志
 *
 * @author yzxh24
 */
class FluxLog
{
    private static $_dataBase = 'u1db5';
    
    /**
     * 汇总一天的总流量
     * @param string $date
     * @param CDbCriteria $criteria
     * @return int
     */
    public static function SumDay($date = null, CDbCriteria $criteria = null)
    {
        $table = self::getTable();
        if (is_null($criteria))
        {
            $criteria = new CDbCriteria();
            $criteria->select = 'COUNT(1) AS count';
        }

        try
        {
            $builder = Yii::app()->getDb()->getCommandBuilder();
            $command = $builder->createFindCommand($table, $criteria);
            $count = $command->queryScalar();
        }
        catch (CDbException $e)
        {
            return $e->getMessage();
        }
        return $count;
    }

    /**
     * 流量分时数据
     * @param string $date
     * @param CDbCriteria $criteria
     * @return array
     */
    public static function TimeSharing($date = null, CDbCriteria $criteria = null)
    {
        $table = self::getTable();
        if (is_null($criteria))
        {
            $criteria = new CDbCriteria();
            $criteria->select = "COUNT(1) AS count, DATE_FORMAT(createdate, '%H') AS hour";
            $criteria->group = 'hour';
        }
        try
        {
            $builder = Yii::app()->getDb()->getCommandBuilder();
            $command = $builder->createFindCommand($table, $criteria);
            $result = $command->queryAll();
        }
        catch (CDbException $e)
        {
            echo $e->getMessage();
        }

        return $result;
    }

    /**
     * 获取完整日志数据库名
     * @param string $date
     * @return string
     */
    public static function getTable($date = null)
    {
        return self::$_dataBase . '.access_log_' . (is_null($date) ? date('Ymd') : $date);
    }
}