<?php
/**
 * core\lib\growth\GrowthExpDayCount.php
 */

/**
 * 每日成长值统计操作类
 *
 * @author sun
 */
class GrowthExpDayCount {
    /**
     * 主数据库
     */
    private $db;

    /**
     * 从数据库
     */
    private $dbback;

    /**
     * 缓存对象
     */
    private $mc;
    
    /**
     * 关联的表名
     * @var string
     */
    private $table;
    
    /**
     * 表中包含字段
     * @var array
     */
    private static $fields = array('id','ctime','way_alias',
        'broker_id','day_exp');
    
    public function __construct() {
        $container = Container::getInstance();
        $this->db = $container->get('db');
        $this->dbback = $container->get('dbback');
        $this->mc = $container->get('mc');
        //print_r($this->mc);
        $this->table = 'growth_exp_day_count';
    }
    
    /**
     * 根据id编号查找一条记录
     * @param int $id 编号
     * @return array 返回一条记录
     */
    public function findOneById($id) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields,
                'id ='.$id);
        return $this->dbback->getRow($sql);
    }
    
    /**
     * 根据方式别名获取相关记录
     * @param string $wayAlias 方式别名
     * @return array
     */
    public function findAllByWayAlias($wayAlias) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields, 
                "way_alias = '$wayAlias'");
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 根据方式别名和经纪人编号获取相关记录
     * @param type $wayAlias 方式别名
     * @param type $brokerId 经纪人编号
     * @return array
     */
    public function findAllByWayAliasAndBrokerId($wayAlias, $brokerId) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields, 
                "way_alias = $wayAlias AND broker_id = $brokerId");
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 根据方式别名和统计时间获取相关操作数据
     * @param type $wayAlias 方式别名
     * @param type $ctime 统计时间
     * @return array
     */
    public function findAllByWayAliasAndCtime($wayAlias, $ctime) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields, 
                "way_alias = $wayAlias AND ctime = $ctime");
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 根据经纪人编号获取相关操作数据
     * @param type $brokerId 经纪人编号
     * @return array
     */
    public function findAllByBrokerId($brokerId) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields, 
                "broker_id = $brokerId");
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 根据统计时间获取相关操作数据
     * @param type $ctime
     * @return array
     */
    public function findAllByCtime($ctime) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields, 
                "ctime = $ctime");
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 根据经纪人编号和统计时间获取相关操作数据
     * @param type $brokerId 经纪人编号
     * @param type $ctime 统计时间
     * @return array
     */
    public function findOneByBrokerIdAndCtime($brokerId, $ctime) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields, 
                "broker_id = $brokerId AND ctime = $ctime");
        return $this->dbback->getAll($sql);
    }
    
    /**
     * 根据经纪人编号、方式别名和统计时间获取相关操作数据
     * @param date $ctime 统计时间
     * @param string $wayAlias 方式别名
     * @param int $brokerId 经纪人编号
     * @return array 返回一条记录
     */
    public function findOneByUniqueIndex($ctime,$wayAlias,$brokerId) {
        $sql = SqlCombinHelper::select_sql($this->table, self::$fields, 
                "ctime = '$ctime' AND way_alias='$wayAlias'"
                . " AND broker_id=$brokerId");
        return $this->db->getRow($sql);
    }
    
   /**
    * 
    * @param date $ctime 统计时间
    * @param string $wayAlias 获取方式别名
    * @param int $brokerId 经纪人编号
    * @param int $dayExp 成长值
    * @return boolean true返回成功，false返回失败
    */
    public function insertData($ctime,$wayAlias,$brokerId,$dayExp) {
        $arrFieldsValue = array();
        $arrFieldsValue['broker_id'] = $brokerId;
        $arrFieldsValue['way_alias'] = $wayAlias;
        $arrFieldsValue['day_exp'] = $dayExp;
        $arrFieldsValue['ctime'] = $ctime;
        $sql = SqlCombinHelper::insert_sql($this->table, $arrFieldsValue);
        return $this->db->execute($sql);
    }
    
    /**
     * 根据经纪人编号、方式别名和统计时间增加或者减少成长值
     * @param string $ctime 统计时间
     * @param string $wayAlias 获取方式别名
     * @param int $brokerId 经纪人编号
     * @param int $score 成长值
     * @return boolean true返回成功，false返回失败
     */
    public function addScoreToOneByUniqueIndex($ctime,$wayAlias,$brokerId, $score) {
        $score = $score > 0 ? '+' . $score : $score;
        $arrField['day_exp'] = $score;
        $sql = SqlCombinHelper::updateSelf_sql($this->table, $arrField, 
                "ctime = '$ctime' AND way_alias='$wayAlias'"
                . " AND broker_id=$brokerId");
        return $this->db->execute($sql);
    }

    /**
     * 每天增加成长值记录
     * @param string $ctime 统计时间
     * @param string $wayAlias 获取方式别名
     * @param int $brokerId 经纪人编号
     * @param int $score 成长值
     * @return boolean true返回成功，false返回失败
     */
    public function increase($ctime,$wayAlias,$brokerId,$score) {
        $score = abs($score);
        $arrRow = $this->findOneByUniqueIndex($ctime, $wayAlias, $brokerId);
        if (count($arrRow) == 0) {
            $status = $this->insertData($ctime, $wayAlias, $brokerId, $score);
        } else {
            $status = $this->addScoreToOneByUniqueIndex($ctime, $wayAlias, 
                    $brokerId, $score);
        }
        return $status;
    }
    
    /**
     * 每天减少成长值记录
     * @param string $ctime 统计时间
     * @param string $wayAlias 获取方式别名
     * @param int $brokerId 经纪人编号
     * @param int $score 成长值
     * @return boolean true返回成功，false返回失败
     */
    public function reduce($ctime,$wayAlias,$brokerId,$score) {
        $score = '-' . abs($score);
        $arrRow = $this->findOneByUniqueIndex($ctime, $wayAlias, $brokerId);
        if (count($arrRow) == 0) {
            $status = $this->insertData($ctime, $wayAlias, $brokerId, $score);
        } else {
            $status = $this->addScoreToOneByUniqueIndex($ctime, $wayAlias, 
                    $brokerId, $score);
        }
        return $status;
    }
    
    /**
     * 经纪人一天获得成长值的总和
     * @param type $day
     * @param type $brokerId
     * @return type
     */
    public function findCountExpByDay($day, $brokerId) {
        $sql = SqlCombinHelper::select_sql($this->table, 'SUM(day_exp)', 
                "ctime = '$day' AND broker_id = $brokerId");
        return $this->dbback->getOne($sql);
    }

        
    /**
     * 经纪人一天获得成长值的除指定项目外的总和
     * @param type $day
     * @param type $brokerId
     * @param type $wayArr
     * @return type
     */
    public function findCountExpByDayExOther($day, $brokerId,$wayArr) {
        $way = '';
        for($i=0;$i<$j=count($wayArr);$i++){
            $way .= $i == $j-1 ?  "'".$wayArr[$i]."'" :  "'".$wayArr[$i]."',";
        }
        $sql = SqlCombinHelper::select_sql($this->table, 'SUM(day_exp)', 
                "ctime = '$day' AND broker_id = $brokerId AND way_alias NOT IN ($way)");
        return $this->dbback->getOne($sql);
    }

   
    
	/**
     * 根据时间，获取方式id数组和经纪人id获得每日成长值
     * @param string $ctime 日期，格式如：2014-02-20
     * @param array $wayAliasArr 获取方式别名
     * @param int $brokerId 经纪人id
     * @return int 总的成长值
     */
    public function findArrayByTimeWayAliasBrokerId($ctime,$wayAliasArr,$brokerId) {
        $wayAlias = '';
        if (is_array($wayAliasArr)) {
            for($i=0;$i<$j=count($wayAliasArr);$i++){
                $i == $j-1 ? $wayAlias .="'".$wayAliasArr[$i]."'" : $wayAlias .="'".$wayAliasArr[$i]."',";			
            }
        } else {
            $wayAlias = "'" . $wayAliasArr . "'";
        }
        $sql = SqlCombinHelper::select_sql($this->table, "sum(day_exp) as sum_exp", "ctime ='".$ctime."' and way_alias in (".$wayAlias.") and broker_id=$brokerId");       
       return $this->dbback->getOne($sql);
    }

    /**
     * 根据时间，获取方式经纪人每日成长值总和
     * @param string $ctime 日期，格式如：2014-02-20   
     * @param int $brokerId 经纪人id
     * @return int 总的成长值
     */
    public function findExpSumByTimeBrokerId($ctime,$brokerId) {		
        $sql = SqlCombinHelper::select_sql($this->table, "sum(day_exp) as sum_credit", "ctime ='".$ctime."' and broker_id=$brokerId");
        $allBrokerExpNum = $this->mc->get($sql);
        if ($allBrokerExpNum === false) {
            $allBrokerExpNum = $this->dbback->getOne($sql);
            $this->mc->set($sql, $allBrokerExpNum,300); 
        }
        return $allBrokerExpNum;
        //return $this->dbback->getOne($sql);
    }


	/**
     * 当前经纪人小区完善获取经验值总值
     * @param type $brokerId  经纪人id
     * @param type $wayAliasArr 获取途径数组 
     */
    public function getImproveExpCountByUid($brokerId,$wayAliasArr) {
        $wayAlias = '';
        if (is_array($wayAliasArr)) {
            for($i=0;$i<$j=count($wayAliasArr);$i++){
                $i == $j-1 ? $wayAlias .="'".$wayAliasArr[$i]."'" : $wayAlias .="'".$wayAliasArr[$i]."',";			
            }
        } else {
            $wayAlias = "'" . $wayAliasArr . "'";
        }
        $sql = SqlCombinHelper::select_sql($this->table,'sum(day_exp) as num', "broker_id='$brokerId'   and way_alias in (".$wayAlias.")");

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

   /**
	**获取小区完善当天获取积分的人数
	**@param string $ctime  时间格式如：2014-02-23
	**@return int 返回人数
	**
	**/
	public function findBrokerImproveNumber($ctime,$wayAliasArr){
        $wayAlias = '';
        if (is_array($wayAliasArr)) {
            for($i=0;$i<$j=count($wayAliasArr);$i++){
                $i == $j-1 ? $wayAlias .="'".$wayAliasArr[$i]."'" : $wayAlias .="'".$wayAliasArr[$i]."',";			
            }
        } else {
            $wayAlias = "'" . $wayAliasArr . "'";
        }
		$sql = SqlCombinHelper::select_sql($this->table, "count(DISTINCT(broker_id)) as num", "ctime ='".$ctime."' and way_alias in (".$wayAlias.") ");
        return $this->dbback->getOne($sql);
	}

   /**
	**获取小区完善当天获取积分比我少的经纪人个数
	**@param string $ctime  时间格式如：2014-02-23  
	**@param array    $wayAliasArr 获取途径数组 
	**@param int   $myCredit 我获取的积分
	**return  int  
	**/
	public function findImproveBelowExpBroker($ctime,$wayAliasArr,$myCredit){
        $wayAlias = '';
        if (is_array($wayAliasArr)) {
            for($i=0;$i<$j=count($wayAliasArr);$i++){
                $i == $j-1 ? $wayAlias .="'".$wayAliasArr[$i]."'" : $wayAlias .="'".$wayAliasArr[$i]."',";			
            }
        } else {
            $wayAlias = "'" . $wayAliasArr . "'";
        }
	   $sql = SqlCombinHelper::select_sql($this->table, "count(id) as num", "ctime = '$ctime' and way_alias in (".$wayAlias.") GROUP BY broker_id HAVING SUM(day_credit) < $myCredit");
	   $brokerArr = $this->dbback->getAll($sql);
       $result = count($brokerArr);
       return $result;
	}
    
	/**
     * 根据时间和别名获取当前成长值及排名
     * @param type $brokerId  经纪人id
     * @param string $ctime  时间格式如：2014-02-23
     * @param type $wayAliasArr 获取途径数组 
     */
    public function getExpAndRank($brokerId, $wayAliasArr, $ctime = null) {
        if ($ctime == null) {
            $ctime = date('Y-m-d');
        }
        if (is_array($wayAliasArr)) {
            $key = md5(serialize($wayAliasArr) . $brokerId . $ctime);
        } else {
            $key = md5($wayAliasArr . $brokerId . $ctime);
        }
        //$this->mc->delete($key);
        $result = $this->mc->get($key);
        //当日操作别名获取的成长值数
        $publishHouseDayExp = $this->findArrayByTimeWayAliasBrokerId($ctime, $wayAliasArr, $brokerId);
        $publishHouseDayExp = $publishHouseDayExp == '' ? 0 : $publishHouseDayExp;
        if ($result === false) {
            //总的经纪人数
            $growthExp = new GrowthExp();
            $allBrokerExpNum = $growthExp->findCountBrokerAndExpInfo();
            //$allBrokerExpNum = count($allBrokerExpInfo);

            //获取全市有多少经纪人 - 当天参加获取途径的经纪人人数 = 得到没有参加的经纪人数
            //得到没有参加的经纪人数 + 当天发布少于本人的其他经纪人人数 = 得到排名数

            //当天参加发布房源的经纪人数
            $dayPublishBrokerNum = $this->findBrokerImproveNumber($ctime, $wayAliasArr);

            //当天发布少于本人的其他经纪人数
            //$dayPublishBelowBrokerNum = $this->findImproveBelowExpBroker($ctime,$wayAliasArr,$publishHouseDayExp) - 1;

            //当前名次
            $rank = $allBrokerExpNum - $dayPublishBrokerNum;
            if ($allBrokerExpNum == 0) {
                $brokerExpPlot = 100;
            } else {
                //你打败了多少经纪人
                $brokerExpPlot = ceil((($rank) / $allBrokerExpNum)*100);
            }
            if($brokerExpPlot >= 100){
               $brokerExpPlot = 99;
            }
            $result = array( 'rank' => $rank, 'rate' => $brokerExpPlot);
            $this->mc->set($key, $result, false, 3600);
        }
        $result['exp'] = $publishHouseDayExp;
        //print_r($result);
        return $result;
    }
}
