<?php

/**
 * core\lib\growth\GrowthCreditRecord.php
 */

/**
 * 积分记录表
 *
 * @author Administrator
 */
class GrowthCreditRecord {
    /**
     *
     * @var type 全局对象的容器，包含db，memcache等
     */
    private $container;
    /**
     *
     * @var String 表名
     */
    private $table;
    
    /**
     *
     * @var array 表中包含的字段
     */
    public static $fields = array('id','broker_id','way_alias','score','credit','description','ctime','discard');


    /**
     * 构造函数，初始化$container,$table属性
     * @param type $weekday 星期
     */
    public function __construct($strDate = null) {
        $container = Container::getInstance();
        $this->db = $container->get('db');
        $this->dbback = $container->get('dbback');
        if ($strDate == '') {
            $strDate = date('Ymd');
        }
        $this->table = "growth_credit_record_" . $strDate;
        $this->credit = new GrowthCredit();
    }
    
    /**
     * 创建表结构
     * @param type $strDate
     * @return type
     */
    public function createTable($tablename) {
        $sql = "CREATE TABLE IF NOT EXISTS `{$tablename}` (
            `id` int(10) unsigned NOT NULL auto_increment,
            `broker_id` int(11) NOT NULL COMMENT '经纪人ID',
            `way_alias` varchar(20) NOT NULL COMMENT '获取途径，关联credit_way表way_alias字段',
            `score` int(11) NOT NULL COMMENT '本次获取积分分值，大于0表示获得，小于0表示扣除',
            `credit` int(11) NOT NULL COMMENT '本次获取后时的积分',
            `description` varchar(256) character set gbk default NULL COMMENT '操作描述',
            `ip` varchar(30) NOT NULL COMMENT '记录操作人的IP地址',
            `ctime` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP COMMENT '积分变化的时间戳',
            `discard` tinyint(4) NOT NULL default '0' COMMENT '是否废弃，1废弃，0正常状态',
            PRIMARY KEY  (`id`),
            KEY `brokerid` (`broker_id`)
          ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='积分变化记录表'";
        return $this->db->execute($sql);
    }
    
    /**
     * 删除表
     * @param type $tablename
     */
    public function dropTable($tablename) {
        $sql = "DROP TABLE  IF EXISTS  $tablename";
        return $this->db->execute($sql);
    }
    
    /**
     * 保存设置的积分分值
     * @param array $fields 包含分值的数组
     * @return boolean
     */
    public function save($fields) {
        $keys = array_keys($fields);
        $sql = "replace into $this->table (".  implode(",", $keys).") value ('".  implode("','", $fields)."')";
        $db = $this->getDb('db');
        if($db->execute($sql)) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 插入一条积分变化记录
     * @param int $brokerId 经纪人id
     * @param String $wayAlias 获取方式别名
     * @param int $score 获取方式对应的分值
     * @param String $description 描述
     * @param int $type 1,用户可见；2，系统可见
     * @param int $discard 是否废弃 ，默认0 ，表示不是废弃的
     * @return boolean
     */
    public function insertData($brokerId,$wayAlias,$score,$description,$type=1,$discard = 0) {
        $arrFieldsValue = array();
        $creditOne = $this->credit->findByBrokerId($brokerId);
        $arrFieldsValue['broker_id'] = $brokerId;
        $arrFieldsValue['way_alias'] = $wayAlias;
        $arrFieldsValue['score'] = $score;
        $arrFieldsValue['credit'] = $creditOne['credit'] - $creditOne['frozen'];;
        $arrFieldsValue['description'] = $description;
        $arrFieldsValue['ip'] = GetIp();
        $arrFieldsValue['type'] = $type;
        $arrFieldsValue['discard'] = $discard;
        $sql = SqlCombinHelper::insert_sql($this->table, $arrFieldsValue);
        return $this->db->execute($sql);
    }
    
    /**
     * 根据经纪人id 查找积分变化记录数据
     * @param int $brokerId 经纪人id
     * @param int $start 开始的记录数
     * @param int $number 返回的条数
     * @param string 排序方式
     * @param int $type 记录类型1，用户可见；2，系统可见
     * @return type
     */
    public function findByBrokerId($brokerId,$start=null,$number=null,$order=null,$type=null) {
        $limit = '';
        if($start !== null&&$number !== null) {
            $limit = "limit $start,$number";
        }
        if($type!==null) {
            $c = ' and type ='.$type.' ';
        } else {
            $c = ' ';
        }
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields,"broker_id = '$brokerId'".$c);
		if($order !== null){
		    $sql .= "order by id $order ";
		}
        $sql .= $limit;

       return $this->dbback->getAll($sql);
    }

        /**
     * 根据名称获得数据库连接
     * @param string $dbname
     * @return Mixed 数据库连接对象
     */
    public function getDb($dbname) {
        return $this->container->get($dbname);
    }
    
    public function findCountByBrokerId($brokerId,$type=null) {
        if($type!==null) {
            $c = ' and type ='.$type;
        } else {
            $c = '';
        }
       $sql = SqlCombinHelper::select_sql($this->table, "count(id) as num","broker_id = '$brokerId' ".$c);
       return $this->dbback->getOne($sql);
    }
    
    public function findSumCreditByBrokerId($brokerId,$type=null) {
        if($type!==null) {
            $c = ' and type ='.$type;
        } else {
            $c = '';
        }
       $sql = SqlCombinHelper::select_sql($this->table, "sum(score) as sum","broker_id = '$brokerId' ".$c);
       return $this->dbback->getOne($sql);
    }
}

?>
