<?php

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

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

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

    const BID_MIN_TIME = 2;//竞投操作的最小时间间隔,单位秒
    /**
     * 1,成功 2,失败,3,暂未投放,4,暂未投中,5,竞投中
     * @var type 
     */
    public static $bidBehavior = array(
        'success' => 1, 'failure' => 2, 'noPut' => 3, 
        'noHit' => 4, 'on' => 5, 'tempHit' => 6
    );
    
    public static $bidProjectName = '小区专家';
    
    private $broker;
    /**
     *
     * @var GrowthBid 
     */
    private $growthBid;
    /**
     *
     * @var GrowthBidRecordOn 
     */
    private $growthBidRecord;
    /**
     *
     * @var GrowthBidRecordHistory 
     */
    private $growthBidRecordHistory;
    
    /**
     *
     * @var GrowthBrokerCredit 
     */
    private $growthBrokerCredit;
    
    /**
     *
     * @var Adodb 
     */
    private $dbback;
    
    private $brokerBlock;
    /**
     *
     * @var 竞投 
     */
    private $blockExpertBidsNew;
    /**
     *
     * @var array 
     */
    private $bidError;
    
    private $growthBidPeriods;


    /**
     * 
     * @param array $broker array("id"=>'','agentcode'=>'','agentname'=>'','level'=>'','is_pay'=>'')
     */
    public function __construct($broker,$growthBrokerCredit) {
        $this->dbback = Container::getInstance()->get('dbback');
        $this->broker= $broker;
        $this->growthBid = new GrowthBidBlockExpert();
        $this->growthBidRecord = new GrowthBidBlockExpertRecordOn();
        $this->growthBidRecordHistory = new GrowthBidBlockExpertRecordHistory();
        $this->growthBrokerCredit = $growthBrokerCredit;
        $this->growthBidPeriods = new GrowthBidPeriods();
    }
    
    public function bid($bidId,$score) {
        //var_dump($this->controlTime());exit;
        if($this->controlTime()==false) {
            $this->bidError['errorCode'] = self::BID_ERROR_MIN_TIME;
            return false;
        }
        $brokerId = $this->broker['id'];
        $bid = $this->growthBid->findById($bidId);
        if(!$bid) {
            return false;
        }
        $bidPeriodsId = $bid['bid_periods_id'];
        $blockId = $bid['block_id'];
        $blockMg = new Block();
        $block = $blockMg->findOneBy($blockId);//小区
        //我的竞投记录
        $myRecord = $this->growthBidRecord->findOneBy($brokerId, $bidId);
        //本竞投的记录
        $winnerRecord = $this->findTempWinnerRecord($bidId);
        $x = $this->checkByRecord($bid,$score,$winnerRecord,$myRecord);
        if($x) {
            //可以竞投
            //判断当前是哪种竞投状态，-1，未投过；0，未投中；1，2，3，4投中了当前是在追加
            $winFlag = $this->checkWinBid($winnerRecord, $myRecord);
            switch ($winFlag) {
                case '-1'://未投过
                    //首次--》添加竞投记录，statua=1；参加竞投人数number=number+1；冻结积分score；
                    $fieldData = array('broker_id'=>$brokerId,
                        'bid_id'=>$bidId,
                        'score'=>$score,
                        'block_id'=>$blockId,
                        'block_name'=>$block['blockname'],
                        'bid_periods_id'=>$bidPeriodsId);
                    $recordId = $this->growthBidRecord->insert($fieldData);
                    
                    if($recordId) {
                        //增加人数
                        $this->growthBid->addJoinNumber($bidId);
                        //冻结积分
                        $this->growthBrokerCredit->frozenCredit($score);
                        //退分
                        $this->complete($bidId);
                        //统计有多少人在使用
                        $growthBidUserBroker = new GrowthBidUserBroker();
                        $growthBidUserBroker->addJoinBidBlockExpertRecord($brokerId);
                        
                        //同时关注
                        if(!$this->hasAttention($bidId)) {//如果没关注
                            $attentionNumber = GrowthBidAttentionHelper::totalNumber($this->broker);
                            if($attentionNumber<GrowthBidAttentionHelper::ATTENTION_MAX_NUMBER) {
                                $this->attent($bidId,$bidPeriodsId);
                            }
                        }
                        
                    } else {
                        $this->bidError['errorCode'] = self::BID_ERROR_SYS_DB;
                        //记录错误日志
                    }
                    break;
                case '0'://已投过，未投中
                    $fieldData = array('score'=>$score,'status'=>'1');
                    $conf = "broker_id='$brokerId' and bid_id='$bidId'";
                    $affectRows = $this->growthBidRecord->update($fieldData, $conf);
                    if($affectRows) {
                        $this->growthBrokerCredit->frozenCredit($score);
                        //处理其他被超过积分，挤出排名的经纪人，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 = "broker_id='$brokerId' and bid_id='$bidId'";
                    $affectRows = $this->growthBidRecord->add($fieldData, $conf);
                    if($affectRows) {
                        $this->growthBrokerCredit->frozenCredit($score);
                    } else {
                        
                    }
                    break;
                default:
                    break;
            }
            //如果存在就更新，不存在就插入(本竞投中是首次投分，还是后续加分)X
            
            
            //后续加分--》更新记录，status=1；冻结积分score；X
            
            //积分记录？
            return true;
        } else {
            return false;
        }
    }
    
    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']);
                }
            }
            
        }
        
    }

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

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

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


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

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

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

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

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

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

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

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

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

        $attentionBidList = array();

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

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

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

        if($template) {
            $html = sprintf($template,$no,$rank02,$score);
        } else {
            $html = '<div class="fraction_rank radius3" style="margin: 5px;"><span class="rank '.$rank02.'">NO.'.$no.'</span><span class="fraction">'.$score.'</span></div>';
        }
        return $html;
    }
    /**
     * 竞投结束排名显示风格
     * @param type $k
     * @param type $r
     * @param type $myrecord
     * @param type $template
     * @return string
     */
    private function renderRankNoScore($k,$r,$myrecord=null,$template=null) {
        $no = $k+1;
        //$rank02 = $no>2?'rank02':'';
        $score = $r['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 radius3"  style="margin: 5px;"><span class="rank '.$rank02.'">NO.'.$no.'</span><span class="fraction"><strong class="num">'.$score.'</strong>分</span></div>';
        }
        return $html;
    }
    /**
     * 检查查看权限
     * @param int $bid
     */
    public function checkViewAuth($cBidPeriodsId,$bid) {
        $blockId = $bid['block_id'];
        $blocks = $this->get_valid_bid_block($cBidPeriodsId,array(), '');
        $blocks = SqlCombinHelper::changeToKeyArray($blocks, "id");
        if(in_array($blockId, array_keys($blocks))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 返回所有可以参与竞投的小区id数组
     * @param type $cBidPeriodsId
     */
    public function get_valid_bid_block_id($cBidPeriodsId) {
        $blockids = $this->findAllBlockHouserNumber(GrowthBrokerBidBlockExpert::HOUSE_NUMBER_LIMIT);
        //过滤，有竞投活动，且经纪人等级满足
        //小区竞投
        $growthBidBlockExpert = new GrowthBidBlockExpert();
        $blockExpertBids = $growthBidBlockExpert->findBy("block_id in ('".implode("','", $blockids)."') and bid_periods_id='$cBidPeriodsId'");
        $blockExpertBidsNew = SqlCombinHelper::changeToKeyArray($blockExpertBids, 'block_id');
        $this->blockExpertBidsNew = $blockExpertBidsNew;
        $blockids = array();
        //print_r($blockExpertBidsNew);
        foreach ($blockExpertBidsNew as $value) {
            if($this->checkBrokerLevel($value['broker_level'])) {
                $blockids[] = $value['block_id'];
            }
        }
        return $blockids;
    }
    /**
     * 可以的小区专家竞投小区
     * @param type $growthBrokerBidBlockExpert
     * @param array $myrecords 我的竞投记录
     * @param string $action 参与的还是所有的标记
     * @return array 小区数组
     */
    public function get_valid_bid_block ($cBidPeriodsId,$myrecords,$action,$blockName='') {
        $blockids = $this->findAllBlockHouserNumber(GrowthBrokerBidBlockExpert::HOUSE_NUMBER_LIMIT);
        //过滤，有竞投活动，且经纪人等级满足
        //小区竞投
        $growthBidBlockExpert = new GrowthBidBlockExpert();
        $blockExpertBids = $growthBidBlockExpert->findBy("block_id in ('".implode("','", $blockids)."') and bid_periods_id='$cBidPeriodsId'");
        $blockExpertBidsNew = SqlCombinHelper::changeToKeyArray($blockExpertBids, 'block_id');
        $this->blockExpertBidsNew = $blockExpertBidsNew;
        $blockids = array();
        //print_r($blockExpertBidsNew);
        foreach ($blockExpertBidsNew as $value) {
            if($this->checkBrokerLevel($value['broker_level'])) {
                $blockids[] = $value['block_id'];
            }
        }
        $block = new Block();
        if($blockName) {
            $blocks = $block->findAllBy("id in ('".  implode("','", $blockids)."') and blockName like '%$blockName%'");
        } else {
            $blocks = $block->findAllBy("id in ('".  implode("','", $blockids)."')");
        }
        if(!$blocks) {
            $blocks = array();
        }
        if($action=='on') {
            $blocksOn = array();//$growthBrokerBidBlockExpert->findBlockBid();
            foreach($myrecords as $mr) {
                $blocksOn[$mr['block_id']] = $mr['block_name'];
            }
            $blockIdsOn = array_keys($blocksOn);
            if($blocks) {//过滤未参与的小区
                foreach($blocks as $k=>$v) {
                    if(!in_array($v['id'],$blockIdsOn)) {
                        unset($blocks[$k]);
                    }
                }
            } 
        }
        $levels = array();//按小区等级排序
        foreach ($blocks as $key=>$v) {
            $levels[$key] = $blockExpertBidsNew[$v['id']]['block_level'];
            $blocks[$key]['block_level'] = $levels[$key];
        }
        array_multisort($levels, SORT_ASC, $blocks);
        //print_r($blocks);
        return $blocks;
    }

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

?>
