<?php

/**
 * Description of GrowthBrokerBidHouse
 *
 * @author user
 */
include_once Growth::getCoreLibDir() . '/HouseRent.php';

class GrowthBrokerBidRent {

    const BID_ERROR_AUTH_IS_PAY = 1; //表示不是付费经纪人
    const BID_ERROR_AUTH_CREDIT = 2; //表示积分不足
    const BID_ERROR_AUTH_LEVEL = 4; //表示经纪人等级不够
    const BID_ERROR_AUTH_SCORE = 5; //表示投入的积分不足
    const BID_ERROR_AUTH_HOUSE = 3; //表示不是激活房源
    /**
      const BID_ERROR_AUTH_HOUSE_GRADE = 1;//表示不是优质房源

      const BID_ERROR_AUTH_HOUSE_BLOCK = 6;//表示竞投的小区不满足条件
      const BID_ERROR_AUTH_HOUSE_TITLE = 7;//表示竞投的房源标题不满足条件* */
    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; //未投中,已投的人>=2个
    const BID_NEED_SCORE_TYPE_NOT_WIN_0 = 0; //未投中,已投的人<2个

    const BID_MIN_TIME = 2;//竞投操作的最小时间间隔,单位秒
    
    private $broker;
    private $dbback;
    public static $bidProjectName = '租房竞投';

    /**
     * 1,成功 2,失败,3,暂未投放,4,暂未投中,5,竞投中
     * @var type 
     */
    public static $bidBehavior = array(
        'success' => 1, 'failure' => 2, 'noPut' => 3,
        'noHit' => 4, 'on' => 5, 'tempHit' => 6
    );

    /**
     * 房源几种状态数组
     * @var type 
     */
    public static $houseState = array(
	  0 => '队列', 1 => '激活', 2 => '失效', 3 => '成交', 
	  4 => '删除', 5 => '冻结'
    );

    /**
     * true表示检查是否多图，false表示检查优质
     * @var type 
     */
    private $checkStar = false;
    /**
     *
     * @var array 
     */
    private $bidError;

    private $creditName;
    private $creditUnit;
    /**
     *
     * @var type credit or dou
     */
    private $mode;
    
    private $additionalScore=1;
    
    public function __construct($broker, $growthBrokerCredit,$mode='credit') {
        $this->dbback = Container::getInstance()->get('dbback');
        $this->db = Container::getInstance()->get('db');
        $this->mc = Container::getInstance()->get('mc');
        $this->broker = $broker;
        $this->growthBidRent = new GrowthBidRent();
        $this->houseRent = new HouseRent();
        $this->growthBidRecord = new GrowthBidRentRecordOn();
        $this->growthBidRecordHistory = new GrowthBidRentRecordHistory();
        $this->growthBrokerCredit = $growthBrokerCredit;
        $this->mKeyFront = 'growth_bidrent_';
        $this->mode = $mode;
        if($this->mode == 'credit') {
            $this->creditName = '积分';
            $this->creditUnit = '分';
        } else {
            $this->creditName = '房豆';
            $this->creditUnit = '房豆';
        }
    }

   /**
     * 设置追加的最低分数
     * @param type $additionalScore
     */
    public function setAdditionalScore($additionalScore) {
        $this->additionalScore = $additionalScore;
    }

    /**
     * 获取最低追加分数
     * @return type
     */
    public function getAdditionalScore() {
        return $this->additionalScore;
    }
    
    /**
     * 把日期格式化成月.日
     * @param type $strDate
     * @return string
     */
    private function getMonthDayByFormatTime($strDate) {
        return date('m.d', strtotime($strDate));
    }

    /**
     * 获取经纪人编号
     * @return type
     */
    private function getBrokerId() {
        return $this->broker['id'];
    }

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

    /**
     * 获取这条房源所竞投记录
     * @param type $cPeriods
     * @param type $type
     * @param type $houseId
     */
    public function findHouseBidRecord($periodsId, $houseId, $status = 'on') {
        //查找我的竞投记录所有记录
        if ($status == 'on') {
            return $this->growthBidRecord->findByPidAndHouseId($periodsId, $houseId);
        } else {
            return $this->growthBidRecordHistory->findByPidAndHouseId($periodsId, $houseId);
        }
    }

    /**
     * 获取这条房源某个竞投记录
     * @param type $bid
     * @param type $houseId
     * @return type
     */
    public function findHouseBidTypeRecord($bid, $houseId, $status = 'on') {
        if ($status == 'on') {
            return $this->growthBidRecord->findByBidAndHouseId($bid, $houseId);
        } else {
            return $this->growthBidRecordHistory->findByBidAndHouseId($bid, $houseId);
        }
    }

    /**
     * 经纪人激活房源的总数(不要用这个方法，用下面的)
     * @param type $searchWhere
     * @return type
     */
    public function findHouseCount($searchWhere) {
        $this->houseRent->setWhere($searchWhere);
        return $this->houseRent->getHouseCount();
    }

    /**
     * 经纪人激活房源的总数new
     * @param type $searchWhere
     * @return type
     */
    public function findHouseCountNew($searchWhere) {
        $this->houseRent->setWhere($searchWhere);
        return $this->houseRent->getHouseCountNew();
    }


    /**
     * 根据相应条件获取经纪人激活房源的列表(不要用这个方法，用下面的)
     * @param type $where
     * @param type $orderField
     * @param type $order
     * @param type $start
     * @param type $limit
     */
    public function findHouseList($searchWhere, $orderField, $order, $start, $limit) {
        $this->houseRent->setWhere($searchWhere);
        $this->houseRent->setOrder($orderField, $order);
        $this->houseRent->setLimit($start, $limit);
        return $this->houseRent->getHouseList();
    }

    /**
     * 根据相应条件获取经纪人激活房源的列表new
     * @param type $where
     * @param type $orderField
     * @param type $order
     * @param type $start
     * @param type $limit
     */
    public function findHouseListNew($searchWhere, $orderField, $order, $start, $limit) {
        $this->houseRent->setWhere($searchWhere);
        $this->houseRent->setOrder($orderField, $order);
        $this->houseRent->setLimit($start, $limit);
        return $this->houseRent->getHouseListNew();
    }


    /**
     * 当前房源所有的竞投状况
     * @param type $cPeriods
     * @param type $houseInfo
     * @return boolean
     */
    public function findBidHouseRecordList($cPeriods, $houseInfo) {
        if (!$houseInfo) {
            return false;
        }
        $ids = array();
        foreach ($houseInfo as $value) {
            $ids[] = $value['id'];
        }
        $bidAllRecord = $this->findHouseBidRecord($cPeriods['id'], $ids);
        $bidAllNewRecord = SqlCombinHelper::changeToDoubleKeyArray($bidAllRecord, 'house_id');
        foreach ($houseInfo as &$v) {
            //竞投状态
            $bidStatus = array();
            if ($cPeriods['status'] == 1 || $cPeriods['status'] == 3) {
                //经纪人有竞投的记录
                if (isset($bidAllNewRecord[$v['id']]) && CommonBase::isFullArray($bidAllNewRecord[$v['id']])) {
                    //查找此房源的竞投记录
                    $bidRecord = $bidAllNewRecord[$v['id']];
                    //查找竞投过的词语，及竞投的状态
                    foreach ($bidRecord as $bR) {
                        if ($bR['type'] == 1) {
                            $bidWords = $v['blockshowname'];
                        } else {
                            $bidWords = $this->growthBidRent->getBidHotWordsByBid($bR['bid_id']);
                        }
                        if ($cPeriods['status'] == 1) {
                            //竞投中
                            $bidBehavior = self::$bidBehavior['on'];
                        } else {
                            //竞投结果
                            $mKeyB = $this->mKeyFront . 'winRecord_' . $bR['bid_id'];
                            $winRecord = $this->mc->get($mKeyB);
                            if ($winRecord === false) {
                                $winRecord = $this->findTempWinnerRecord($bR['bid_id']);
                                $this->mc->set($mKeyB, $winRecord, 3600);
                            }
                            $mKeyH = $this->mKeyFront . 'myRecord_' . $bR['bid_id'] . $bR['house_id'];
                            $myRecord = $this->mc->get($mKeyH);
                            if ($myRecord === false) {
                                $myRecord = $this->findHouseBidTypeRecord($bR['bid_id'], $bR['house_id']);
                                $this->mc->set($mKeyH, $myRecord, 3600);
                            }
                            $bidRank = $this->checkWinBid($winRecord, $myRecord);
                            $bidBehavior = $bidRank > 0 ?
                                    self::$bidBehavior['success'] : self::$bidBehavior['failure'];
                        }
                        $bidStatus[] = array(
                            'words' => $bidWords,
                            'behavior' => $bidBehavior,
                        );
                    }
                } else {
                    //暂未投放
                    $bidStatus[] = array(
                        'words' => '',
                        'behavior' => self::$bidBehavior['noPut'],
                    );
                }
                $v['bid_status'] = $bidStatus;
            } else if ($cPeriods['status'] == 2) {
                $v['start_time'] = $cPeriods['start_time'];
            }
            $v['house_id'] = $v['id'];
            $v['price'] = floatval($v['price']);
            $v['block_id'] = $v['blockid'];
            $v['content'] = "{$v['address']}【{$v['room']}室"
                    . "{$v['hall']}" . "厅 {$v['buildarea']}㎡ "
                    . "{$v['price']}】";
            $v['status'] = $cPeriods['status'];
            $v['tg_start_time'] = $cPeriods['tg_start_time'];
            $v['tg_end_time'] = $cPeriods['tg_end_time'];
        }
        return $houseInfo;
    }

    /**
     * 获取竞投中的房源总数
     * @return type
     */
    public function findBidOnHouseRecordCount() {
        $searchWhere = array();
        $brokerId = $this->getBrokerId();
        $searchWhere['broker_id'] = $brokerId;
        $this->growthBidRecord->setWhere($searchWhere);
        return $this->growthBidRecord->findBrokerbidHouseCount();
    }

    /**
     * 获取某次竞投中房源记录
     * @param type $cPeriods
     * @param type $orderField
     * @param type $order
     * @param type $start
     * @param type $limit
     * @return boolean
     */
    public function findBidOnHouseRecord($orderField, $order, $start, $limit) {
        $brokerId = $this->getBrokerId();
        $searchWhere = array();
        $searchWhere['broker_id'] = $brokerId;
        $this->growthBidRecord->setWhere($searchWhere);
        $this->growthBidRecord->setOrder($orderField, $order);
        $this->growthBidRecord->setLimit($start, $limit);
        return $this->growthBidRecord->findBrokerBidHouse();
    }

    /**
     * 获取竞投中的房源信息
     * @param type $orderField
     * @param type $order
     * @param type $start
     * @param type $limit
     */
    public function findBidOnHouseRecordList($cPeriods, $bidHouseRecord) {
        if (!CommonBase::isFullArray($bidHouseRecord) || $cPeriods['status'] == 2) {
            return array();
        }
        $brokerId = $this->getBrokerId();
        $ids = array();
        foreach ($bidHouseRecord as $value) {
            $ids[] = $value['house_id'];
        }
        //获取房源的基本信息
        $searchWhere = array();
        $searchWhere['uid'] = $brokerId;
        $houseids = implode(',', $ids);
        $searchWhere['id'] = "IN($houseids)";
        $this->houseRent->setWhere($searchWhere);
        $house = $this->houseRent->getAllHouse();
        $houseNew = SqlCombinHelper::changeToKeyArray($house, 'id');
        //获取竞投记录
        $bidAllRecord = $this->findHouseBidRecord($cPeriods['id'], $ids);
        $bidAllNewRecord = SqlCombinHelper::changeToDoubleKeyArray($bidAllRecord, 'house_id');
        foreach ($bidHouseRecord as &$value) {
            //经纪人竞投的记录
            $bidRecord = array_key_exists($value['house_id'], $bidAllNewRecord)?$bidAllNewRecord[$value['house_id']]:array();    
            //经纪人的房源
            $houseInfo = $houseNew[$value['house_id']];
            $bidStatus = array();
            foreach ($bidRecord as $v) {
                
                //竞投词语
                if ($v['type'] == 1) {
                    $bidWords = $houseInfo['blockshowname'];
                } else {
                    $bidWords = $this->growthBidRent->getBidHotWordsByBid($v['bid_id']);
                }
                $value['block_id'] = $houseInfo['blockid'];
                //竞投状态
                if ($cPeriods['status'] == 1) {
                    //竞投中
                    $bidBehavior = self::$bidBehavior['on'];
                } else {
                    //竞投结果
                    $mKeyB = $this->mKeyFront . 'winRecord_' . $v['bid_id'];
                    $winRecord = $this->mc->get($mKeyB);
                    if ($winRecord === false) {
                        $winRecord = $this->findTempWinnerRecord($v['bid_id']);
                        $this->mc->set($mKeyB, $winRecord, 3600);
                    }
                    $mKeyH = $this->mKeyFront . 'myRecord_' . $v['bid_id']
                            . $v['house_id'];
                    $myRecord = $this->mc->get($mKeyH);
                    if ($myRecord === false) {
                        $myRecord = $this->findHouseBidTypeRecord($v['bid_id'], $v['house_id']);
                        $this->mc->set($mKeyH, $myRecord, 3600);
                    }
                    $bidRank = $this->checkWinBid($winRecord, $myRecord);
                    $bidBehavior = $bidRank > 0 ?
                            self::$bidBehavior['success'] : self::$bidBehavior['failure'];
                }
                $bidStatus[] = array(
                    'words' => $bidWords,
                    'behavior' => $bidBehavior,
                );
            }
            $value['bid_status'] = $bidStatus;
            //激活房源读取最新信息
            if (isset($houseInfo) && $houseInfo['esta'] == 1) {
                $value['blockshowname'] = $houseInfo['blockshowname'];
                $value['infotype'] = $houseInfo['infotype'];
                $value['address'] = $houseInfo['address'];
                $value['room'] = $houseInfo['room'];
                $value['hall'] = $houseInfo['hall'];
                $value['price'] = $houseInfo['price'];
                $value['priceunit'] = $houseInfo['priceunit'];
                $value['buildarea'] = $houseInfo['buildarea'];
                $value['content'] = "{$houseInfo['address']}【{$houseInfo['room']}室"
                        . "{$houseInfo['hall']}" . "厅 {$houseInfo['buildarea']}㎡ "
                        . "{$houseInfo['price']}】";
                $value['esta'] = $houseInfo['esta'];
                $value['grade'] = $houseInfo['grade'];
                $value['isstar'] = $houseInfo['isstar'];
                $value['block_id'] = $houseInfo['blockid'];
            } else {
                //读取竞投时的填交的信息
                $value['blockshowname'] = $v['blockname'];
                $value['block_id'] = $houseInfo['blockid'];
                $value['infotype'] = $v['infotype'];
                $value['content'] = $v['content'];
                $value['esta'] = isset($houseInfo) ? $houseInfo['esta'] : 4;
                $value['content'] = $v['content'] . '<span style="color:red;">[' 
                        . self::$houseState[$houseInfo['esta']] . ']</span>';
            }
            $value['tg_start_time'] = $cPeriods['tg_start_time'];
            $value['tg_end_time'] = $cPeriods['tg_end_time'];
        }
        return $bidHouseRecord;
    }

    /**
     * 获取竞投历史记录的房源总数
     * @return type
     */
    public function findBidHistoryHouseRecordCount($searchWhere) {
        $recordWhere = array();
        $brokerId = $this->getBrokerId();
        $recordWhere['broker_id'] = $brokerId;
        if(isset($searchWhere['infotype'])) {
        $recordWhere['infotype'] = $searchWhere['infotype'];
        }
        if(isset($searchWhere['blockshowname'])) {
        $recordWhere['blockname'] = $searchWhere['blockshowname'];
        }
		if(array_key_exists('id', $searchWhere)) {
            $recordWhere['house_id'] = $searchWhere['id'];
        }
        $this->growthBidRecordHistory->setWhere($recordWhere);
        return $this->growthBidRecordHistory->findBrokerbidHouseCount();
    }

    /**
     * 
     * @param type $searchWhere
     * @param type $orderField
     * @param type $order
     * @param type $start
     * @param type $limit
     * @return type
     */
    public function findBidHistoryHouseRecord($searchWhere, $orderField, $order, $start, $limit) {
        $brokerId = $this->getBrokerId();
        $recordWhere['broker_id'] = $brokerId;
        if(array_key_exists('infotype', $searchWhere)) {
            $recordWhere['infotype'] = $searchWhere['infotype'];
        }
        if(array_key_exists('blockname', $searchWhere)) {
            $recordWhere['blockname'] = $searchWhere['blockshowname'];
        }
		if(array_key_exists('id', $searchWhere)) {
            $recordWhere['house_id'] = $searchWhere['id'];
        }

        $this->growthBidRecordHistory->setWhere($recordWhere);
        $this->growthBidRecordHistory->setOrder($orderField, $order);
        $this->growthBidRecordHistory->setLimit($start, $limit);
        return $this->growthBidRecordHistory->findBrokerBidHouse();
    }

    /**
     * 获取竞投历史记录的房源信息
     * @param type $orderField
     * @param type $order
     * @param type $start
     * @param type $limit
     */
    public function findBidHistoryHouseRecordList($bidHouseRecord) {
        if (!CommonBase::isFullArray($bidHouseRecord)) {
            return array();
        }
        $brokerId = $this->getBrokerId();
        $growthBidPeriods = new GrowthBidPeriods();
        $ids = array();
        foreach ($bidHouseRecord as $value) {
            $ids[] = $value['house_id'];
        }
        //获取房源的基本信息
        $searchWhere = array();
        $searchWhere['uid'] = $brokerId;
        $houseids = implode(',', $ids);
        $searchWhere['id'] = "IN($houseids)";
        $this->houseRent->setWhere($searchWhere);
        $house = $this->houseRent->getAllHouse();
        $houseNew = SqlCombinHelper::changeToKeyArray($house, 'id');
        foreach ($bidHouseRecord as &$value) {
            $houseInfo = $houseNew[$value['house_id']];
            $periodsId = $value['bid_periods_id'];
            $memKeyRecord = $this->mKeyFront . $periodsId . $value['house_id'];
            $bidRecord = $this->mc->get($memKeyRecord);
            if ($bidRecord === false) {
                $bidRecord = $this->findHouseBidRecord($periodsId, $value['house_id'], 'history');
                $this->mc->set($memKeyRecord, $bidRecord, 600);
            }
            if (!$bidRecord) {
                return array();
            }
            $cBidPeriods = $growthBidPeriods->findById($periodsId);
            $bidStatus = array();
            foreach ($bidRecord as $v) {
                //竞投词语
                $memKeyBid = $this->mKeyFront . $v['bid_id'];
                $bidOne = $this->mc->get($memKeyBid);
                if ($bidOne === false) {
                    $bidOne = $this->growthBidRent->findOneById($v['bid_id']);
                    $this->mc->set($memKeyBid, $bidOne, 3600);
                }
                if ($v['type'] == 1) {
                    $bidWords = $houseInfo['blockshowname'];
                } else {
                    $bidWords = $bidOne['keyword'];
                }
                $intBehavior = $v['status'] == 1 ? self::$bidBehavior['success'] : self::$bidBehavior['failure'];
                $bidStatus[] = array(
                    'behavior' => $intBehavior, 'words' => $bidWords,
                    'score' => $v['score']
                );
                //竞投结果
                $mKeyB = $this->mKeyFront . 'winRecord_' . $v['bid_id'];
                $winRecord = $this->mc->get($mKeyB);
                if ($winRecord === false) {
                    $winRecord = $this->findWinnerRecord($v['bid_id']);
                    $this->mc->set($mKeyB, $winRecord, 3600);
                }
                $mKeyH = $this->mKeyFront . 'myRecord_' . $v['bid_id']
                        . $v['house_id'];
                $myRecord = $this->mc->get($mKeyH);
                if ($myRecord === false) {
                    $myRecord = $this->findHouseBidTypeRecord($v['bid_id'], $v['house_id'], 'history');
                    $this->mc->set($mKeyH, $myRecord, 3600);
                }
                $template = '<span style="padding-left:10px;"><span class="m_l_33 blod">NO.%s：</span><span style="border-right-width: 0px; margin-right: 5px;" class="rank %s">%s</span>'.$this->creditUnit.'</span>';
                $value['record_list'][] = $this->rankList($winRecord, GrowthBidPeriods::BID_PERIODS_STATUS_FINISH, $template, $myRecord);
                $value['number'][] = $bidOne['number'];
                $value['tg_start_time'] = $cBidPeriods['tg_start_time'];
                $value['tg_end_time'] = $cBidPeriods['tg_end_time'];
            }
            $value['bid_status'] = $bidStatus;
            //激活房源读取最新信息
            if (isset($houseInfo) && $houseInfo['esta'] == 1) {
                $value['blockshowname'] = $houseInfo['blockshowname'];
                $value['infotype'] = $houseInfo['infotype'];
                $value['address'] = $houseInfo['address'];
                $value['room'] = $houseInfo['room'];
                $value['hall'] = $houseInfo['hall'];
                $value['price'] = $houseInfo['price'];
                $value['priceunit'] = $houseInfo['priceunit'];
                $value['buildarea'] = $houseInfo['buildarea'];
                $value['content'] = "{$houseInfo['address']}【{$houseInfo['room']}室"
                        . "{$houseInfo['hall']}" . "厅 {$houseInfo['buildarea']}㎡ "
                        . "{$houseInfo['price']}】";
                $value['esta'] = $houseInfo['esta'];
            } else {
                //读取竞投时的填交的信息
                $value['blockshowname'] = $v['blockname'];
                $value['infotype'] = $v['infotype'];
                $value['content'] = $v['content'];
                $value['esta']= isset($houseInfo) ? $houseInfo['esta'] : 4;
                $value['content'] = $v['content'] . '<span style="color:red;">[' 
                        . '' . self::$houseState[$value['esta']] . ']</span>';
            }
        }
        return $bidHouseRecord;
    }

    /**
     * 获取最新一期的竞投记录
     * @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(2, $cPeriods['id']);
            $cPeriods['status'] = 2;
            $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) {
            $bidMaxMinScore = $growthBidRecord->findMaxMinScoreByBidSuccess($v['bid_id']);
            if ($cPeriods['status'] == 1 || $cPeriods['status'] == 3) {
                $bidRecord = $this->findTempWinnerRecord($v['bid_id']);
            } else {
                $bidRecord = $this->findWinnerRecord($v['bid_id']);
            }
            $myRecord = $growthBidRecord->findByBidAndHouseId($v['bid_id'], $v['house_id']);
            $bidRank = $this->checkWinBid($bidRecord, $myRecord);
            //竞投词语
            $bidOne = $this->growthBidRent->findOneById($v['bid_id']);
            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'];
            }
            $houseWhere = array('uid' => $brokerId, 'id' => $v['house_id']);
            $this->houseRent->setWhere($houseWhere);
            $houseInfo = $this->houseRent->getOneHouse();
            $houseInfo['bidType'] = $v['type'];
            if ($v['type'] == 1) {
                $bidWords = $houseInfo['blockshowname'];
            } else {
                $bidWords = $bidOne['keyword'];
            }
            if (isset($houseInfo) && $houseInfo['esta'] == 1) {
                $content = "{$houseInfo['address']}【{$houseInfo['room']}室"
                        . "{$houseInfo['hall']}" . "厅 {$houseInfo['buildarea']}㎡ "
                        . "{$houseInfo['price']}】";
                $esta = $houseInfo['esta'];
            } else {
                $esta = isset($houseInfo) ? $houseInfo['esta'] : 4;
                $content = $v['content'] . '[' . self::$houseState[$esta] . ']';
            }
            if ($cPeriodsStatus == 1 || $cPeriodsStatus == 3) {
                $bidRankUrl = 'market_bid_house.php?type=' . $v['type']
                        . '&houseid=' . $v['house_id'];
            } else {
                $bidRankUrl = 'market_bid_house_manage.php?tab=history';
            }
           
            
            
            $tgStartTime = $cPeriods['tg_start_time'];
            $tgEndTime = $cPeriods['tg_end_time'];
            $arrBidRecord[$k]['projectname'] = self::$bidProjectName;
            $arrBidRecord[$k]['tg_start_time'] = $this->getMonthDayByFormatTime($tgStartTime);
            $arrBidRecord[$k]['tg_end_time'] = $this->getMonthDayByFormatTime($tgEndTime);
            $arrBidRecord[$k]['utime'] = $v['utime'];
            $arrBidRecord[$k]['content'] = $content;
            $arrBidRecord[$k]['score'] = $v['score'];
            $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]['words'] = "【{$bidWords}】";
            $arrBidRecord[$k]['esta'] = $esta;
            $arrBidRecord[$k]['type'] = $v['type'];
            $arrBidRecord[$k]['house_id'] = $v['house_id'];
            $arrBidRecord[$k]['new_words'] = $bidWords;
            $arrBidRecord[$k]['house_status'] = $this->checkHouse($houseInfo, $periodsId); //竞投房源状态
         
           
        }
        //print_r($arrBidRecord);
        return $arrBidRecord;
    }

    /**
     * 验证房源是否是优质房
     * @param type $grade
     */
    private function checkHouseGrade($grade) {
        if ($grade == 1) {
            return true;
        } else {
            $this->bidError['errorCode'] = self::BID_ERROR_AUTH_HOUSE;
            return false;
        }
    }

    /**
     * 验证房源是否是激活房源
     * @param type $grade
     */
    private function checkHouseEsta($esta) {
        if ($esta == 1) {
            return true;
        } else {
            $this->bidError['errorCode'] = self::BID_ERROR_AUTH_HOUSE;
            return false;
        }
    }

    /**
     * 检查房源的标题是否包含热搜词
     * @param type $address
     * @param type $periodsId 
     */
    private function checkHouseAddress($address, $periodsId) {
        $bidHotSearch = $this->growthBidRent->findPeriodsHotSearch($periodsId);
        $bidHotSearchNew = array();
        if ($bidHotSearch) {
            foreach ($bidHotSearch as $v) {
                $bidHotSearchNew[] = $v['keyword'];
            }
        }
        $hotSearchWords = implode('|', $bidHotSearchNew);
        if (preg_match("/{$hotSearchWords}/", $address)) {
            return true;
        } else {
            $this->bidError['errorCode'] = self::BID_ERROR_AUTH_HOUSE;
        }
    }

    /**
     * 检查房源的小区编号是否参与竞投
     * @param type $blockId
     * @param type $periodsId 
     */
    private function checkHouseBlockId($blockId, $periodsId) {
        $bidBlock = $this->growthBidRent->findPeriodsBlock($periodsId);
        $bidBlockNew = array();
        if ($bidBlock) {
            foreach ($bidBlock as $v) {
                $bidBlockNew[] = $v['block_id'];
            }
        }
        if (in_array($blockId, $bidBlockNew)) {
            return true;
        } else {
            $this->bidError['errorCode'] = self::BID_ERROR_AUTH_HOUSE;
            return false;
        }
    }

    //检查房源
    private function checkHouse($houseInfo, $periodsId) {
        if (array_key_exists('esta', $houseInfo)&&$this->checkHouseEsta($houseInfo['esta'])) {
            if($this->checkCustomConf($houseInfo)) {
                if ($houseInfo['bidType'] == 1) {
                    return $this->checkHouseBlockId($houseInfo['blockid'], $periodsId);
                } else {
                    return $this->checkHouseAddress($houseInfo['address'], $periodsId);
                }
            } else {
                return false;
            }
            
        } else {
            return false;
        }
    }
    /**
     * 自定义条件检查
     */
    private function checkCustomConf($houseInfo) {
        if($this->checkStar) {
            return $this->checkHouseStar($houseInfo['isstar']);
        } else {
            return $this->checkHouseGrade($houseInfo['grade']);
        }
    }
    
    public function setCheckStar($checkStar) {
        $this->checkStar = $checkStar;
    }
    
    private function checkHouseStar($star) {
        if($star==3) {
            return true;
        } else {
            $this->bidError['errorCode'] = self::BID_ERROR_AUTH_IS_PAY;
            return false;
        }
    }
    
    //检查经纪人付费
    private function checkBroker() {
        if ($this->broker['is_pay'] == payStatus) {
            return true;
        } else {
            $this->bidError['errorCode'] = self::BID_ERROR_AUTH_IS_PAY;
            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;
        }
    }

    /**
     * 检查投入的积分是否大于所需的最小积分
     * @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;
    }

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

    //竞投
    public function bid($bidId, $score, $houseId) {
        //控制竞投的时间间隔
        if($this->controlTime()==false) {
            $this->bidError['errorCode'] = self::BID_ERROR_MIN_TIME;
            return false;
        }
        $brokerId = $this->broker['id'];
        $bid = $this->growthBidRent->findById($bidId);
        if (!$bid) {
            return false;
        }
        $bidPeriodsId = $bid['bid_periods_id'];
        $type = $bid['type'];
        $myRecord = $this->growthBidRecord->findByBidAndHouseId($bidId, $houseId);
        //本竞投的记录
        $winnerRecord = $this->findTempWinnerRecord($bidId);
        $this->houseRent->setWhere(array('id' => $houseId, 'uid' => $brokerId));
        $houseInfo = $this->houseRent->getOneHouse();
        if ($houseInfo) {
            $houseInfo['bidType'] = $type;
        } else {
            return false;
        }
        if($type==1) {
            $bid['bidWord'] = $houseInfo['blockshowname'];
        } else if($type==2) {
            $bid['bidWord'] = $bid['keyword'];
        }
        $x = $this->checkByRecord($bid, $score, $winnerRecord, $myRecord, $houseInfo);
        if ($x) {
            $bidWord = $bid['bidWord'];
            $winFlag = $this->checkWinBid($winnerRecord, $myRecord);

            //优先房豆消耗权限
            $functionSwitch = config_item('functionSwitch');
            if(!empty($functionSwitch['priorityHousebeanConsume']))
            {
                $housebean_consume_type = '';
                if ($type == 1) {
                    $housebean_consume_type = 5;
                } elseif ($type == 2) {
                    $housebean_consume_type = 6;
                }

                //获取优先消费临近过期的房豆
                $priorityConsumeHousebeanData = $this->getPriorityConsumeHousebean($brokerId, $score);
                if (!empty($priorityConsumeHousebeanData) && !empty($myRecord)) {
                    $payment_housebean_record_id_arr = array_keys($priorityConsumeHousebeanData);
                    $sql = "select * from housebean_consume where relation_id='" . $myRecord['id'] . "' && type='" . $housebean_consume_type . "' && payment_housebean_record_id in(" . implode(',', $payment_housebean_record_id_arr) . ")";
                    $housebeanConsumeInfo = $this->dbback->GetAll($sql);

                    $housebeanConsumeData = array();
                    if (!empty($housebeanConsumeInfo)) {
                        foreach ($housebeanConsumeInfo as $key => $item) {
                            $housebeanConsumeData[$item['payment_housebean_record_id']] = $item;
                        }
                    }

                    foreach ($priorityConsumeHousebeanData as $key => $value) {
                        $sql = "update payment_housebean_record set total = total-" . $value . " where id=" . $key;
                        $this->db->Execute($sql);

                        if (isset($housebeanConsumeData[$key])) {
                            $housebean_consume_num = $value;
                            if ($winFlag > 0) {
                                $housebean_consume_num += $housebeanConsumeData[$key]['num'];
                            }

                            $sql = "update housebean_consume set num='" . $housebean_consume_num . "' where id=" . $item['id'];
                            $this->db->Execute($sql);
                        } else {
                            $sql = "insert into housebean_consume(id,uid,payment_housebean_record_id,num,type,relation_id,addtime) values('','".$brokerId."','" . $key . "','" . $value . "','" . $housebean_consume_type . "','" . $myRecord['id'] . "','" . time() . "')";
                            $this->db->Execute($sql);
                        }
                    }
                }
            }

            switch ($winFlag) {
                case '-1':
                    $fieldData = array('broker_id' => $brokerId,
                        'bid_id' => $bidId,
                        'score' => $score,
                        'house_id' => $houseId,
                        'content' => "{$houseInfo['address']}【{$houseInfo['room']}室"
                        . "{$houseInfo['hall']}" . "厅 {$houseInfo['buildarea']}㎡ "
                        . "{$houseInfo['price']}】",
                        'blockname' => $houseInfo['blockshowname'],
                        'infotype' => $houseInfo['infotype'],
                        'type' => $type,
                        'bid_periods_id' => $bidPeriodsId);
                    $recordId = $this->growthBidRecord->insert($fieldData);
                    if ($recordId) {
                        //增加人数
                        $this->growthBidRent->addJoinNumber($bidId);

                        //经纪人已经参加过竞投
                        $growthBidUserBroker = new GrowthBidUserBroker();
                        $growthBidUserBroker->addJoinBidRentRecord($brokerId);
                        
                        //冻结积分 参与房源竞投，竞投词：学区，冻结积分1234分
                        if($type==1) {
                            $msg = '小区词竞投中投入【'.$bidWord.'】';
                        } else {
                            $msg = '热搜词竞投中投入【'.$bidWord.'】';
                        }
                        $this->growthBrokerCredit->frozenCredit($score,null,'',self::$bidProjectName . $msg);

                        //优先房豆消耗权限
                        if(!empty($functionSwitch['priorityHousebeanConsume']))
                        {
                            //添加房豆消费日志
                            if (!empty($priorityConsumeHousebeanData)) {
                                foreach ($priorityConsumeHousebeanData as $key => $value) {
                                    $sql = "update payment_housebean_record set total = total-" . $value . " where id=" . $key;
                                    $this->db->Execute($sql);

                                    $sql = "insert into housebean_consume(id,uid,payment_housebean_record_id,num,type,relation_id,addtime) values('','".$brokerId."','" . $key . "','" . $value . "','" . $housebean_consume_type . "','" . $recordId . "','" . time() . "')";
                                    $this->db->Execute($sql);
                                }
                            }
                        }

                        //退分
                        $this->complete($bid);

                        //同时关注
                        if (!$this->hasAttention($bidId, $houseId)) {//如果没关注
                            $attentionNumber = GrowthBidAttentionHelper::totalNumber($this->broker);
                            if ($attentionNumber < GrowthBidAttentionHelper::ATTENTION_MAX_NUMBER) {
                                $this->attent($bidId, $bidPeriodsId, $houseId);
                            }
                        }
                    } else {
                        $this->bidError['errorCode'] = self::BID_ERROR_SYS_DB;
                        //记录错误日志
                    }
                    break;
                case '0':
                    $fieldData = array('score' => $score,'status'=>'1');
                    $conf = "house_id='$houseId' and bid_id='$bidId'";
                    $affectRows = $this->growthBidRecord->update($fieldData, $conf);
                    if ($affectRows) {
                        if($type==1) {
                            $msg = '小区词竞投中投入【'.$bidWord.'】';
                        } else {
                            $msg = '热搜词竞投中投入【'.$bidWord.'】';
                        }
                        $this->growthBrokerCredit->frozenCredit($score,null,'',self::$bidProjectName . $msg);
                        //处理其他被超过积分，挤出排名的经纪人，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 = "house_id='$houseId' and bid_id='$bidId'";
                    $affectRows = $this->growthBidRecord->add($fieldData, $conf);
                    if ($affectRows) {
                        if($type==1) {
                            $msg = '小区词竞投中追加【'.$bidWord.'】';
                        } else {
                            $msg = '热搜词竞投中追加【'.$bidWord.'】';
                        }
                        $this->growthBrokerCredit->frozenCredit($score,null,'',  self::$bidProjectName . $msg);
                    } else {
                        
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 获取优先消费的房豆充值记录
     * @param int $brokerId   经纪人ID
     * @param int $score      房豆消费数量
     * @return array
     */
    public function getPriorityConsumeHousebean($brokerId = 0,$score = 0)
    {
        $result = array();
        if(empty($brokerId) || empty($score))
        {
            return $result;
        }

        $time = time();
        $sql = "select id,total from payment_housebean_record where broker_id=".$brokerId." && ".$time."<=endtime order by endtime";
        $info = $this->dbback->GetAll($sql);
        if(!empty($info))
        {
            foreach($info as $key => $item)
            {
                if($item['total'] > 0)
                {
                    if($item['total'] >= $score)
                    {
                        $result[$item['id']] = $score;
                        break;
                    }
                    else
                    {
                        $score = $score - $item['total'];
                        $result[$item['id']] = $item['total'];
                    }
                }
            }
        }

        return $result;
    }

    public function complete($bid) {
        //处理其他被超过积分，挤出排名的经纪人，bid=$bid，and 积分《score and status = 1
        //积分记录 解冻积分，frozen= frozen-score；若关注，则通知
        $bidId = $bid['id'];
        $bidWord = $bid['bidWord'];
        $refundRecord = $this->findRecordForRefund($bidId);
        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['type'] = $value['type'];
                $refundBroker[] = $temp;
            }

            //优先房豆消耗权限
            $functionSwitch = config_item('functionSwitch');
            if(!empty($functionSwitch['priorityHousebeanConsume']))
            {
                //根据优先消费临近过期的房豆规则，此处逻辑：依次退还房豆
                $sql = "select * from housebean_consume where type in(5,6) && relation_id in(" . implode("','", $ids) . ")";
                $housebeanConsumeInfo = $this->dbback->GetAll($sql);
                if (!empty($housebeanConsumeInfo))
                {
                    $housebeanConsumeIdArr = array();
                    $paymentHousebeanRecordScoreData = array();
                    foreach ($housebeanConsumeInfo as $key => $item)
                    {
                        if (isset($paymentHousebeanRecordScoreData[$item['payment_housebean_record_id']]))
                        {
                            $paymentHousebeanRecordScoreData[$item['payment_housebean_record_id']] += $item['num'];
                        }
                        else
                        {
                            $paymentHousebeanRecordScoreData[$item['payment_housebean_record_id']] = $item['num'];
                        }

                        $housebeanConsumeIdArr[$item['id']] = $item['id'];
                    }

                    $sql = "delete from housebean_consume where id in(".implode(',',$housebeanConsumeIdArr).")";
                    $this->db->Execute($sql);

                    foreach ($paymentHousebeanRecordScoreData as $key => $value)
                    {
                        $sql = "update payment_housebean_record set total=total+" . $value . " where id=" . $key;
                        $this->db->Execute($sql);
                    }
                }
            }

            //status标记为失败
            $this->growthBidRecord->update(array('status' => 0), "id in ('" . implode("','", $ids) . "')");
            //解冻积分
            if ($refundBroker) {
                //$growthCredit = $this->growthBrokerCredit->getGrowthCredit();
                foreach ($refundBroker as $value) {
                    //$growthCredit->unfreeze($value['broker_id'], $value['score']);
                    if($value['type']==1) {
                            //$msg = '小区词竞投中追加【'.$bidWord.'】';
                            $msg = '小区词竞投失败返还【'.$bidWord.'】';
                        } else {
                            //$msg = '热搜词竞投中追加【'.$bidWord.'】';
                            $msg = '热搜词竞投失败返还【'.$bidWord.'】';
                        }
                    $this->growthBrokerCredit->frozenCredit($value['score'],$value['broker_id'],'',self::$bidProjectName . $msg);
                }
            }
        }
    }

    /**
     * 最后一次投入的分数
     * @param array $bid
     */
    public function lastBidScore($myRecord) {
        if ($myRecord) {
            return $myRecord['score'];
        } else {
            return 0;
        }
    }

    /**
     * 查找暂时赢得竞投的人的竞投记录
     * @param int $bidId 竞投id
     * @return array 中投的记录数组
     */
    public function findTempWinnerRecord($bidId) {
        return $this->growthBidRecord->findByBid($bidId, "score desc, utime asc", "0,2");
    }

    /**
     * 查找赢得竞投的人的竞投记录
     * @param int $bidId 竞投id
     * @return array 中投的记录数组
     */
    public function findWinnerRecord($bidId) {
        return $this->growthBidRecordHistory->findBy("bid_id='$bidId' and status=1", "score desc, utime asc", "0,2");
    }

    /**
     * 退分的标志
     * @param int $bidId
     * @return array
     */
    public function findRecordForRefund($bidId) {
        $res = $this->growthBidRecord->findBy("bid_id='$bidId' and status=1", "score desc, utime asc", "2,10");
        if ($res) {
            return $res;
        } else {
            return array();
        }
    }

    /**
     * 检查投中了没有以及第几位
     * @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['house_id'];
            $i = 0;
            foreach ($winnerRecord as $value) {
                $i++;
                if ($value['house_id'] == $myRecordId) {
                    $number = $i;
                    break;
                }
            }
        } else {
            $number = '-1';
        }
        return $number;
    }

    /**
     * 返回竞投需要投入的最低积分
     * @return array $result = array('type'=>'','score'=>'');type表示是否起拍，0，起拍分,1,第二名的分，2,追加分
     */
    public function getNeedScore($bid, $winnerRecord, $myRecord) {
        //检查我投中没有
        $result = array('type' => '', 'score' => '');
        $bidRank = $this->checkWinBid($winnerRecord, $myRecord);
        if ($bidRank > 0) {//投中了
            $result['type'] = self::BID_NEED_SCORE_TYPE_WIN;
            $result['score'] = $this->additionalScore;
        } else {//未投中
            if (count($winnerRecord) == 2) {
                $result['type'] = self::BID_NEED_SCORE_TYPE_NOT_WIN_1;
                $result['score'] = $winnerRecord[1]['score'] + 1;//$this->additionalScore;
            } else {
                $result['type'] = self::BID_NEED_SCORE_TYPE_NOT_WIN_0;
                $result['score'] = $bid?$bid['min_score']:0;
            }
        }
        return $result;
    }

    /**
     * 返回竞投面板上的提示，积分够不够的提示
     * @param int $myCredit 我的积分
     * @param array $needScore 本竞投需要的积分 ，通过 getNeedScore($bid,$winnerRecord,$myRecord)返回
     * @return string 提示字符串
     */
    public function tipOnPanel($myCredit, $needScore) {
        $tip = "";
        if ($needScore) {
            $type = $needScore['type'];
            $minScore = $needScore['score'];
            if($this->mode=='credit') {
                $t = "您".$this->creditName."不够哦 " . '<a target="_blank" href="./my_growth.php">先去赚'.$this->creditName.'&gt;&gt;</a>';
            } else {
                $t = "您".$this->creditName."不够哦 ";
            }
            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) {
        $myScore = $this->lastBidScore($myRecord);
        if ($winFlag == '-1') {
            $tip2 = "";
        } elseif ($winFlag == 0) {
            $tip2 = "我已投入" . $myScore . "".$this->creditName.",由于未抢过前2名，已退还。";
        } else {
            $tip2 = "我已投入" . $myScore . "".$this->creditName."";
        }
        return $tip2;
    }

    /**
     * 生成计时圆环
     * @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;
        }
    }

    /**
     * 竞投面板上输入框等
     * @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->creditName.':<span class="calScore" value="' . $myScore . '" style="width: 21px; color: red;">' . $myScore . '</span>'.$this->creditUnit;
            }
        }
        return $default;
    }

    public function getAttentionList($cPeriods) {
        $bidPeriodsId = $cPeriods['id'];
        $attentionList = $this->findAttention($bidPeriodsId);
        //print_r($attentionList);
        if (!$attentionList) {//没有关注返回空数组
            return array();
        }
        $bidList = array();
        foreach ($attentionList as $value) {
            $myRecords = $this->findHouseBidRecord($bidPeriodsId, $value['house_id']);
            $bidOne = $this->growthBidRent->findById($value['target_id']);
            $type = $bidOne['type'];
            $temp = $this->findHouseBidRecordList($cPeriods, $myRecords, $type, $value['house_id']);
            $temp['disabled_bid_link'] = $this->getBidError()?true:false;
            $bidList[] = $temp;//$this->findHouseBidRecordList($cPeriods, $myRecords, $type, $value['house_id']);
        }
        return $bidList;
    }

    /**
     * 获取本期房源竞投的数据
     * @param type $cBidPeriods
     * @param type $myRecord
     * @param type $type
     */
    public function findHouseBidRecordList($cPeriods, $myRecords, $type, $houseId, $bidId = '') {
        $periodsId = $cPeriods['id'];
        $bidPeriodsStatus = $cPeriods['status'];
        $brokerId = $this->getBrokerId();
        $myCredit = $this->broker['credit'];
        if(count($myRecords)) {
            $myRecordsNew = SqlCombinHelper::changeToKeyArray($myRecords, 'type');
            $myRecord = array_key_exists($type, $myRecordsNew)?$myRecordsNew[$type]:array();
        } else {
            $myRecord = array();
        }
        
        //获取这条房源详细信息
        $searchWhere = array('id' => $houseId, 'uid' => $brokerId);
        $this->houseRent->setWhere($searchWhere);
        $houseInfo = $this->houseRent->getOneHouse();
        if (!$houseInfo) {
            $this->bidError['errorCode'] = self::BID_ERROR_AUTH_HOUSE;
            return false;
        }
        //判断房源是否有效
        $houseInfo['bidType'] = $type;
        if (!$this->checkHouse($houseInfo, $periodsId)) {
            //return false;
        }
        if ($type == 2) {
            $hotSearch = $this->growthBidRent->findPeriodsHotSearch($periodsId);
            $hotSearchNew = SqlCombinHelper::changeToKeyArray($hotSearch, 'id');
            $houseInfo['hotsearch'] = array();
            $houseInfo['keyword'] = '';
            if ($myRecord) {
                //热搜词竞投了
                $keyword = $hotSearchNew[$myRecord['bid_id']]['keyword'];
                $bidId = $myRecord['bid_id'];
                $houseInfo['hotsearch'][] = array(
                    'bid' => $myRecord['bid_id'],
                    'keyword' => $keyword,
                );
                $houseInfo['keyword'] = $keyword;
            } else {
                //匹配房源标题可以竞投的关键词
                foreach ($hotSearch as $v) {
                    if (array_key_exists('address',$houseInfo)&&strstr($houseInfo['address'], $v['keyword'])) {
                        $houseInfo['hotsearch'][] = array(
                            'bid' => $v['id'],
                            'keyword' => $v['keyword']
                        );
                    }
                }
                if ($bidId) {
                    //没有竞投，只是选择了某个竞投词
                    $keyword = $hotSearchNew[$bidId]['keyword'];
                    $houseInfo['keyword'] = $keyword;
                }
            }
        } else {
            $block = $this->growthBidRent->findPeriodsBlock($periodsId);
            $blockNew = SqlCombinHelper::changeToKeyArray($block, 'block_id');
            if (!array_key_exists('blockid', $houseInfo)||!isset($blockNew[$houseInfo['blockid']])) {
                //此小区不允许竞投
                $this->bidError['errorCode'] = self::BID_ERROR_AUTH_HOUSE;
                return false;
            }
            $bidId = $blockNew[$houseInfo['blockid']]['id'];
        }
        if ($bidId) {
            $houseInfo['bid'] = $bidId;
        } else {
            $houseInfo['bid'] = '';
        }
        //关注记录
        $attentionList = $this->findAttention($periodsId);
        //预处理
        //print_r($attentionList);
        $attentionListNew = SqlCombinHelper::changeToDoubleKeyArray($attentionList, 'target_id', 'house_id');
        //print_r($attentionListNew);
        if (isset($myRecord) || $type == 1 || $bidId) {
            $bidOne = $this->growthBidRent->findById($bidId);
        }
        $houseInfo['rule_score'] = $bidOne['min_score'];
        if ($cPeriods['status'] == 1) {
            //返回竞投记录
            $houseInfo['my_record'] = $myRecord;
            $houseInfo['bid_status'] = $bidPeriodsStatus;
            $houseInfo['record'] = $bidOne?$this->findTempWinnerRecord($bidOne['id']):array();
            //返回可以使用的积分
            $houseInfo['my_credit'] = $myCredit;
            //上次投的积分
            $houseInfo['my_score'] = $this->lastBidScore($houseInfo['my_record']);
            //关注状态
            if (array_key_exists($bidId, $attentionListNew) && array_key_exists($houseId, $attentionListNew[$bidId])) {
                $houseInfo['attention_id'] = $attentionListNew[$bidId][$houseId];
            }
            //默认页面打开
            if (empty($houseInfo['my_record']) && $type == 2 && $bidId == '') {
                $tempBid = $this->growthBidRent->findById($houseInfo['hotsearch'][0]['bid']);
                $houseInfo['min_score'] = array('type' => 0, 'score' => $tempBid['min_score']);
                $houseInfo['rule_score'] = $houseInfo['rule_score'] ? $houseInfo['rule_score'] : $tempBid['min_score'];
                $houseInfo['number'] = '--'; //参加人数     
            } else {
                //竞投所需要的最低分
                $houseInfo['min_score'] = $this->getNeedScore($bidOne, $houseInfo['record'], $houseInfo['my_record']);
                $houseInfo['number'] = $bidOne?$bidOne['number']:0; //参加人数     
            }
            //提示
            $houseInfo['tip'] = $this->tipOnPanel($houseInfo['my_credit'], $houseInfo['min_score']);
            //判断有没有竞投成功
            $winFlag = $this->checkWinBid($houseInfo['record'], $houseInfo['my_record']);
            $houseInfo['winFlag'] = $winFlag;
            //提示1
            $houseInfo['tip1'] = $this->tip1OnPanel($houseInfo['my_record'], $winFlag);
            //积分输入框默认内容
            $houseInfo['score_input_default'] = $this->scoreInputDefault($houseInfo['min_score'], $houseInfo['my_score']);

            //竞投信息
            $houseInfo['bid_status_str'] = '竞投中';
            $houseInfo['end_time'] = $cPeriods['end_time'];
            $houseInfo['tg_start_time'] = $cPeriods['tg_start_time'];
            $houseInfo['tg_end_time'] = $cPeriods['tg_end_time'];
            $houseInfo['start_time'] = $cPeriods['start_time'];
            $houseInfo['timeRing'] = $this->TimeRing($houseInfo['start_time'], $houseInfo['end_time']);
        } else if ($cPeriods['status'] == 3) {
            $houseInfo['bid_status_str'] = '竞投结束';
            $houseInfo['bid_status'] = $bidPeriodsStatus;
            $houseInfo['tg_start_time'] = $cPeriods['tg_start_time']; //推广时间
            $houseInfo['tg_end_time'] = $cPeriods['tg_end_time']; //推广时间
            $houseInfo['end_time'] = $cPeriods['end_time']; //竞投结束时间
            $houseInfo['start_time'] = $cPeriods['start_time'];
            $houseInfo['timeRing'] = $this->TimeRing($houseInfo['start_time'], $houseInfo['end_time']);

            //投入积分前2位
            $houseInfo['record'] = $bidOne?$this->findTempWinnerRecord($bidOne['id']):array();
            $houseInfo['number'] = $bidOne?$bidOne['number']:0; //参加人数    
            //关注状态
            if ($bidOne&&array_key_exists($bidOne['id'], $attentionListNew) && $attentionListNew[$bidId][$houseId]) {
                $houseInfo['attention_id'] = $attentionListNew[$bidOne['id']][$houseId];
            }
            //竞拍记录
            //echo $tempBid['id'].'x';
            $houseInfo['my_record'] = $myRecord; //我的记录
            $houseInfo['my_credit'] = $myCredit; //我的可用积分
            if ($houseInfo['my_record'] == '' && $type == 2 && $bidId == '') {
                $tempBid = $this->growthBidRent->findById($hotSearchId[0]);
                $houseInfo['min_score'] = array('type' => 0, 'score' => $tempBid['min_score']);
                $houseInfo['number'] = '--'; //参加人数     
            } else {
                //竞投所需要的最低分
                $houseInfo['min_score'] = $this->getNeedScore($bidOne, $houseInfo['record'], $houseInfo['my_record']);
                $houseInfo['number'] = $bidOne?$bidOne['number']:0; //参加人数     
            }
            //最低起拍积分
            //计算，没投过
            //上次投的积分
            $houseInfo['my_score'] = $this->lastBidScore($houseInfo['my_record']);
            //所需最低积分，是个数组
            $houseInfo['min_score'] = $this->getNeedScore($bidOne, $houseInfo['record'], $houseInfo['my_record']);
            //提示
            $houseInfo['tip'] = $this->tipOnPanel($houseInfo['my_credit'], $houseInfo['min_score']);
            //是否投中标记
            $winFlag = $this->checkWinBid($houseInfo['record'], $houseInfo['my_record']);

            $houseInfo['winFlag'] = $winFlag;
            //提示1
            $houseInfo['tip1'] = $this->tip1OnPanel($houseInfo['my_record'], $winFlag);
            //积分输入框默认内容
            $houseInfo['score_input_default'] = $this->scoreInputDefault($houseInfo['min_score'], $houseInfo['my_score']);
        } else if ($cPeriods['status'] == 2) {
            //竞投信息
            $houseInfo['bid_status_str'] = '敬请期待'; //'上期竞投结束';
            $houseInfo['bid_status'] = $bidPeriodsStatus;
            $houseInfo['tg_start_time'] = $cPeriods['tg_start_time']; //推广时间
            $houseInfo['tg_end_time'] = $cPeriods['tg_end_time']; //推广时间
            $houseInfo['end_time'] = $cPeriods['end_time']; //竞投结束时间
            $houseInfo['start_time'] = $cPeriods['start_time']; //竞投开始时间
            $houseInfo['timeRing'] = $this->TimeRing($houseInfo['start_time'], $houseInfo['end_time']);
            //竞拍记录
            //echo $tempBid['id'].'x';
            //$houseInfo['my_record'] = $myRecord;//我的记录
            $houseInfo['my_credit'] = $myCredit; //我的可用积分
            $houseInfo['number'] = '--'; //参加人数  
            $houseInfo['record'] = array();
            //最低起拍积分
            //计算，没投过
            //上次投的积分
            $houseInfo['my_record'] = $myRecord;
            $houseInfo['my_score'] = $this->lastBidScore($houseInfo['my_record']);
            //所需最低积分，是个数组
            if ($type == 2) {
                $tempBid = $this->growthBidRent->findById($houseInfo['hotsearch'][0]['bid']);
                $houseInfo['min_score'] = array('type' => 0, 'score' => $tempBid['min_score']);
            } else {
                $houseInfo['min_score'] = $this->getNeedScore($bidOne, $houseInfo['record'], $houseInfo['my_record']);
            }
            //提示
            $houseInfo['tip'] = $this->tipOnPanel($houseInfo['my_credit'], $houseInfo['min_score']);
            //是否投中标记
            //$winFlag = $this->checkWinBid($houseInfo['record'], $houseInfo['my_record']);
            //$houseInfo['winFlag'] = $winFlag;
            //提示1
            // $houseInfo['tip1'] = $this->tip1OnPanel($houseInfo['my_record'], $winFlag); 
            //积分输入框默认内容
            $houseInfo['score_input_default'] = $this->scoreInputDefault($houseInfo['min_score'], $houseInfo['my_score']);
        }
        $houseInfo['type'] = 3;
        return $houseInfo;
    }

    /**
     * 获取某次最新竞投状况
     * @param type $bid
     */
    public function getNewBidBaseInfo($bidOne) {
        //查找前几名的分值情况
        $bidRecord = $this->findTempWinnerRecord($bidOne['id']);
        //如果有竞投记录查看最新排名的情况
        //bid_id获取竞投的人数
        $userNumber = $bidOne['number'];
        return array('number' => $userNumber, 'records' => $bidRecord);
    }

    /**
     * 返回排名列表
     * @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) {
        if (!$records) {
            $records = array();
        }
        $records = array_pad($records, 2, array());
        $html = '';
        foreach ($records as $key => $value) {
            if ($tType == GrowthBidPeriods::BID_PERIODS_STATUS_ON) {
                $html .= $this->renderRankHasScore($key, $value, $myrecord, $template);
            } else {
                $html .= $this->renderRankNoScore($key, $value, $myrecord, $template);
            }
        }
        //echo $html;
        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 = $no>2?'rank02':'';
        $rank02 = 'rank02';
        if (!empty($r)) {
            //$score = $r['score']?$r['score']:'— —';
            //$rank02 = 'rank02';
            if ($myrecord && $myrecord['id'] == $r['id']) {//判断是不是自己
                //echo 'xxx';
                //echo "#".$r['id']."--#".$myrecord['id'];
                $rank02 = '';
                $score = '<strong class="num">' . $r['score'] . '</strong>'.$this->creditUnit;
            } 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_box"><div class="fraction_rank'
                    . ' radius3"><span class="rank ' . $rank02 . '">NO.' . $no . '</span>'
                    . '<span class="fraction">' . $score . '</span></div></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_box"><div class="fraction_rank'
                    . ' radius3"><span class="rank ' . $rank02 . '">NO.' . $no . '</span>'
                    . '<span class="fraction"><strong class="num">' . $score
                    . '</strong>'.$this->creditUnit.'</span></div></div>';
        }
        return $html;
    }

    /**
     * 获取往期竞投历史记录总数
     * @param type $bids
     * @return type
     */
    public function findBidHistoryRecordCount($type, $bid) {
        return $this->growthBidRent->findHistoryByTypeAndBid($type, $bid);
    }

    /**
     * 获取往期竞投历史记录
     * @param type $start
     * @param type $limit
     */
    public function findBidHistoryRecordList($bids) {
        //bid 获取这期竞投的type及 
        //如果type=1 小区词 通过block_id type =2 匹配keyword
        //找出历史四期bid，并且bid<>$bid
        if ($bids) {
            foreach ($bids as $v) {
                $bidNews[] = $v['id'];
            }
            //$bidIds = implode("','", $bidNews);
            //$bidWhere = "bid_id IN ('" . $bidIds . "')";
        }
        foreach ($bids as $value) {
            $bidPeriodsIds[] = $value['bid_periods_id'];
        }
        $growthBidPeriods = new GrowthBidPeriods();
        $bidPeriodsMKey = $bidPeriodsIds;
        $bidPs = $this->mc->get($bidPeriodsMKey);
        if ($bidPs === false) {
            $bidPs = $growthBidPeriods->findBy("id in ('" . implode("','", $bidPeriodsIds) . "')");
            $bidPs = SqlCombinHelper::changeToKeyArray($bidPs, 'id');
            $this->mc->set($bidPeriodsMKey, $bidPs, 3600);
        }
        //$bidHistoryRecord = $this->growthBidRecordHistory->findBidHistoryBy($bidWhere, $start, $limit);
        $bidNewHistoryRecord = array();
        $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="%s">%s</span>'.$this->creditUnit.'</div>';
        $block = new Block();
        foreach ($bids as $bid) {
            $periodsId = $bid['bid_periods_id'];
            if ($bid['type'] == 1) {
                $blockOne = $block->findOneBy($bid['block_id']);
                $keyword = $blockOne['blockname'];
            } else {
                $keyword = $bid['keyword'];
            }
            $bidNewHistoryRecord[] = array(
                'tg_start_time' => $bidPs[$periodsId]['tg_start_time'],
                'tg_end_time' => $bidPs[$periodsId]['tg_end_time'],
                'number' => $bid['number'],
                'bid_status' => '已结束',
                'record_list' => $this->rankList($this->findWinnerRecord($bid['id']), GrowthBidPeriods::BID_PERIODS_STATUS_FINISH, $template),
                'keyword' => $keyword,
            );
        }
        return $bidNewHistoryRecord;
    }

    public function hasAttention($bidId, $houseId) {
        //检查是否关注过
        $growthAttention = new GrowthBidAttention();
        $brokerId = $this->broker['id'];
        $conf = "broker_id='$brokerId' and type=2 and target_id='$bidId' and house_id='$houseId'";
        $number = $growthAttention->findNumberBy($conf);
        if ($number == 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查是否可以关注
     * @param int $bidid 竞投id
     */
    public function checkAttention($bidId, $houseId) {
        //return true;
        if ($this->hasAttention($bidId, $houseId)) {
            return false;
        }
        if ($this->checkBroker()) {
            $bid = $this->growthBidRent->findById($bidId);
            if ($bid) {
                //$blockId = $bid['broker_id'];
                $bidBrokerLevel = $bid['broker_level']; //可以竞投的等级
                return $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=2");
    }

    public function attent($bidId, $cBidPeriods, $houseId) {
        $fieldData = array();
        $fieldData['broker_id'] = $this->broker['id'];
        $fieldData['type'] = 2;
        $fieldData['target_id'] = $bidId;
        $fieldData['bid_periods_id'] = $cBidPeriods;
        $fieldData['house_id'] = $houseId;
        $growthAttention = new GrowthBidAttention();
        //print_r($fieldData);
        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);
    }
    
    /**
     * 控制可以参与竞投的时间间隔
     */
    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()+self::BID_MIN_TIME;
                return true;
            }
        } else {
            $_SESSION['last_bid_time'] = time()+self::BID_MIN_TIME;
            return true;
        }
    }
}
