<?php

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

class GrowthBrokerBidHouse {

    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 => '冻结'
    );

    /**
     *
     * @var array 
     */
    private $bidError;

    public function __construct($broker, $growthBrokerCredit) {
        $this->dbback = Container::getInstance()->get('dbback');
        $this->db = Container::getInstance()->get('db');
        $this->mc = Container::getInstance()->get('mc');
        $this->broker = $broker;
        $this->growthBidHouse = new GrowthBidHouse();
        $this->houseSell = new HouseSell();
        $this->growthBidRecord = new GrowthBidHouseRecordOn();
        $this->growthBidRecordHistory = new GrowthBidHouseRecordHistory();
        $this->growthBrokerCredit = $growthBrokerCredit;
        $this->mKeyFront = 'growth_bidhouse_';
    }

    /**
     * 把日期格式化成月.日
     * @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->houseSell->setWhere($searchWhere);
        return $this->houseSell->getHouseCount();
    }

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

    /**
     * 当前房源所有的竞投状况
     * @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->growthBidHouse->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['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->houseSell->setWhere($searchWhere);
        $house = $this->houseSell->getAllHouse();
        $houseNew = SqlCombinHelper::changeToKeyArray($house, 'id');
        //获取竞投记录
        $bidAllRecord = $this->findHouseBidRecord($cPeriods['id'], $ids);
        $bidAllNewRecord = SqlCombinHelper::changeToDoubleKeyArray($bidAllRecord, 'house_id');
        foreach ($bidHouseRecord as &$value) {
            //经纪人竞投的记录
            $bidRecord = $bidAllNewRecord[$value['house_id']];
            //经纪人的房源
            $houseInfo = $houseNew[$value['house_id']];
            $bidStatus = array();
            foreach ($bidRecord as $v) {
                //竞投词语
                if ($v['type'] == 1) {
                    $bidWords = $houseInfo['blockshowname'];
                } else {
                    $bidWords = $this->growthBidHouse->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['content'] = "{$houseInfo['address']}【{$houseInfo['room']}室"
                        . "{$houseInfo['hall']}" . "厅 {$houseInfo['buildarea']}㎡ "
                        . "{$houseInfo['price']}万】";
                $value['esta'] = $houseInfo['esta'];
                $value['grade'] = $houseInfo['grade'];
            } 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[$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;
        $recordWhere['infotype'] = $searchWhere['infotype'];
        $recordWhere['blockname'] = $searchWhere['blockshowname'];
        $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;
        $recordWhere['infotype'] = $searchWhere['infotype'];
        $recordWhere['blockname'] = $searchWhere['blockshowname'];
        $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->houseSell->setWhere($searchWhere);
        $house = $this->houseSell->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->growthBidHouse->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>分</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['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']);
            $growthBidRecord = $this->growthBidRecordHistory;
        }
        $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->growthBidHouse->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->houseSell->setWhere($houseWhere);
            $houseInfo = $this->houseSell->getOneHouse();
            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;
        }
        //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->growthBidHouse->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->growthBidHouse->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 ($this->checkHouseEsta($houseInfo['esta']) && $this->checkHouseGrade($houseInfo['grade'])) {
            if ($houseInfo['bidType'] == 1) {
                return $this->checkHouseBlockId($houseInfo['blockid'], $periodsId);
            } else {
                return $this->checkHouseAddress($houseInfo['address'], $periodsId);
            }
        } else {
            return false;
        }
    }

    //检查经纪人付费
    private function checkBroker() {
        if ($this->broker['is_pay'] == 0) {
            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->growthBidHouse->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->houseSell->setWhere(array('id' => $houseId, 'uid' => $brokerId));
        $houseInfo = $this->houseSell->getOneHouse();
        if ($houseInfo) {
            $houseInfo['bidType'] = $type;
        } else {
            return false;
        }
        $x = $this->checkByRecord($bid, $score, $winnerRecord, $myRecord, $houseInfo);
        if ($x) {
            $winFlag = $this->checkWinBid($winnerRecord, $myRecord);
            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->growthBidHouse->addJoinNumber($bidId);

                        //经纪人已经参加过竞投
                        $growthBidUserBroker = new GrowthBidUserBroker();
                        $growthBidUserBroker->addJoinBidHouseRecord($brokerId);

                        //冻结积分
                        $this->growthBrokerCredit->frozenCredit($score);
                        //退分
                        $this->complete($bidId);

                        //同时关注
                        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) {
                        $this->growthBrokerCredit->frozenCredit($score);
                        //处理其他被超过积分，挤出排名的经纪人，bid=$bid，and 积分《score and status = 1
                        //积分记录 解冻积分，frozen= frozen-score；若关注，则通知
                        $this->complete($bidId);
                    } 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) {
                        $this->growthBrokerCredit->frozenCredit($score);
                    } else {
                        
                    }
                    break;
                default:
                    break;
            }
        }
    }

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

    /**
     * 最后一次投入的分数
     * @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'] = 1;
        } else {//未投中
            if (count($winnerRecord) == 2) {
                $result['type'] = self::BID_NEED_SCORE_TYPE_NOT_WIN_1;
                $result['score'] = $winnerRecord[1]['score'] + 1;
            } else {
                $result['type'] = self::BID_NEED_SCORE_TYPE_NOT_WIN_0;
                $result['score'] = $bid['min_score'];
            }
        }
        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 ($type == 0) {
                $tip = $myCredit < $minScore ? "您积分不够哦 " . '<a target="_blank" href="./my_growth.php">先去赚积分&gt;&gt;</a>' : "";
            }
            if ($type == 1) {
                $tip = $myCredit < $minScore ? "您积分不够哦 " . '<a target="_blank" href="./my_growth.php">先去赚积分&gt;&gt;</a>' : "";
            }
            if ($type == 2) {
                $tip = $myCredit < 1 ? "您积分不够哦 " . '<a target="_blank" href="./my_growth.php">先去赚积分&gt;&gt;</a>' : "";
            }
        }
        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 . "积分,由于未抢过前2名，已退还。";
        } else {
            $tip2 = "我已投入" . $myScore . "积分";
        }
        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'] = "至少1";
                $default['span'] = "我要追加";
                $default['totalTip'] = '投入积分:<span class="calScore" value="' . $myScore . '" style="width: 21px; color: red;">' . $myScore . '</span>分';
            }
        }
        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->growthBidHouse->findById($value['target_id']);
            $type = $bidOne['type'];
            $bidList[] = $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'];
        $myRecordsNew = SqlCombinHelper::changeToKeyArray($myRecords, 'type');
        $myRecord = $myRecordsNew[$type];
        //获取这条房源详细信息
        $searchWhere = array('id' => $houseId, 'uid' => $brokerId, 'esta' => 1);
        $this->houseSell->setWhere($searchWhere);
        $houseInfo = $this->houseSell->getOneHouse();
        //判断房源是否有效
        $houseInfo['bidType'] = $type;
        if (!$this->checkHouse($houseInfo, $periodsId)) {
            return false;
        }
        if ($type == 2) {
            $hotSearch = $this->growthBidHouse->findPeriodsHotSearch($periodsId);
            $hotSearchNew = SqlCombinHelper::changeToKeyArray($hotSearch, 'id');
            $houseInfo['hotsearch'] = array();
            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 (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->growthBidHouse->findPeriodsBlock($periodsId);
            $blockNew = SqlCombinHelper::changeToKeyArray($block, 'block_id');
            if (!isset($blockNew[$houseInfo['blockid']])) {
                //此小区不允许竞投
                $this->bidError['errorCode'] = self::BID_ERROR_AUTH_HOUSE;
                return false;
            }
            $bidId = $blockNew[$houseInfo['blockid']]['id'];
        }
        if ($bidId) {
            $houseInfo['bid'] = $bidId;
        }
        //关注记录
        $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->growthBidHouse->findById($bidId);
        }
        if ($cPeriods['status'] == 1) {
            //返回竞投记录
            $houseInfo['my_record'] = $myRecord;
            $houseInfo['bid_status'] = $bidPeriodsStatus;
            $houseInfo['record'] = $this->findTempWinnerRecord($bidOne['id']);
            //返回可以使用的积分
            $houseInfo['my_credit'] = $myCredit;
            //上次投的积分
            $houseInfo['my_score'] = $this->lastBidScore($houseInfo['my_record']);
            //关注状态
            if ($attentionListNew[$bidId] && $attentionListNew[$bidId][$houseId]) {
                $houseInfo['attention_id'] = $attentionListNew[$bidId][$houseId];
            }
            //默认页面打开
            if ($houseInfo['my_record'] == '' && $type == 2 && $bidId == '') {
                $tempBid = $this->growthBidHouse->findById($houseInfo['hotsearch'][0]['bid']);
                $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['number']; //参加人数     
            }
            //提示
            $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['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['timeRing'] = $this->TimeRing($houseInfo['start_time'], $houseInfo['end_time']);

            //投入积分前2位
            $houseInfo['record'] = $this->findTempWinnerRecord($bidOne['id']);
            $houseInfo['number'] = $bidOne['number']; //参加人数    
            //关注状态
            if ($attentionListNew[$bidOne['id']] && $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->growthBidHouse->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['number']; //参加人数     
            }
            //最低起拍积分
            //计算，没投过
            //上次投的积分
            $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['my_score'] = $this->lastBidScore($houseInfo['my_record']);
            //所需最低积分，是个数组
            if ($type == 2) {
                $tempBid = $this->growthBidHouse->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'] = 2;
        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>分';
            } 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['score'] ? $r['score'] : '— —';
        $rank02 = 'rank02';
        if ($myrecord) {//判断是不是自己
            //echo 'xxx';
            //echo "#".$r['id']."--#".$myrecord['id'];
            if ($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>分</span></div></div>';
        }
        return $html;
    }

    /**
     * 获取往期竞投历史记录总数
     * @param type $bids
     * @return type
     */
    public function findBidHistoryRecordCount($type, $bid) {
        return $this->growthBidHouse->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>分</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->growthBidHouse->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;
        }
    }
}
