<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * 用户中心-我的成长 
 */
class Ucenter_growth extends MY_Controller {

    /**
     * 解析函数
     *
     * @access public
     * @return void
     */
    public function __construct() 
    {
        parent::__construct();
    }

    /**
     * Index Page for this controller.
     */
    public function index() {
        //加载broker模型类
        $this->load->model('broker_model');
        $this->load->model('payment_model');
        $css = load_css('zsb/css/v1.0/style1.css');
        $info = $this->broker_model->get_user_session();
        $groupId = $info['package_id'];//套餐
        $brokerType = $info['is_pay'] == payStatus ? '1' : '0';//免费or付费
        $gbe = new GrowthBrokerExp(array('id'=>$info['uid'],'groupid'=>$groupId));
        $gbc = new GrowthBrokerCredit(array('id'=>$info['uid'],'groupid'=>$groupId));
        $allLevel = $this->allLevel();
        //等级
        $info['level'] = $gbe->getLevel(2);
        //经验
        $info['exp'] = $gbe->getExp();
        //升级天数
        $info['nextLevel'] = $this->nextLevel($info['level'],$allLevel);
        $growthExpDayLimit = $this->getGroupDayMaxExp($groupId);
        $info['level_day'] = $this->calUpgradeDays($info['nextLevel'],$growthExpDayLimit,$info['exp']);
        
        //房豆
        $info['credit'] = $gbc->getValidCredit();

        //经纪人总数
        $info['brokerNumber'] = $gbe->getBrokerNumber();
        //当前用的排序名次
        $info['rank'] = $gbe->getRank($info['brokerNumber'],$info['exp']);
        //当前用的排序名次百分比
        $info['rankRate'] = $info['brokerNumber']?intval(($info['brokerNumber']-$info['rank'])/$info['brokerNumber']*100):0;
        $info['rankRate'] = $info['rankRate'] ==100 ? 99 :$info['rankRate'];
        
        //头像
        $info['smallphoto'] = $info['smallphoto'] ? $info['smallphoto'] : "<?=STATIC_SOURCE_URL?>/zsb/images/v1.0/defaultface.jpg";

        //经验条长度
        $expBar = $this->expbar($info['level']);
        $this->load->model("broker_package_model",'package');
        $package = $this->package->find_by_id($info['package_id']);
        $groupNumber = $package['package_valid_num'];
        $groupRefreshNumber = $package['package_refresh_num'];
        //任务数据
		// 2016-1-14 添加星级数据 -----------start -------->
		
		$broker_new_info =$this->broker_model->get_broker_info_by_uid($info['uid']);
		// 2016-1-14 添加星级数据 -----------end -------->

		$documentation = $this->config->item('documentation');
        $is_open_housebean = $this->config->item('is_open_housebean');

        $taskData = array();
        $viewData = array();
        $viewData['page_title'] = '租售宝-个人中心';
        $viewData['js'] = load_js('common/js/jquery.jcountdown.js');
        $viewData['css'] = $css;
        $viewData['info'] = $info;
        $viewData['expBar'] = $expBar;
        $viewData['taskData'] = $taskData;
		$viewData['documentation'] = $documentation;
        $viewData['is_open_housebean'] = $is_open_housebean;
        $viewData['payment_model'] = $this->payment_model;
		$viewData['broker_new_info'] = $broker_new_info;
        $viewData['my_privilege'] = $this->my_privilege($info['level'],$brokerType,$info['credit'],$groupId);
		$viewData['google_analytics'] = get_ga_js_code('/个人中心/我的成长/');
		
		$viewData['functionSwitch'] = $this->config->item('functionSwitch');   //功能开关	

        $this->view('ucenter', 'ucenter/my_growth', $viewData);
    }

    /**
     * 经验条
     */
    public function expbar($level){
            switch($level){
                    case '1': $levelLinePlot = 0;			
                            break;
                    case '2': $levelLinePlot = 10;			
                            break;
                    case '3': $levelLinePlot = 18.5;			
                            break;
                    case '4': $levelLinePlot = 23;			
                            break;
                    case '5': $levelLinePlot = 28;			
                            break;
                    case '6': $levelLinePlot = 34.5;			
                            break;
                    case '7': $levelLinePlot = 42;			
                            break;
                    case '8': $levelLinePlot = 51;			
                            break;
                    case '9': $levelLinePlot = 58;			
                            break;
                    case '10': $levelLinePlot = 67;			
                            break;
                    case '11': $levelLinePlot = 74;			
                            break;
                    case '12': $levelLinePlot = 83;			
                            break;
                    case '13': $levelLinePlot = 88;			
                            break;
                    case '14': $levelLinePlot = 94;			
                            break;
                    case '15': $levelLinePlot = 100;			
                            break;
            default : $levelLinePlot = 0;

            }
            return $levelLinePlot;
    }
    
    /**
     * 发布房源获取房豆任务信息
     */
    private function taskPublishHouse($brokerId,$groupId,$groupNumber) {
        $res['cur'] = $this->publishHouseScore($brokerId);//今日获得的房豆
        $res['one'] = $this->getYouZhiScore($groupId);//发布一条奖励的分数
        $res['usedNumber'] = $this->getUsedHouseNumber($brokerId);//已用多少条房源
        $pLimit = $this->publishHouseLimit($groupId);
        $res['max'] = $pLimit<$groupNumber?$pLimit*$res['one']:$groupNumber*$res['one'];
        $res['link'] = '####';
        return $res;
    }
    
    /**
     * 套餐当天发房源送房豆限制的房源数量
     * @param type $groupId
     */
    private function publishHouseLimit($groupId) {
        $key = 'growth_credit_way_alias_package_dayHouseNum'.$groupId;
        $upperLimitNum = $this->mc->get($key);
        if($upperLimitNum === false){
           $expControllPackage = new GrowthExpControllPackage();  
           $upperLimitNum = $expControllPackage->findScoreByWayAliasPackageId('dayHouseNum', $groupId);
           //echo $upperLimitNum ;exit;
           $this->mc->set($key,$upperLimitNum,6000);	
        }
        return $upperLimitNum;
    }

        /**
     * 今日已获得的房豆
     * @param type $brokerId
     * @return type
     */
    private function publishHouseScore($brokerId) {
//        //当日发布房源已获房豆
//        $this->load->driver('cache');
//        $key = md5('nj_Ucenter_growth_taskPublishHouse_brokerid_'.$brokerId);
//        $res = $this->cache->memcached->get($key);
//        $this->cache->memcached->save($key, $res, 10);
//        if($res===false) {
            $creditPublishEventArray = array('pQualityHouse','pStarHouse','pNoStarHouse');
            $growthCreditDayCount = new GrowthCreditDayCount();
            $ctime = date('Y-m-d');
            $publishHouseDayCredit = $growthCreditDayCount->findArrayByTimeWayAliasBrokerId($ctime,$creditPublishEventArray,$brokerId);
            $publishHouseDayCredit = $publishHouseDayCredit == '' ? 0 : $publishHouseDayCredit; 
            return $publishHouseDayCredit;
    }
    
    /**
     * 刷新房源获取房豆任务信息
     */
    private function taskRefreshHouse($brokerId, $groupId,$groupRefreshNumber) {
        $res['cur'] = $this->refreshHouseScore($brokerId);//今日获得的房豆
        $res['one'] = $this->getRefreshOneScore($groupId);//刷新一条奖励的分数
        $res['usedNumber'] = $this->getRefreshHouseNumber($brokerId);//已刷新多少条房源
        //$pLimit = $this->publishHouseLimit($groupId);
        $res['max'] = $groupRefreshNumber*$res['one'];
        $res['link'] = '####';
        return $res;
    }
    
    /**
     * 当日刷新房源已领到的分数
     * @param type $brokerId
     */
    private function refreshHouseScore($brokerId) {
        $growthCreditDayCount = new GrowthCreditDayCount();
        $ctime = date('Y-m-d');
        $refreshHouseDayCreditCount = $growthCreditDayCount->findArrayByTimeWayAliasBrokerId($ctime,array('refreshHouse'),$brokerId);
        //print_r($refreshHouseDayCreditCount);exit;
        $refreshHouseDayCreditCount['day_credit'] = $refreshHouseDayCreditCount['day_credit'] == '' ? 0 : $refreshHouseDayCreditCount['day_credit'];
        return $refreshHouseDayCreditCount['day_credit'];
    }
    
    /**
     * 刷新一条房源可得的分
     */
    private function getRefreshOneScore($groupId) {
        //刷新一条可获得的房豆
        $key = 'growth_credit_way_alias_package_refreshHouse'.$groupId;
        $refreshHouseScore = $this->mc->get($key);
        if($refreshHouseScore === false){
            $growthCreditWayPackage = new GrowthCreditWayPackage();
            $refreshHouseScore = $growthCreditWayPackage->getScoreByWayAliasAndPackageId('refreshHouse',$groupId);
            $this->mc->set($key,$refreshHouseScore,6000);
        }
        return $refreshHouseScore;
    }
    /**
     * 已刷新多少房源
     * @param type $brokerId
     */
    private function getRefreshHouseNumber($brokerId) {
        $this->load->model("log_refresh");
        $refreshnum = $this->log_refresh->findTodayNumberByBrokerId($brokerId);
        //print_r($refreshnum);exit;
        //$refreshnum = (int)$dbback->GetOne($sql); //今日刷新量
        return $refreshnum;
    }

    /**
     * 完善小区获取房豆任务信息
     */
    private function taskImproveBlock($brokerId,$groupId) {
        $res['cur'] = $this->improveBlockScore($brokerId);//今日获得的房豆
        $res['one'] = $this->getImproveBlockOneScore($groupId);//刷新一条奖励的分数
        //$res['usedNumber'] = $this->getRefreshHouseNumber($brokerId);//已刷新多少条房源
        //$pLimit = $this->publishHouseLimit($groupId);
        //$res['max'] = $groupRefreshNumber*$res['one'];
        $res['link'] = '####';
        return $res;
    }
    
    /**
     * 每发布一条优质房源的分数
     */
    private function getYouZhiScore($groupId) {
        $key = md5('nj_growth_credit_way_alias_package_pQualityHouse'.$groupId);
        $pubGoodHouseScore = $this->mc->get($key);
        if($pubGoodHouseScore === false){
           $growthCreditWayPackage = new GrowthCreditWayPackage();
           $pubGoodHouseScore = $growthCreditWayPackage->getScoreByWayAliasAndPackageId('pQualityHouse',$groupId);
           $this->mc->set($key, $pubGoodHouseScore, 6000);
        }
        return $pubGoodHouseScore;
    }
    
    
    /**
     * 当日已发房源量
     * @param type $brokerId
     */
    private function getUsedHouseNumber($brokerId) {
        return 0;
        $this->load->model('sell_model','sell');
        $this->load->model('rent_model','rent');
        //print_r($this->sell);exit;
        $startTime = strtotime(date('Y-m-d',time()));//当天零点时间戳
        $endTime = $startTime+3600*24;//第二天时间戳	
        $where = "uid = '$brokerId' and infofrom = '5' and esta = 1 and creattime > $startTime AND creattime < $endTime";
        $sellNum = $this->sell->find_count_by($where);
        $rentNum = $this->rent->find_count_by($where);
        $publishHouseNum = $sellNum + $rentNum;//当天发房源数量
        return $publishHouseNum;
    }
    
    /**
     * 每日套餐可以获得最高分值
     */
    private function getGroupDayMaxExp($groupId) {
        //套餐每天最高获取成长值
        $growthExpControllPackage = new GrowthExpControllPackage();
        $key = 'growth_exp_limit'.$groupId;
        $growthExpDayLimit = $this->mc->get($key);
        if($growthExpDayLimit === false){//echo 1;exit;
            $growthExpDayLimit = $growthExpControllPackage->findScoreByWayAliasAndPackageId('dayExpLimit',$groupId);
            $this->mc->set($key,$growthExpDayLimit,6000);
        }
        return $growthExpDayLimit;
    }
    /**
     * 计算升级天数
     */
    private function calUpgradeDays($nextLevel,$growthExpDayLimit,$exp) {
        if ($growthExpDayLimit == 0) {
            $growthExpDayLimit = 1;
        }
        $days = ceil(($nextLevel['down_exp']-$exp)/$growthExpDayLimit);
        return $days;
    }
    
    /**
     * 今日完善小区资料获得的房豆
     */
    private function improveBlockScore($brokerId) {
        $creditBlockEventArray = array('pABlockContri','uABlockContri','pBBlockContri','uBBlockContri','pCBlockContri','uCBlockContri','pDBlockContri','uDBlockContri');
        $growthCreditDayCount = new GrowthCreditDayCount();
        $ctime = date('Y-m-d');
        $sumBlockDayCredit=$growthCreditDayCount->findArrayByTimeWayAliasBrokerId($ctime,$creditBlockEventArray,$brokerId);
        $sumBlockDayCredit = $sumBlockDayCredit?$sumBlockDayCredit: 0;
        return $sumBlockDayCredit;
    }
    
    /**
     * 完善一项小区信息获得房豆数
     */
    private function getImproveBlockOneScore($groupId) {
        $key = 'growth_credit_way_alias_package_pDBlockContri'.$groupId;
        $pDBlockContriScore = $this->mc->get($key);
        if($pDBlockContriScore === false){
            $growthCreditWayPackage = new GrowthCreditWayPackage();
            $pDBlockContriScore = $growthCreditWayPackage->getScoreByWayAliasAndPackageId('pDBlockContri',$groupId);
                $this->mc->set($key,$pDBlockContriScore,6000);	    
        }
        return $pDBlockContriScore;
    }
    
    /**
     * 返回下一个等级
     * @param type $level
     * @param type $allLevel
     * @return boolean
     */
    private function nextLevel($level,$allLevel) {
        if($allLevel) {
            foreach ($allLevel as $key => $value) {
                if($value['level_id']==$level+1) {
                    return $value;
                }  else {
                    continue;
                }
            }
            return FALSE;
        }
    }
    
    /**
     * 返回全部等级数组
     * @return type
     */
    private function allLevel() {
        $key = "growth_level_data";
        $allLevel = $this->mc->get($key);
        if($allLevel === false) {
            $growthLevel = new GrowthLevel();
            $allLevel = $growthLevel->findAllLevelData();
            $this->mc->set($key,$allLevel,600);	
        }
        return $allLevel;
    }
    
    private function my_privilege($brokerLevel,$brokerType,$brokerCredit,$packageid) {
        $privilege = array();
		
        //$privilege[] = $this->getPrivilegeBlockExpert($brokerLevel, $brokerType, $brokerCredit,$packageid);
        //$privilege[] = $this->getPrivilegeBuy($brokerLevel, $brokerType, $brokerCredit,$packageid);
        //$privilege[] = $this->getPrivilegeRent($brokerLevel, $brokerType, $brokerCredit,$packageid);
        $this->load->library('TeQuan');
        $privilege = $this->tequan->init($brokerLevel,$brokerType,$brokerCredit,$packageid)->getAll();
        //var_dump($x);exit;
        $data = array();
        $data['privilege'] = $privilege;
        return $this->load->view('ucenter/my_privilege.php',$data,true);
    }
    /**
     * 
     * @param type $brokerLevel 经纪人等级
     * @param type $brokerType 经纪人类型，付费or免费
     * @param type $brokerCredit 经纪人房豆
     * @param type $packageid 经纪人套餐类型
     */
    private function getPrivilegeBlockExpert($brokerLevel,$brokerType,$brokerCredit,$packageId) {
        $key = "PrivilegeBlockExpert_".$brokerLevel."_".$brokerType."_".$brokerCredit."_".$packageId;
        $p = $this->mc->get($key);
        if($p===false) {
            $p = array();
            $permi = new GrowthLevelWayPermission();
            $minLevel = $permi->findMinLevelByWayAliasAndType('bidAExperts');
            //$gcreditWayPackage = new GrowthCreditWayPackage();
            //$minCredit = $gcreditWayPackage->getScoreByWayAliasAndPackageId('bidAExperts', $packageid);
            $minCredit = 500;
            $p['name'] = '小区专家';
            $p['level'] = $minLevel;//等级要求
            if($brokerType==1&&$brokerCredit>=$minCredit&&$brokerLevel>=$minLevel) {
                $p['allow'] = TRUE;//是否允许
            } else {
                $p['allow'] = FALSE;//是否允许
            }
            $gbuserbroker = new GrowthBidUserBroker();
            $p['using'] = $gbuserbroker->findCountByType(1);//正在使用人数
            $p['intro'] = '7天搜索列表页、小区频道稀缺推广位全部房豆换。发布5条同一小区不同出售多图房源，即可申请该小区的小区专家。申请成功小区专家，热门小区代言人就是你！500房豆就可申请，还不快行动？！';//介绍
            $p['img'] = $p['allow']?'tqXqzjIco.png':'tqXqzjIco.png';//tqqgppIco.png,tqqzppIco.png
            $btn = array();
            if($p['allow']) {
                $btn = array('link'=>'/market_block_expert/','text'=>'快去参与','class'=>'btnColor_p');
            }else {
                if($brokerType!=1) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'暂无权限','class'=>'btnColor_p_no btnColor_p_no_w150');
                }elseif ($brokerCredit<500) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'房豆不够','class'=>'btnColor_p_no btnColor_p_no_w150');
                } elseif ($brokerLevel<$minLevel) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'等级不够','class'=>'btnColor_p_no btnColor_p_no_w150');
                }
            }
            $p['btn'] = $btn;
            $this->mc->set($key,$p,6000);
        }
        return $p;
    }

    /**
     * 求购匹配特权
     * @param type $brokerLevel
     * @param type $brokerType
     * @param type $brokerCredit
     * @param type $packageId
     * @return string
     */
    private function getPrivilegeBuy($brokerLevel,$brokerType,$brokerCredit,$packageId) {
        $key = "PrivilegeBuy_".$brokerLevel."_".$brokerType."_".$brokerCredit."_".$packageId;
        $p = $this->mc->get($key);//$p = false;
        if($p===false) {
            $p = array();
            $permi = new GrowthLevelWayPermission();
            $minLevel = $permi->findMinLevelByWayAliasAndType('matchBuy');
            $growthCwp = new GrowthCreditWayPackage();
            $minCredit = $growthCwp->getScoreByWayAliasAndPackageId('matchBuy', $packageId);
            $p['name'] = '求购匹配';
            $p['level'] = $minLevel;//等级要求
            if($brokerType==1&&$brokerCredit>=$minCredit&&$brokerLevel>=$minLevel) {
                $p['allow'] = TRUE;//是否允许
            } else {
                $p['allow'] = FALSE;//是否允许
            }
            //$gbuserbroker = new GrowthBidUserBroker();
            //$p['using'] = $gbuserbroker->findCountByType(1);//正在使用人数
            
            $this->load->model('buy_match_model');
            $p['using'] = $this->buy_match_model->get_matchednum();

            
            $p['intro'] = '这里有迫切求购意向的精准客户，这里有细化到区位、面积、价格的真实需求，这里更有100%真实可靠的客户联系方式。使用房豆兑换即可匹配需求，抓住精准用户，迅速开单，从求购匹配开始！';//介绍
            $p['img'] = $p['allow']?'tqqgppIco.png':'tqqgppIco.png';//tqqgppIco.png,tqqzppIco.png
            $btn = array();
            if($p['allow']) {
                $btn = array('link'=>'/house_demands/buy/','text'=>'快去参与','class'=>'btnColor_p');
            }else {
                if($brokerType!=1) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'暂无权限','class'=>'btnColor_p_no btnColor_p_no_w150');
                }elseif ($brokerCredit<500) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'房豆不够','class'=>'btnColor_p_no btnColor_p_no_w150');
                } elseif ($brokerLevel<$minLevel) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'等级不够','class'=>'btnColor_p_no btnColor_p_no_w150');
                }
            }
            $p['btn'] = $btn;
            $this->mc->set($key,$p,6000);
        }
        return $p;
    }

    /**
     * 求租匹配特权
     * @param type $brokerLevel
     * @param type $brokerType
     * @param type $brokerCredit
     * @param type $packageId
     * @return string
     */
    private function getPrivilegeRent($brokerLevel,$brokerType,$brokerCredit,$packageId) {
        $key = "PrivilegeRent_".$brokerLevel."_".$brokerType."_".$brokerCredit."_".$packageId;
        $p = $this->mc->get($key); //$p = false;
        if($p===false) {
            $p = array();
            $permi = new GrowthLevelWayPermission();
            $minLevel = $permi->findMinLevelByWayAliasAndType('matchRent');
            $growthCwp = new GrowthCreditWayPackage();
            $minCredit = $growthCwp->getScoreByWayAliasAndPackageId('matchRent', $packageId);
            //var_dump($minCredit);exit;
            //$minCredit = 500;
            $p['name'] = '求租匹配';
            $p['level'] = $minLevel;//等级要求
            if($brokerType==1&&$brokerCredit>=$minCredit&&$brokerLevel>=$minLevel) {
                $p['allow'] = TRUE;//是否允许
            } else {
                $p['allow'] = FALSE;//是否允许
            }
            //$gbuserbroker = new GrowthBidUserBroker();
            //$p['using'] = $gbuserbroker->findCountByType(1);//正在使用人数
            $this->load->model('rent_match_model');
            $p['using'] = $this->rent_match_model->get_matchednum();
            $p['intro'] = '这里有迫切求购意向的精准客户，这里有细化到区位、面积、价格的真实需求，这里更有100%真实可靠的客户联系方式。使用房豆兑换即可匹配需求，抓住精准用户，迅速开单，从求购匹配开始！';//介绍
            $p['img'] = $p['allow']?'tqqzppIco.png':'tqqzppIco.png';//tqqgppIco.png,tqqzppIco.png
            $btn = array();
            if($p['allow']) {
                $btn = array('link'=>'/house_demands/rent/','text'=>'快去参与','class'=>'btnColor_p');
            }else {
                if($brokerType!=1) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'暂无权限','class'=>'btnColor_p_no btnColor_p_no_w150');
                }elseif ($brokerCredit<500) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'房豆不够','class'=>'btnColor_p_no btnColor_p_no_w150');
                } elseif ($brokerLevel<$minLevel) {
                    $btn = array('link'=>'javascript:void(0)','text'=>'等级不够','class'=>'btnColor_p_no btnColor_p_no_w150');
                }
            }
            $p['btn'] = $btn;
            $this->mc->set($key,$p,6000);
        }
        return $p;
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
