<?php

/*
 * 版权所有，盗版必查水表
 */

/**
 * Description of GrowthBrokerBid
 *
 * @author Administrator
 */
class GrowthBrokerBidSchoolExpert {
    
    const HOUSE_NUMBER_LIMIT = 4;
    const BID_ERROR_AUTH_IS_PAY = 1;//表示不是付费经纪人
    const BID_ERROR_AUTH_CREDIT = 2;//表示积分不足
    const BID_ERROR_AUTH_HOUSE=3;//表示经纪人在该小区的房源不足
    const BID_ERROR_AUTH_LEVEL=4;//表示经纪人等级不够
    const BID_ERROR_AUTH_SCORE = 5;//表示投入的积分不足
    const BID_ERROR_SYS_DB = 10;//数据库错误
    const BID_ERROR_FINISH = 100;//竞投结束，不能再提交竞投
    const BID_ERROR_MIN_TIME = 200;//时间不足

    const BID_NEED_SCORE_TYPE_WIN = 2;//投中情况下
    const BID_NEED_SCORE_TYPE_NOT_WIN_1 = 1;//未投中,已投的人>=4个
    const BID_NEED_SCORE_TYPE_NOT_WIN_0 = 0;//未投中,已投的人<4个

    const BID_MIN_TIME = 2;//竞投操作的最小时间间隔,单位秒
    
    /**
     * 积分模式 或房豆模式
     * @var type 
     */
    private $mode;

        /**
     * 1,成功 2,失败,3,暂未投放,4,暂未投中,5,竞投中
     * @var type 
     */
    public static $bidBehavior = array(
        'success' => 1, 'failure' => 2, 'noPut' => 3, 
        'noHit' => 4, 'on' => 5, 'tempHit' => 6
    );
    
    public static $bidProjectName = '学区专家';
    
    private $broker;
    /**
     *
     * @var GrowthBid 
     */
    private $growthBid;
    /**
     *
     * @var GrowthBidRecordOn 
     */
    private $growthBidRecord;
    /**
     *
     * @var GrowthBidRecordHistory 
     */
    private $growthBidRecordHistory;
    
    /**
     *
     * @var GrowthBrokerCredit 
     */
    private $growthBrokerCredit;
    
    /**
     *
     * @var Adodb 
     */
    private $dbback;
    
    private $brokerBlock;
    /**
     *
     * @var 竞投 
     */
    private $schoolExpertBidsNew;
    /**
     *
     * @var array 
     */
    private $bidError;
    
    private $growthBidPeriods;

    /**
     * 自定义竞投名额列表
     * @var type 
     */
    private $customNumberList = array();

    private $additionalScore=1;
    /**
     * 
     * @param array $broker array("id"=>'','agentcode'=>'','agentname'=>'','level'=>'','is_pay'=>'')
     */
    public function __construct($broker,$growthBrokerCredit,$mode='credit') {
        $this->dbback = Container::getInstance()->get('dbback');
        $this->broker= $broker;
        $this->growthBid = new GrowthBidSchoolExpert();
        $this->growthBidRecord = new GrowthBidSchoolExpertRecordOn();
        $this->growthBidRecordHistory = new GrowthBidSchoolExpertRecordHistory();
        $this->growthBrokerCredit = $growthBrokerCredit;
        $this->growthBidPeriods = new GrowthBidPeriods();
        $this->mode = $mode;
    }
    
    /**
     * 设置追加的最低分数
     * @param type $additionalScore
     */
    public function setAdditionalScore($additionalScore) {
        $this->additionalScore = $additionalScore;
    }

    /**
     * 获取最低追加分数
     * @return type
     */
    public function getAdditionalScore() {
        return $this->additionalScore;
    }

    public function setCustomNumberList($customNumberList) {
        $this->customNumberList = $customNumberList;
    }
    
    public function getCustomExpertNumberList() {
        return $this->customNumberList;
    }
    
    public function bid($bidId,$score) {
        //var_dump($this->controlTime());exit;
        if($this->controlTime()==false) {
            $this->bidError['errorCode'] = self::BID_ERROR_MIN_TIME;
            return false;
        }
        $brokerId = $this->broker['id'];
        $bid = $this->growthBid->findById($bidId);
        if(!$bid) {
            return false;
        }
        $bidPeriodsId = $bid['bid_periods_id'];
        $schoolId = $bid['school_id'];
        $schoolMg = new School();
        $school = $schoolMg->findOneBy($schoolId);//学区
        //我的竞投记录
        $myRecord = $this->growthBidRecord->findOneBy($brokerId, $bidId);
        //本竞投的记录
        $winnerRecord = $this->findTempWinnerRecord($bid);
        $x = $this->checkByRecord($bid,$score,$winnerRecord,$myRecord);
        if($x) {
            //可以竞投
            //判断当前是哪种竞投状态，-1，未投过；0，未投中；1，2，3，4投中了当前是在追加
            $winFlag = $this->checkWinBid($winnerRecord, $myRecord);
            switch ($winFlag) {
                case '-1'://未投过
                    //首次--》添加竞投记录，statua=1；参加竞投人数number=number+1；冻结积分score；
                    $fieldData = array('broker_id'=>$brokerId,
                        'bid_id'=>$bidId,
                        'score'=>$score,
                        'school_id'=>$schoolId,
                        'school_name'=>$school['schoolname'],
                        'bid_periods_id'=>$bidPeriodsId);
                    $recordId = $this->growthBidRecord->insert($fieldData);
                    
                    if($recordId) {
                        //增加人数
                        $this->growthBid->addJoinNumber($bidId);
                        //冻结积分
                        $this->growthBrokerCredit->frozenCredit($score,null,'','学区专家竞投中投入【'.$school['schoolname'].'】');
                        //退分
                        $this->complete($bid);
                        //统计有多少人在使用
                        $growthBidUserBroker = new GrowthBidUserBroker();
                        $growthBidUserBroker->addJoinBidSchoolExpertRecord($brokerId);
                        
                        //同时关注
                        if(!$this->hasAttention($bidId)) {//如果没关注
                            $attentionNumber = GrowthBidAttentionHelper::totalNumber($this->broker);
                            if($attentionNumber<GrowthBidAttentionHelper::ATTENTION_MAX_NUMBER) {
                                $this->attent($bidId,$bidPeriodsId);
                            }
                        }
                        
                    } else {
                        $this->bidError['errorCode'] = self::BID_ERROR_SYS_DB;
                        //记录错误日志
                    }
                    break;
                case '0'://已投过，未投中
                    $fieldData = array('score'=>$score,'status'=>'1');
                    $conf = "broker_id='$brokerId' and bid_id='$bidId'";
                    $affectRows = $this->growthBidRecord->update($fieldData, $conf);
                    if($affectRows) {
                        //$this->growthBrokerCredit->frozenCredit($score);
                        $this->growthBrokerCredit->frozenCredit($score,null,'','学区专家竞投中投入【'.$school['schoolname'].'】');
                        //处理其他被超过积分，挤出排名的经纪人，bid=$bid，and 积分《score and status = 1
                        //积分记录 解冻积分，frozen= frozen-score；若关注，则通知
                        $this->complete($bid);
                    } else {
                        
                    }
                    
                    break;
                case '1'://追加
                case '2':
                case '3':
                case '4':
                    $fieldData = array('score'=>$score);
                    $conf = "broker_id='$brokerId' and bid_id='$bidId'";
                    $affectRows = $this->growthBidRecord->add($fieldData, $conf);
                    if($affectRows) {
                        //$this->growthBrokerCredit->frozenCredit($score);
                        $this->growthBrokerCredit->frozenCredit($score,null,'','学区专家竞投中追加【'.$school['schoolname'].'】');
                    } else {
                        
                    }
                    break;
                default:
                    break;
            }
            //如果存在就更新，不存在就插入(本竞投中是首次投分，还是后续加分)X
            
            
            //后续加分--》更新记录，status=1；冻结积分score；X
            
            //积分记录？
            return true;
        } else {
            return false;
        }
    }
    
    public function complete($bid) {
        //处理其他被超过积分，挤出排名的经纪人，bid=$bid，and 积分《score and status = 1
        //积分记录 解冻积分，frozen= frozen-score；若关注，则通知
        $refundRecord = $this->findRecordForRefund($bid);
        if($refundRecord) {
            //把这些标记为失败
            $ids = array();
            $refundBroker = array();
            foreach ($refundRecord as $value) {
                $ids[] = $value['id'];
                $temp = array();
                $temp['broker_id'] = $value['broker_id'];
                $temp['score'] = "-".$value['score'];
                $temp['school_name'] = $value['school_name'];
                $refundBroker[] = $temp;
            }
            //status标记为失败
            $this->growthBidRecord->update(array('status'=>0), "id in ('".  implode("','", $ids)."')");
            //解冻积分
            if($refundBroker) {
                //$growthCredit = $this->growthBrokerCredit->getGrowthCredit();
                foreach ($refundBroker as $value) {
                    $this->growthBrokerCredit->frozenCredit($value['score'],$value['broker_id'],'','学区专家竞投失败返还【'.$value['school_name'].'】');
                    //$growthCredit->unfreeze($value['broker_id'],$value['score']);
                }
            }
            
        }
        
    }

    public function getBidError() {
        return $this->bidError;
    }

    /**
     * 检查是否可以竞投，检查3项
     * @param int $bidId
     * @return boolean
     */
    public function check($bid,$score) {
        return false;
        if($this->checkBroker()&&$this->checkCredit($score)) {
            //$bid = $this->growthBid->findByBidId($bidId);
            if($bid) {
                //检查投入的分是否大于本次竞投当前要求的最低分
                $this->getNeedScore($bid,$winnerRecord,$myRecord);
                $schoolId = $bid['broker_id'];
                $bidBrokerLevel = $bid['broker_level'];//可以竞投的等级
                return $this->checkHouseNumber($schoolId)&&$this->checkBrokerLevel($bidBrokerLevel);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    
    /**
     * 根据提供的竞投和竞投记录判断是否可以竞投
     * @param array $bid
     * @param int $score
     * @param array $winnerRecord
     * @param array $myRecord
     * @return boolean
     */
    public function checkByRecord($bid,$score,$winnerRecord,$myRecord) {
        //检查时间
        //查$bid所在的期次
        $bidPeriodsId = $bid['bid_periods_id'];
        $bidPeriods = $this->growthBidPeriods->findById($bidPeriodsId);
        if(!GrowthBidPeriods::isBidOn($bidPeriods)) {
            //竞投结束了
            $this->bidError['errorCode']= self::BID_ERROR_FINISH;
            return false;
        }
        if($this->checkBroker()&&$this->checkCredit($score)) {
            //$bid = $this->growthBid->findByBidId($bidId);
            if($bid) {
                //检查投入的分是否大于本次竞投当前要求的最低分
                $needScore = $this->getNeedScore($bid,$winnerRecord,$myRecord);
                
                if($this->checkScore($score, $needScore)) {
                    $schoolId = $bid['school_id'];
                    $bidBrokerLevel = $bid['broker_level'];//可以竞投的等级
                    return $this->checkHouseNumber($schoolId)&&$this->checkBrokerLevel($bidBrokerLevel);
                } else {
                    return false;
                }
                
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 检查投入的积分是否大于所需的最小积分
     * @param int $score
     * @param array $needScore 是$this->getNeedScore($bid,$winnerRecord,$myRecord)返回值
     */
    public function checkScore($score,$needScore) {
        $type = $needScore['type'];
        $flag = $score>=$needScore['score'];
        if(!$flag) {
            $this->bidError['errorCode']= self::BID_ERROR_AUTH_SCORE;
            return false;
        }
        return true;
    }


    /**
     * 检查积分够不够
     * @param int $score
     * @return boolean
     */
    public function checkCredit($score) {
        $myCredit = $this->broker['credit'];
        if($myCredit<$score) {
            $this->bidError['errorCode']= self::BID_ERROR_AUTH_CREDIT;
            return false;
        }
        return true;
    }

    /**
     * 检查经纪人是否是付费经纪人，
     * 
     */
    public function checkBroker() {
        if($this->broker['is_pay']==0){
            return true;
        } else {
            $this->bidError['errorCode']= self::BID_ERROR_AUTH_IS_PAY;
            return false;
        }
    }
    //是否有该小区的4条或以上房源,
    public function checkHouseNumber($schoolId) {
        $brokerid = $this->broker['id'];
        $sql = "SELECT count(school_block.school_id) FROM school_block LEFT JOIN sell on school_block.block_id = sell.blockid where sell.uid = '$brokerid' AND school_block.school_id='$schoolId' AND  sell.esta=1 AND sell.infofrom=5";
       // $sql = "SELECT count(blockid) FROM `sell` WHERE uid = '$brokerid' and blockid='$blockId' and  esta=1 and infofrom=5";
        $houseNumber = $this->dbback->getOne($sql);
        if($houseNumber>=self::HOUSE_NUMBER_LIMIT) {
            return true;
        } else {
            $this->bidError['errorCode']= self::BID_ERROR_AUTH_HOUSE;
            return false;
        }
    }
    //经纪人等级是否满足小区等级
    public function checkBrokerLevel($bidBrokerLevel) {
        $brokerLevel = $this->broker['level'];//经纪人等级
        $arr = explode(",", $bidBrokerLevel);
        if(in_array($brokerLevel, $arr)) {
            return true;
        } else {
            $this->bidError['errorCode']= self::BID_ERROR_AUTH_LEVEL;
            return false;
        }
    }

    /**
     * 查找经纪人全部可用的学区专家竞投
     */
    public function findAllBid($houseNumber) {
        $schoolids = $this->findAllSchoolHouserNumber($houseNumber);
        $brokerLevel = $this->broker['level'];
        //$bLevelHeat = new BlockLevelHeat();
        $conf = "school_id in ('".implode("','", $schoolids)."') and broker_level like '%LV".$brokerLevel."%'";
        $bids = $this->growthBid->findBy($conf);
        //$blockLevel = $bLevelHeat->findBy("block_id,level", "block_id in ('".implode("','", $blockids)."')", 0);
        //print_r($bids);
        return $bids;
    }
    
    /**
     * 查找经纪人的房源大于等于$houseNumber这个房源数量的学区
     * @param int $houseNumber 房源数量
     * @return array 小区id数组
     */
    public function findAllSchoolHouserNumber($houseNumber=0) {
        $brokerid = $this->broker['id'];
        $sql = "SELECT school_block.school_id,count(school_block.school_id)  FROM school_block LEFT JOIN sell ON school_block.block_id = sell.blockid  WHERE sell.uid='$brokerid' AND sell.esta=1 AND sell.isstar=3 AND sell.infofrom=5 GROUP BY school_block.school_id";
        $this->brokerSchool = $this->dbback->getAssoc($sql);
        $temp= array();
        if($this->brokerSchool) {
            foreach ($this->brokerSchool as $key=>$value) {
                if($value>=$houseNumber) {
                    $temp[] = $key;
                }
            }
        }
        return $temp;
        //return $this->brokerSchool;
    }
    
    public function findAllBlock($blockids) {
        ///
    }
    
    public function hasAttention($bidId) {
        //检查是否关注过
        $growthAttention = new GrowthBidAttention();
        $brokerId = $this->broker['id'];
        $conf = "broker_id='$brokerId' and type=4 and target_id='$bidId'";
        $number = $growthAttention->findNumberBy($conf);
        if($number==1) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 检查是否可以关注
     * @param int $bidid 竞投id
     */
    public function checkAttention($bidId) {
        if($this->hasAttention($bidId)) {
            return false;
        }
        if($this->checkBroker()) {
            $bid = $this->growthBid->findById($bidId);
            if($bid) {
                $schoolId = $bid['school_id'];
                $bidBrokerLevel = $bid['broker_level'];//可以竞投的等级
                return $this->checkHouseNumber($schoolId)&&$this->checkBrokerLevel($bidBrokerLevel);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    
    public function findAttention($bidPeriodsId) {
        $brokerId = $this->broker['id'];
        $growthAttention = new GrowthBidAttention();
        return $growthAttention->findBy("broker_id='$brokerId' and bid_periods_id='$bidPeriodsId' and type=4");
    }
    
    public function attent($bidId,$cBidPeriods) {
        $fieldData = array();
        $fieldData['broker_id'] = $this->broker['id'];
        $fieldData['type'] = 4;
        $fieldData['target_id'] = $bidId;
        $fieldData['bid_periods_id'] = $cBidPeriods;
        $growthAttention = new GrowthBidAttention();
        return $growthAttention->insert($fieldData);
        
    }
    
    public function cancelAttent($attentionId) {
        $growthAttention = new GrowthBidAttention();
        $brokerId = $this->broker['id'];
        $conf = "id='$attentionId' and broker_id='$brokerId'";
        return $growthAttention->delBy($conf);;
    }
    
    /**
     * 根据期次id查找本期参与的竞投记录
     * @param int $bidPeriodsId
     * @return array 竞投记录数组
     */
    public function findBidRecord($bidPeriodsId=0) {
        $brokerId = $this->broker['id'];
        if($bidPeriodsId) {
            $conf = "broker_id='$brokerId' and bid_periods_id='$bidPeriodsId'";
            return $this->growthBidRecord->findBy($conf);
        } else {
            return $this->growthBidRecord->findByBrokerId($brokerId);
        }
    }
    
    /**
     * 查找经纪人的竞投历史记录
     * @param int $bidPeriodsId
     * @param string $order
     * @param string $limit
     * @return array
     */
    public function findBidHistoryRecord($bidPeriodsId=0,$schoolName='',$order='',$limit='') {
        $brokerId = $this->broker['id'];
        $conf = "broker_id='$brokerId'";
        if($bidPeriodsId) {
            $conf .= " and bid_periods_id='$bidPeriodsId'";
        } 
        if($schoolName) {
            $conf .= " and school_name like '%$schoolName%' ";
        }
        return $this->growthBidRecordHistory->findBy($conf,$order,$limit);
    }

    public function findBidHistoryRecordNumber($bidPeriodsId=0,$schoolName='') {
        $brokerId = $this->broker['id'];
        $conf = "broker_id='$brokerId'";
        if($bidPeriodsId) {
            $conf .= " and bid_periods_id='$bidPeriodsId'";
        } 
        if($schoolName) {
            $conf .=" and school_name like '%$schoolName%'";
        }
        return $this->growthBidRecordHistory->findNumberBy($conf);
    }

    /**
     * 查找参与过的学区
     * @return array 小区数组
     */
    public function findSchoolBid() {
        $bidRecords = $this->findBidRecord();
        $schools = array();
        if($bidRecords) {
        foreach($bidRecords as $b) {
            $schools[$b['school_id']] = $b['school_name'];
        }
        }
        return $schools;
    }
    
    /**
     * 检查投中了没有以及第几位
     * @param array $winnerRecord
     * @param array $myRecord
     * @return int 名次，0，表示未投中，1，2，3，4表示第几位 -1,表示没有投过
     */
    public function checkWinBid($winnerRecord,$myRecord) {
        $number = 0;
        if($myRecord&&$winnerRecord) {
            $myRecordId = $myRecord['id'];
            $i = 0;
            foreach ($winnerRecord as $value) {
                $i++;
                if($value['id']==$myRecordId) {
                    $number = $i;
                    break;
                }
            }
        } else {
            $number = '-1';
        }
        return $number;
    }
    
    /**
     * 查找最终赢得竞投的记录，根据status判断
     * @param type $bidId
     */
    public function findWinner($bidId) {
        
    }

    /**
     * 查找暂时赢得竞投的人的竞投记录
     * @param int $bid 竞投数组
     * @return array 中投的记录数组
     */
    public function findTempWinnerRecord($bid) {
        $bidId = $bid['id'];
        $maxWinNumber = $bid['max_win_number']?$bid['max_win_number']:4;
        return $this->growthBidRecord->findByBid($bidId, "score desc, utime asc", "0,$maxWinNumber");
    }
    
     /**
     * 查找赢得竞投的人的竞投记录
     * @param int $bidId 竞投id
     * @return array 中投的记录数组
     */
    public function findWinnerRecord($bid) {
        $bidId = $bid['id'];
        $maxWinNumber = $bid['max_win_number']?$bid['max_win_number']:4;
        return $this->growthBidRecordHistory->findBy("bid_id='$bidId' and status=1", "score desc, utime asc", "0,$maxWinNumber");
    }
    /**
     * 
     * @param int $bid
     * @return array
     */
    public function findRecordForRefund($bid) {
        $bidId = $bid['id'];
        $maxWinNumber = $bid['max_win_number']?$bid['max_win_number']:4;
        $res = $this->growthBidRecord->findBy("bid_id='$bidId' and status=1", "score desc, utime asc", "$maxWinNumber,10");
        if($res) {
            return $res;
        } else {
            return array();
        }
    }
    
    public function isWinBid($bidId) {
        
    }
    
    /**
     * 返回竞投需要投入的最低积分
     * @return array $result = array('type'=>'','score'=>'');type表示是否起拍，0，起拍分,1,第四名的分，2,追加分
     */
    public function getNeedScore($bid,$winnerRecord,$myRecord) {		
        //检查我投中没有
        $score = 0;
        $result = array('type'=>'','score'=>'');
        if($this->checkWinBid($winnerRecord, $myRecord)>0) {//投中了
                $result['type'] = self::BID_NEED_SCORE_TYPE_WIN;
                $result['score'] = $this->additionalScore;
        } else {//未投中
            $maxWinNumber = $bid['max_win_number']?$bid['max_win_number']:4;
            if(count($winnerRecord)==$maxWinNumber) {
                $result['type'] = self::BID_NEED_SCORE_TYPE_NOT_WIN_1;
                $result['score'] = $winnerRecord[$maxWinNumber-1]['score']+1;//$this->additionalScore;
            } else {
                $result['type'] = self::BID_NEED_SCORE_TYPE_NOT_WIN_0;
                $result['score'] = $bid['min_score'];
            }
        }
        return $result;
    }
    
    /**
     * 最后一次投入的分数
     * @param array $bid
     */
    public function lastBidScore($myRecord) {
        if($myRecord) {
            return  $myRecord['score'];
        } else {
            return 0;
        }
        
    }
    
    /**
     * 返回竞投面板上的提示，积分够不够的提示
     * @param int $myCredit 我的积分
     * @param array $needScore 本竞投需要的积分 ，通过 getNeedScore($bid,$winnerRecord,$myRecord)返回
     * @return string 提示字符串
     */
    public function tipOnPanel($myCredit,$needScore) {
        //$needScore = $this->getNeedScore($bid,$winnerRecord,$myRecord);
        $tip = "";
        if($needScore) {
            $type = $needScore['type'];
            $minScore = $needScore['score'];
            if($this->mode='dou') {
                $t = "您".$this->modeString()."不够哦 ";
            } else {
                $t = "您".$this->modeString()."不够哦 ".'<a target="_blank" href="./my_growth.php">先去赚'.$this->modeString().'&gt;&gt;</a>';
            }
            if($type == 0) {
                $tip = $myCredit<$minScore?$t:"";
            }
            if($type == 1) {
                $tip = $myCredit<$minScore?$t:"";
            }
            if($type == 2) {
                $tip = $myCredit<1?$t:"";
            }
        }
        return $tip;
    }
    
    /**
     * 竞投成功失败的提示
     * @param array $myRecord
     * @param int $winFlag
     * @return string
     */
    public function tip1OnPanel($myRecord,$winFlag,$maxWinNumber=4) {
        $myScore = $this->lastBidScore($myRecord);
        if($winFlag=='-1') {
            $tip2 = "";
        } elseif($winFlag==0) {
            $tip2 = "我已投入".$myScore."".$this->modeString().",由于未抢过前".$maxWinNumber."名，已退还。";
        } else {
            $tip2 = "我已投入".$myScore.$this->modeString();
        }
        return $tip2;
    }
    
    /**
     * 竞投面板上输入框等
     * @param array $needScore
     * @return array
     */
    public function scoreInputDefault($needScore,$myScore) {
        $default = array('span'=>'','value'=>'','totalTip'=>'');
        if($needScore) {
            $type = $needScore['type'];
            $minScore = $needScore['score'];
            if($type == 0) {
                $default['value'] = "起拍".$minScore;
                $default['span'] = "我要投入";
                $default['totalTip'] = '';
            }
            if($type == 1) {
                $default['value'] = "至少".$minScore;
                $default['span'] = "我要投入";
                $default['totalTip'] = "";
            }
            if($type == 2) {
                $default['value'] = "至少".$minScore;
                $default['span'] = "我要追加";
                $default['totalTip'] = '投入'.$this->modeString().':<span class="calScore" value="'.$myScore.'" style="width: 21px; color: red;">'.$myScore.'</span>'.$this->modeString(2);
            }
        }
        return $default;
    }
    
    /**
     * 生成计时圆环
     * @param string $startTime 投票开始时间
     * @param string $endTime 投票结束时间
     */
    public function TimeRing($startTime,$endTime) {
        $time = time();
        $stime= strtotime($startTime);
        $etime= strtotime($endTime);
        $hours = ($etime-$stime)/3600;
        $ev = $hours/4;
        if($time>=$stime&&$time<$stime+3600*$ev) {
            return 1;
        } elseif($time>=$stime+3600*$ev&&$time<$stime+3600*$ev*2) {
            return 2;
        } elseif($time>=$stime+3600*$ev*2&&$time<$stime+3600*$ev*4) {
            return 3;
        } else {
            return 4;
        }
    }
    
    /**
     * 竞投列表
     */
    public function get_bid_school_expert_list($schools,$cBidPeriods,$myrecords) {     
        $myCredit = $this->broker['credit'];
            $list = array();
            if($schools) {//有满足条件的小区
                //print_r($cBidPeriods);
                    $schoolsNew = SqlCombinHelper::changeToKeyArray($schools, 'id');
                    $schoolids = array_keys($schoolsNew);
                    $bidPeriodsStatus = $cBidPeriods['status'];
                    $cBidPeriodsId = $cBidPeriods['id'];
                    $cBidPeriodsTgStartTime = $cBidPeriods['tg_start_time'];//本期推广时间
                    $cBidPeriodsTgEndTime = $cBidPeriods['tg_end_time'];
                    $cBidPeriodsStartTime = $cBidPeriods['start_time'];//竞投开始时间
                    $cBidPeriodsendTime = $cBidPeriods['end_time'];//竞投结束时间
                    //学区竞投
                    $growthBidSchoolExpert = new GrowthBidSchoolExpert();
                    $schoolExpertBids = $growthBidSchoolExpert->findBy("school_id in ('".implode("','", $schoolids)."') and bid_periods_id='$cBidPeriodsId'",array("school_level"=>"asc"));
                    $schoolExpertBidsNew = SqlCombinHelper::changeToKeyArray($schoolExpertBids, 'school_id');
                    //关注记录
                    $attentionList = $this->findAttention($cBidPeriodsId);
                    //预处理
                    $attentionListNew = SqlCombinHelper::changeToKeyArray($attentionList, 'target_id');
                    //print_r($attentionListNew);
                    if($bidPeriodsStatus==1) {
                        //本期竞投中
                        //查找对应的竞投id
                        foreach($schoolExpertBidsNew as $key=>$bid) {
                            $temp = array();
                            $tempBid = $bid;
                            $temp['bid'] = $tempBid;
                            $b = $schoolsNew[$tempBid['school_id']];
                            $schoolId = $b['id'];
                            $temp['school_id'] = $schoolId;
                            $temp['school_name'] = $b['schoolname'];
                            $temp['school_image'] = $b['coverphoto']?$b['coverphoto']:'<?=STATIC_SOURCE_URL?>/zsb/images/v1.0/nopic1.gif';
                            $temp['school_heat_level'] = $tempBid['school_level'];//小区热度等级
                            //竞投信息
                            $temp['bid_id'] = $tempBid['id'];
                            $temp['bid_status'] = $bidPeriodsStatus;
                            $temp['bid_status_str'] = '竞投中';
                            $temp['tg_start_time'] = $cBidPeriodsTgStartTime;//推广时间
                            $temp['tg_end_time'] = $cBidPeriodsTgEndTime;//推广时间
                            $temp['time'] = $cBidPeriodsendTime;//竞投结束时间
                            $temp['timeRing'] = $this->TimeRing($cBidPeriodsStartTime, $cBidPeriodsendTime);
                            $temp['number'] = $tempBid['number'];//参加人数
                            //投入积分前4位
                            $temp['record'] = $this->findTempWinnerRecord($tempBid);
                            //print_r($tempBid);
                            //print_r($tempRecord);exit;
                            //关注状态
                            if(array_key_exists($tempBid['id'], $attentionListNew)) {
                                $temp['attention_id'] = $attentionListNew[$tempBid['id']];
                            } else {
                                $temp['attention_id'] = array();
                            }
                            //竞拍记录
                            //echo $tempBid['id'].'x';
                            if(array_key_exists($tempBid['id'], $myrecords)) {
                                $temp['my_record'] = $myrecords[$tempBid['id']];//我的记录
                            } else {
                                $temp['my_record'] = array();//我的记录
                            }
                            $temp['my_credit'] = $myCredit;//我的可用积分
                            //往期统计数据
                            $allBidStat = $this->allPrevBidStat();
                            $temp['all_prev_stat'] = array_key_exists($schoolId, $allBidStat)?$allBidStat[$schoolId]:array();
                            //最低起拍积分
                            //计算，没投过
                            //上次投的积分
                            $temp['my_score'] = $this->lastBidScore($temp['my_record']);
                            //所需最低积分，是个数组
                            $temp['min_score'] = $this->getNeedScore($tempBid, $temp['record'], $temp['my_record']);
                            //提示
                            $temp['tip'] = $this->tipOnPanel($temp['my_credit'], $temp['min_score']);
                            //是否投中标记
                            $winFlag = $this->checkWinBid($temp['record'], $temp['my_record']);
                            $temp['winFlag'] = $winFlag;
                            //提示1
                            $temp['tip1'] = $this->tip1OnPanel($temp['my_record'], $winFlag,$tempBid['max_win_number']); 
                            //积分输入框默认内容
                            $temp['score_input_default'] = $this->scoreInputDefault($temp['min_score'],$temp['my_score']);
							$temp['type']=4;
                            $list[] = $temp;
                        }  
                    }

                    if($bidPeriodsStatus==2) {//新竞投还没开始
                        foreach($schools as $b) {
                            $temp = array();
                            $schoolId = $b['id'];
                            $tempBid = $schoolExpertBidsNew[$schoolId];
                            $temp['bid'] = $tempBid;
                            $temp['school_id'] = $schoolId;
                            $temp['school_name'] = $b['schoolname'];
                            $temp['school_image'] = $b['coverphoto']?$b['coverphoto']:'./images/no_img_small.gif';
                            $temp['school_heat_level'] = $tempBid['school_level'];//小区热度等级
                            //竞投信息
                            $temp['bid_id'] = $tempBid['id'];
                            $temp['bid_status'] = $bidPeriodsStatus;
                            $temp['bid_status_str'] = '上期竞投结束';//'上期竞投结束';
                            $temp['tg_start_time'] = $cBidPeriodsTgStartTime;//推广时间
                            $temp['tg_end_time'] = $cBidPeriodsTgEndTime;//推广时间
                            $temp['start_time'] = $cBidPeriodsStartTime;//竞投开始时间
                            $temp['time'] = $cBidPeriodsendTime;//竞投结束时间
                            $temp['timeRing'] = $this->TimeRing($cBidPeriodsStartTime, $cBidPeriodsendTime);
                            $temp['number'] = $tempBid['number'];//参加人数
                            $temp['my_credit'] = $myCredit;//我的可用积分
                            $temp['min_score'] = $this->getNeedScore($tempBid, array(), array());
                            $temp['score_input_default'] = $this->scoreInputDefault($temp['min_score'],0);
                            //上期，本小区竞投历史
                            //$prevRecord =$this->growthBidRecordHistory->findBy("block_id='$blockId' and status=1", "score desc, utime asc", "0,4");
                            //$template = '<div style="float: left; width: 120px;margin-bottom: 2px;"><span class="m_l_33 blod">NO.%s：</span><span style="border-right-width: 0px; margin-right: 5px;" class="rank %s">%s</span>分</div>';
                            //$temp['record_list'] = $this->rankList($prevRecord,  GrowthBidPeriods::BID_PERIODS_STATUS_FINISH,$template,null);
                            //print_r($tempBid);
                            //print_r($tempRecord);exit;
                            //往期统计数据
                            $allBidStat = $this->allPrevBidStat();
                            $temp['all_prev_stat'] = array_key_exists($schoolId, $allBidStat)?$allBidStat[$schoolId]:array();
                            //关注状态
                            /**
                            if($attentionListNew[$tempBid['id']]) {
                                //$temp['attention_id'] = $attentionListNew[$tempBid['id']];
                            }**/
                            $list[] = $temp;
                        }  
                    }
                    
                    if($bidPeriodsStatus==3) {
                        foreach($schoolExpertBidsNew as $key=>$bid) {
                            $temp = array();
                            $tempBid = $bid;
                            $temp['bid'] = $tempBid;
                            $b = $schoolsNew[$tempBid['school_id']];
                            $schoolId = $b['id'];
                            $temp['school_id'] = $schoolId;
                            $temp['school_name'] = $b['schoolname'];
                            $temp['school_image'] = $b['coverphoto']?$b['coverphoto']:'./images/no_img_small.gif';
                            $temp['school_heat_level'] = $tempBid['school_level'];//小区热度等级
                            //竞投信息
                            $temp['bid_id'] = $tempBid['id'];
                            $temp['bid_status'] = $bidPeriodsStatus;
                            $temp['bid_status_str'] = '竞投结束';
                            $temp['tg_start_time'] = $cBidPeriodsTgStartTime;//推广时间
                            $temp['tg_end_time'] = $cBidPeriodsTgEndTime;//推广时间
                            $temp['time'] = $cBidPeriodsendTime;//竞投结束时间
                            $temp['timeRing'] = $this->TimeRing($cBidPeriodsStartTime, $cBidPeriodsendTime);
                            $temp['number'] = $tempBid['number'];//参加人数
                            //投入积分前4位
                            $temp['record'] = $this->findTempWinnerRecord($tempBid);
                            //print_r($tempBid);
                            //print_r($tempRecord);exit;
                            //往期统计数据
                            $allBidStat = $this->allPrevBidStat();
                            if(array_key_exists($schoolId, $allBidStat)) {
                                $temp['all_prev_stat'] = $allBidStat[$schoolId];
                            } else {
                                $temp['all_prev_stat'] = array();
                            }
                            
                            //关注状态
                            if(array_key_exists($tempBid['id'], $attentionListNew)) {
                                $temp['attention_id'] = $attentionListNew[$tempBid['id']];
                            }
                            //竞拍记录
                            //echo $tempBid['id'].'x';
                            if(array_key_exists($tempBid['id'], $myrecords)){
                                $temp['my_record'] = $myrecords[$tempBid['id']];//我的记录
                            } else {
                                $temp['my_record'] = array();
                            }
                            $temp['my_credit'] = $myCredit;//我的可用积分
                            //最低起拍积分
                            //计算，没投过
                            //上次投的积分
                            $temp['my_score'] = $this->lastBidScore($temp['my_record']);
                            //所需最低积分，是个数组
                            $temp['min_score'] = $this->getNeedScore($tempBid, $temp['record'], $temp['my_record']);
                            //提示
                            $temp['tip'] = $this->tipOnPanel($temp['my_credit'], $temp['min_score']);
                            //是否投中标记
                            $winFlag = $this->checkWinBid($temp['record'], $temp['my_record']);
                            $temp['winFlag'] = $winFlag;
                            //提示1
                            $temp['tip1'] = $this->tip1OnPanel($temp['my_record'], $winFlag,$tempBid['max_win_number']); 
                            //积分输入框默认内容
                            $temp['score_input_default'] = $this->scoreInputDefault($temp['min_score'],$temp['my_score']);
                            $list[] = $temp;
                        }  
                    }
            }
            //print_r($list);exit;
            return $list;
        }

    public function getAttentionList($cBidPeriods) {
        $bidPeriodsId = $cBidPeriods['id'];
        $attentionList = $this->findAttention($bidPeriodsId);
        //print_r($attentionList);
        if(!$attentionList) {//没有关注返回空数组
            return array();
        }

        $bidIds = array();
        foreach ($attentionList as $value) {
            $bidIds[] = $value["target_id"];
        }
        //查竞投
        $conf = "id in ('".  implode("','", $bidIds)."')";
        $bids = $this->growthBid->findBy($conf);
        $bids = SqlCombinHelper::changeToKeyArray($bids, "school_id");
	
      
        $schoolIds = array_keys($bids);
        $schoolMg = new School();
        $schools = $schoolMg->findAllBy("id in ('".implode("','", $schoolIds)."')");
        //print_r($blocks);
        //查我的记录
        $myrecords = $this->findBidRecord($bidPeriodsId);
        $myrecords = SqlCombinHelper::changeToKeyArray($myrecords, 'bid_id');

        $attentionBidList = array();

        $attentionList = $this->get_bid_school_expert_list($schools, $cBidPeriods, $myrecords);
      
		
       // print_r($attentionList);
        return $attentionList;
    }

    /**
     * 返回排名列表
     * @param array $records 排名记录
     * @param string $tType  竞投状态GrowthBidPeriods::BID_PERIODS_STATUS_ON;
                                     GrowthBidPeriods::BID_PERIODS_STATUS_NOT_START;
                                     GrowthBidPeriods::BID_PERIODS_STATUS_FINISH//字符串on，或者history,默认on
     * @param type $template
     * @param type $myrecord
     * @return type
     */
    public function rankList($records, $tType = GrowthBidPeriods::BID_PERIODS_STATUS_ON, $template=null, $myrecord = null,$maxWinNumer=4) {
        if(!$records) {$records = array();}
        $records = array_pad($records, $maxWinNumer, array());
        $html = "";
        foreach($records as $k=>$r) {
            //$funcName = "renderRank".ucfirst($tType);
            if($tType==GrowthBidPeriods::BID_PERIODS_STATUS_ON) {
                $html .= $this->renderRankHasScore($k,$r,$myrecord,$template);
            } else {
                $html .= $this->renderRankNoScore($k,$r,$myrecord,$template);
            }
        } 
        return $html;
    }

    /**
     * 竞投中的排名显示
     * @param type $k
     * @param type $r
     * @param type $myrecord
     * @param type $template
     * @return string
     */
    private function renderRankHasScore($k,$r,$myrecord=null,$template=null) {
        $no = $k+1;
        $rank02 = 'rank02';
        if(!empty($r)) {
            if($myrecord&&$myrecord['id']==$r['id']) {//判断是不是自己
                $rank02 = '';
                $score = '<strong class="num">'.$r['score'].'</strong>'.$this->modeString(2);
            } else {
                $score = '<strong class="num">已被抢占</strong>';
            }
        } else {
                $score = '<strong class="num">缺席中</strong>';
        }

        if($template) {
            $html = sprintf($template,$no,$rank02,$score);
        } else {
            $html = '<div class="fraction_rank radius3" style="margin: 5px;"><span class="rank '.$rank02.'">NO.'.$no.'</span><span class="fraction">'.$score.'</span></div>';
        }
        return $html;
    }
    /**
     * 竞投结束排名显示风格
     * @param type $k
     * @param type $r
     * @param type $myrecord
     * @param type $template
     * @return string
     */
    private function renderRankNoScore($k,$r,$myrecord=null,$template=null) {
        $no = $k+1;
        //$rank02 = $no>2?'rank02':'';
        $score = $r&&$r['score']?$r['score']:'— —';
        $rank02 = 'rank02';
        if($myrecord) {//判断是不是自己
                //echo 'xxx';
                //echo "#".$r['id']."--#".$myrecord['id'];
            if($r&&$r['id']==$myrecord['id']) {
                $rank02 = '';
            }
        }
        if($template) {
            $html = sprintf($template,$no,$rank02,$score);
        } else {
            $html = '<div class="fraction_rank radius3"  style="margin: 5px;"><span class="rank '.$rank02.'">NO.'.$no.'</span><span class="fraction"><strong class="num">'.$score.'</strong>'.$this->modeString(2).'</span></div>';
        }
        return $html;
    }
    /**
     * 检查查看权限
     * @param int $bid
     */
    public function checkViewAuth($cBidPeriodsId,$bid) {
        $schoolId = $bid['school_id'];
        $schools = $this->get_valid_bid_school($cBidPeriodsId,array(), '');
        $schools = SqlCombinHelper::changeToKeyArray($schools, "id");
        if(in_array($schoolId, array_keys($schools))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 返回所有可以参与竞投的学区id数组
     * @param type $cBidPeriodsId
     */
    public function get_valid_bid_school_id($cBidPeriodsId) {
        $schoolids = $this->findAllSchoolHouserNumber(GrowthBrokerBidSchoolExpert::HOUSE_NUMBER_LIMIT);
        //过滤，有竞投活动，且经纪人等级满足
        //学区竞投
        $growthBidSchoolExpert = new GrowthBidSchoolExpert();
        $schoolExpertBids = $growthBidSchoolExpert->findBy("school_id in ('".implode("','", $schoolids)."') and bid_periods_id='$cBidPeriodsId'");
        $schoolExpertBidsNew = SqlCombinHelper::changeToKeyArray($schoolExpertBids, 'school_id');
        $this->schoolExpertBidsNew = $schoolExpertBidsNew;
        $schoolids = array();
        //print_r($blockExpertBidsNew);
        foreach ($schoolExpertBidsNew as $value) {
            if($this->checkBrokerLevel($value['broker_level'])) {
                $schoolids[] = $value['school_id'];
            }
        }
        return $schoolids;
    }
    /**
     * 可以的小区专家竞投小区
     * @param type $growthBrokerBidBlockExpert
     * @param array $myrecords 我的竞投记录
     * @param string $action 参与的还是所有的标记
     * @return array 小区数组
     */
    public function get_valid_bid_school ($cBidPeriodsId,$myrecords,$action,$schoolName='') {
        //找出经纪人符合要求的房源小区
        $schoolids = $this->findAllSchoolHouserNumber(GrowthBrokerBidSchoolExpert::HOUSE_NUMBER_LIMIT);
        //过滤，有竞投活动，且经纪人等级满足
        //小区竞投
        $growthBidSchoolExpert = new GrowthBidSchoolExpert();
        $schoolExpertBids = $growthBidSchoolExpert->findBy("school_id in ('".implode("','", $schoolids)."') and bid_periods_id='$cBidPeriodsId'");
        $schoolExpertBidsNew = SqlCombinHelper::changeToKeyArray($schoolExpertBids, 'school_id');
        $this->schoolExpertBidsNew = $schoolExpertBidsNew;
        $schoolids = array();
        //print_r($blockExpertBidsNew);
        foreach ($schoolExpertBidsNew as $value) {
            if($this->checkBrokerLevel($value['broker_level'])) {
                $schoolids[] = $value['school_id'];
            }
        }
		
        $school = new School();
		
        if($schoolName) {
			//echo "id in ('".  implode("','", $schoolids)."') and schoolname like '%$schoolName%'";exit;
            $schools = $school->findAllBy("id in ('".  implode("','", $schoolids)."') and schoolname like '%$schoolName%'");

        } else {
            $schools = $school->findAllBy("id in ('".  implode("','", $schoolids)."')");
        }
        if(!$schools) {
            $schools = array();
        }
        if($action=='on') {
            $schoolOn = array();//$growthBrokerBidBlockExpert->findBlockBid();
            foreach($myrecords as $mr) {
                $schoolOn[$mr['school_id']] = $mr['school_name'];
            }
            $schoolIdsOn = array_keys($schoolOn);
            if($schools) {//过滤未参与的小区
                foreach($schools as $k=>$v) {
                    if(!in_array($v['id'],$schoolIdsOn)) {
                        unset($schools[$k]);
                    }
                }
            } 
        }
        $levels = array();//按小区等级排序
        foreach ($schools as $key=>$v) {
            $levels[$key] = $schoolExpertBidsNew[$v['id']]['school_level'];
            $schools[$key]['school_level'] = $levels[$key];
        }
        array_multisort($levels, SORT_ASC, $schools);
        //print_r($blocks);
        return $schools;
    }

    /**
     * 返回竞投历史列表
     * @param array $myrecords 我的竞投记录
     * @return array 历史列表数组
     */
    public function get_bid_school_expert_history_list($myrecords) {
        if(!$myrecords) {
            return array();
        }
        $mc = Container::getInstance()->get('mc');
        //查期次bid_periods
        $bidPeriodsIds = array();
        $bidIds = array();
        $historyList = array();
        foreach ($myrecords as $value) {
            $bidPeriodsIds[] = $value['bid_periods_id'];
            $bidIds[] = $value['bid_id'];
        }
        $bidPeriodsIds = array_unique($bidPeriodsIds);
        $growthBidPeriods = new GrowthBidPeriods();
        $bidPeriodsMKey = array( $bidPeriodsIds);
        $bidPs = $mc->get($bidPeriodsMKey);
        if($bidPs === false) {
            $bidPs = $growthBidPeriods->findBy("id in ('".  implode("','", $bidPeriodsIds)."')");
            $mc->set($bidPeriodsMKey,$bidPs,3600);
        }
        
        $bidPs = SqlCombinHelper::changeToKeyArray($bidPs, 'id');
        //查竞投bid
        $bids = $this->growthBid->findBy("id in ('".  implode("','", $bidIds)."')");
        $bids = SqlCombinHelper::changeToKeyArray($bids, 'id');
        //print_r($bids);exit;
        //获胜的记录
        foreach ($myrecords as &$value) {
            $temp = array();
            $temp['school_name'] = $value['school_name'];
            $bidP = $bidPs[$value['bid_periods_id']];
            $temp['tg_start_time'] = $bidP['tg_start_time'];
            $temp['tg_end_time'] = $bidP['tg_end_time'];
            $temp['number'] = $bids[$value['bid_id']]['number'];
            $maxWinNumber = $bids[$value['bid_id']]['max_win_number'];
            $temp['bid_status'] = "已结束";
            if($value['status'] == 1) {
                $temp['my_result'] = '<span class="s_color ">竞投成功</span>';
                $temp['my_result_tip'] = '';
            } else {
                $temp['my_result'] = '<span class="f_color ">竞投失败</span>';
                $temp['my_result_tip'] = ' 已退还';
            }
            $temp['my_score'] = $value['score'];
            $bidNum = $bids[$value['bid_id']]['max_win_number'];
            $recordsMKey = array($value['bid_id'], "score desc, utime asc", "0,$bidNum");
            $records = $mc->get($recordsMKey);
            if($records === false){
                $records = $this->growthBidRecordHistory->findByBid($value['bid_id'], "score desc, utime asc", "0,$bidNum");
                $mc->set($recordsMKey,$records,3600);
            }
            if($this->mode=='dou'){
                $template = '<div style="float: left; width: 130px;margin-bottom: 2px;"><span class="m_l_33 blod">NO.%s：</span><span style="border-right-width: 0px; margin-right: 5px;" class="rank %s">%s</span>'.$this->modeString(2).'</div>';
            } else {
                $template = '<div style="float: left; width: 120px;margin-bottom: 2px;"><span class="m_l_33 blod">NO.%s：</span><span style="border-right-width: 0px; margin-right: 5px;" class="rank %s">%s</span>'.$this->modeString(2).'</div>';
            }
            $temp['record_list'] = $this->rankList($records,  GrowthBidPeriods::BID_PERIODS_STATUS_FINISH,$template,$value,$maxWinNumber);
            $historyList[] = $temp;
        }
        //print_r($historyList);exit;
        return $historyList;
    }
    
    /**
     * 获取最新一期的竞投记录,营销中心首页上用
     * @return type
     */
    public function findNewBidRecord($cPeriods) {
        $brokerId = $this->getBrokerId();
		$cPeriodsStatus = $cPeriods['status'];
        if ($cPeriods['status'] == 1 || $cPeriods['status'] == 3) {
            $growthBidRecord = $this->growthBidRecord;
        } else {
            //向上推一个
            $growBidPeriods = new GrowthBidPeriods();
            $cPeriods = $growBidPeriods->upBidPeriods(1, $cPeriods['id']);
            $cPeriods['status'] = isset($cPeriods['status']) ?  $cPeriods['status'] : 0;
            $growthBidRecord = $this->growthBidRecordHistory;
        }
        if (!isset($cPeriods['id']) || $cPeriods['id'] == '') {
            return array();
        }
        $periodsId = $cPeriods['id'];
        $bidAllRecord = $growthBidRecord->findByPidAndBrokerId($periodsId, $brokerId, 10);
        if (!CommonBase::isFullArray($bidAllRecord)) {return array();}
        $arrBidRecord = array();
        foreach($bidAllRecord as $k => $v) {
            $bidId = $v['bid_id'];
            $bid = $this->growthBid->findById($bidId);
            $bidMaxMinScore = $growthBidRecord->findMaxMinScoreByBidSuccess($bidId);
 			if ($cPeriods['status'] == 1 || $cPeriods['status'] == 3) {
				$bidRecord = $this->findTempWinnerRecord($bid);
			} else {
				$bidRecord = $this->findWinnerRecord($bid);
			}
            $myRecord = $growthBidRecord->findOneBy($brokerId,$bidId);//$growthBidRecord->findBidRecordByBidAndHouseId($v['bid_id'], $v['house_id']);
            //print_r($myRecord);
            $bidRank = $this->checkWinBid($bidRecord, $myRecord);
            if ($cPeriods['status'] == 1) {
                if ($bidRank > 0) {
                    $intBehavior = self::$bidBehavior['tempHit'];
                    $arrBidRecord[$k]['rank'] = $bidRank;
                } else {
                    $intBehavior = self::$bidBehavior['noHit'];
                }
            } else {
                $intBehavior = $bidRank > 0 ? self::$bidBehavior['success'] 
                        : self::$bidBehavior['failure'];
            }
            if ($cPeriodsStatus == 2) {
                $bidRankUrl = 'market_bid_school_expert_history.php';
            } else {
                $bidRankUrl = 'market_bid_school_expert.php?tab=on';
            }
            $content = $v['school_name'];
            $tgStartTime = $cPeriods['tg_start_time'];
            $tgEndTime = $cPeriods['tg_end_time'];
            $arrBidRecord[$k]['projectname'] = self::$bidProjectName;
            $arrBidRecord[$k]['tg_start_time'] = date('m.d', strtotime($tgStartTime));
            $arrBidRecord[$k]['tg_end_time'] = date('m.d', strtotime($tgEndTime));
            $arrBidRecord[$k]['content'] = $content;
            $arrBidRecord[$k]['score'] = $v['score'];
            $arrBidRecord[$k]['utime'] = $v['utime'];
            $arrBidRecord[$k]['behavior'] = $intBehavior;
            $arrBidRecord[$k]['max_score'] = $cPeriods['status']==  GrowthBidPeriods::BID_PERIODS_STATUS_ON?'等你来抢':$bidMaxMinScore['max'];
            $arrBidRecord[$k]['min_score'] = $bidMaxMinScore['min'];
            $arrBidRecord[$k]['operate'] = $bidRankUrl;
            $arrBidRecord[$k]['esta'] = 1;
        }
        return $arrBidRecord;
    }
    
    public function getBrokerId() {
        return $this->broker['id'];
    }
    
        /**
     * 控制可以参与竞投的时间间隔
     */
    public function  controlTime() {
        if(isset($_SESSION['last_bid_time'])) {
            $lastTime = $_SESSION['last_bid_time'];
            if($lastTime>time()) {
                return false;
            } else {
                $_SESSION['last_bid_time'] = time()+GrowthBrokerBidSchoolExpert::BID_MIN_TIME;
                return true;
            }
        } else {
            $_SESSION['last_bid_time'] = time()+GrowthBrokerBidSchoolExpert::BID_MIN_TIME;
            return true;
        }
        
        
    }
    
    /**
     * 所有往期竞投数据统计，包括，总共有多少人添加，
     * 竞投成功的人投入的最高积分值和最低积分值
     * @return array 数组
     */
    public function allPrevBidStat() {
        $mc = Container::getInstance()->get('mc');
        $sql = "SELECT school_id,MAX(score) as max,MIN(score) as min FROM growth_bid_school_expert_record_history WHERE `status`=1 GROUP BY school_id";
        $sql1 = "SELECT school_id, count(id) as number FROM growth_bid_school_expert_record_history  GROUP BY school_id";
        $recordsMKey = array($sql, $sql1);
        $data = $mc->get($recordsMKey);
        if($data === false){
            $creditData = $this->dbback->getAll($sql);
            $data = SqlCombinHelper::changeToKeyArray($creditData, 'school_id');
            $numberData = $this->dbback->getAll($sql1);
            foreach ($numberData as $value) {
                $schoolId = $value['school_id'];
                $data[$schoolId]['number'] = $value['number'];
            }
             $mc->set($recordsMKey,$data,3600);
        }
        return $data;
    }
    
    /**
     * 
     * @param type $type 1名字，2单位
     * @return array
     */
    private function modeString($type=1) {
        $mode = $this->mode;
        $arr = array(
            'credit'=>array(1=>'积分',2=>'分'),
            'dou'=>array(1=>'房豆',2=>'房豆'));
        return $arr[$mode][$type];
    }
}

?>
