<?php

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

/**
 * 竞投小助手
 *
 * @author Administrator
 */
class GrowthBidAttentionHelper {
    const ATTENTION_MAX_NUMBER = 10;
    private $broker;
    private $growthBidAttention;
    private $growthBidRecord;
    private $growthBidRecordHistory;
    private $growthBid;
    
    public function __construct($broker) {
        $this->broker = $broker;
        $this->growthBidRecord = new GrowthBidBlockExpertRecordOn();
        $this->growthBidRecordHistory = new GrowthBidBlockExpertRecordHistory();
        $this->growthBid = new GrowthBidBlockExpert();
        $this->growthBidAttention = new GrowthBidAttention();
    }
    
    /**
     * 查找关注的小区的列表
     * @return type
     */
    public function getAttentionBlocks() {
        $brokerId = $this->broker['id'];
        //关注的小区id
        $type = 1;
        $conf = "broker_id = '$brokerId' and type='$type'";
        $bidFollow = $this->growthBidFollow->findBy($conf);
        $blocks = array();
        if($bidFollow) {
            $block = new Block();
            foreach ($bidFollow as $value) {
                //$blockIds[] = $value['target_id'];
                $blocks[$value['target_id']] = $block->findOneBy($value['target_id']);
                $blocks[$value['target_id']]['follow_id'] = $value['id'];
            }
            return $blocks;
        }
        return $blocks;
    }
    public function findAttention() {
        $brokerId = $this->broker['id'];
        $growthAttention = new GrowthBidAttention();
        return $growthAttention->findBy("broker_id='$brokerId'");
    }
    
    public function getAttentionList($bidPeriodsId = null) {
        //关注的竞投对象，此处为小区，包含id，小区名
        //$cBidp = $this->currentBidPeriods();
        //print_r($cBidp);
        if(!$bidPeriodsId) return false;
        $broker_id = $this->broker['id'];
        $conf = "broker_id='$broker_id' and bid_periods_id='$bidPeriodsId'";
        $attentionList = $this->growthBidAttention->findBy($conf);
        //print_r($attentionList);
        //$bidp = $this->currentBidPeriods();
        if($attentionList) {
            $bidIds = array();//关注的竞投id
            foreach ($attentionList as $v) {
                $bidIds[] = $v['target_id'];
            }
            //查竞投
            $bidList = array();
            if($bidIds) {
                $conf = "id in ('".  implode("','", $bidIds)."')";
                $bidList = $this->growthBid->findBy($conf);
                $bidList = SqlCombinHelper::changeToKeyArray($bidList, 'id');
            }
            //查竞投记录1，我的，2，统计最大最小值
            $dbback = Container::getInstance()->get('dbback');
            $type = 1;
            if($type==1) {
                $recordTable =$this->growthBidRecord->getTable();
            } 
            if($type==2) {
                $recordTable =$this->growthBidRecordHistory->getTable();
            }
            $mybconf = "broker_id='$broker_id' and bid_id in ('".implode("','", $bidIds)."')";
            $recordListMy = $this->growthBidRecord->findBy($mybconf);
            $recordListMy = SqlCombinHelper::changeToKeyArray($recordListMy, 'bid_id');
            
            //统计
            $sql = "select bid_id, max(score) as max,min(score) as min from $recordTable where bid_id in ('".implode("','", $bidIds)."') group by bid_id";
            $recordList = $dbback->getAll($sql);
            $recordList = SqlCombinHelper::changeToKeyArray($recordList, 'bid_id');
            //$this->getBidInfo($bidid);
            //查小区
            $blockIds = array();
            foreach($bidList as $b) {
                $blockIds[] = $b['block_id'];
            }
            $block = new Block();
            $bconf = "id in ('".  implode("','", $blockIds)."')";
            $blocks = $block->findAllBy($bconf);
            $blocks = SqlCombinHelper::changeToKeyArray($blocks, 'id');
            //print_r($blocks);
            foreach($attentionList as &$v) {
                $bidId = $v['target_id'];
                $v['bid'] = $bidList[$bidId];
                $blockId = $v['bid']['block_id'];
                if(key_exists($blockId, $blocks)) {
                    $b = $blocks[$blockId];
                    $v['target'] = '【小区专家】'.$b['blockname'];
                }
                
                if(key_exists($bidId, $recordList)) {//有人竞投
                    $v['record'] = $recordList[$bidId];
                    $v['max'] = $v['record']['max'];
                    $v['min'] = $v['record']['min'];
                } else {//没有人参加竞投
                    $v['max'] = "— —";
                    $v['min'] = "— —";
                }
                if(key_exists($bidId, $recordListMy)) {//本人参加了竞投
                    $v['myrecord'] = $recordListMy[$bidId];
                    $myrecordId = $v['myrecord']['id'];
                    $v['myscore'] = $v['myrecord']['score'];
                    $v['rank'] = $this->growthBidRecord->findRankBy($v['myscore'], $myrecordId, $bidId);
                    if($v['rank']>=4) {
                        $v['status_description'] = '暂未投中';
                    } else {
                        $v['status_description'] = '暂投中第'.$v['rank'].'位';
                    }
                } else {//本人没参加竞投
                    $v['myscore'] = "— —";
                    $v['status_description'] = '暂未投放';
                }
                
                $v['url'] = $this->bidUrl($bidId);
            }
        } else {
            $attentionList = array();
        }
        //print_r($attentionList);
        return $attentionList;
    }

    /**
     * 
     * @param int $bidid
     * @param int $type 1,表示当前表，2，表示历史表
     * @return array
     */
    public function getBidInfo($bidid,$type=1) {
        $dbback = Container::getInstance()->get('dbback');
        $brokerId = $this->broker['id'];
        if($type==1) {
            $recordTable =$this->growthBidRecord->getTable();
        } 
        if($type==2) {
            $recordTable =$this->growthBidRecordHistory->getTable();
        }
        $temp = array();
        
        $x = $dbback->getRow("select max(score) as max,min(score) as min from $recordTable where bid_id=$bidid");
        //var_dump($x);
        if($x) {
            $temp = array_merge($temp, $x);
        }
        //echo "select score,status  from $recordTable where broker_id = $brokerId and bid_id=$bidid";exit;
        $x1 = $dbback->getRow("select score,status  from $recordTable where broker_id = $brokerId and bid_id=$bidid");
        //var_dump($x1);
        if($x1) {
            $temp['myscore'] = $x1['score']?$x1['score']:'';
            $temp['mystatus'] = $x1['status'];//1,成功，-1，失败
            $temp['mystatus_str'] = $x1['status']==1?'成功':'失败';
        } else {
            $temp['myscore'] = '';
            $temp['mystatus'] = 0;//1,成功，-1，失败,0,未参加
            $temp['mystatus_str'] = '';
        }
        return $temp;
    }

    /**
     * 已废弃，请调用GrowthBidPeriods 类中的同名方法
     */
    public function currentBidPeriods($type=1) {
        //最新一期的id
        $growBidPeriods = new GrowthBidPeriods();
        $confgbp = "type='$type'";
        $order = "ctime desc";
        $limit = "0,1";
        $bidp = $growBidPeriods->findBy($confgbp, $order, $limit);
        if($bidp) {
            $bidp= $bidp[0];
        }
        $bidpid = $bidp['id'];
        //判断本期的状态
        $time = time();
        $start_time = strtotime($bidp['start_time']);
        $end_time = strtotime($bidp['end_time']);
        if($time>=$start_time&&$time<$end_time) {//进行中
            $bidp['status'] = '1';
        } else if($time<$start_time){
            $bidp['status'] = '2';//未开始
        } elseif($time>=$end_time) {
            $bidp['status'] = '3';//竞投结束
        }
        //print_r($bidp);exit;
        return $bidp;
    }
    
    
   /**
     * 关注竞投
     * @param int $type 关注的对象的类型，1，小区，。。。。。
     * @param int $targetId 关注的对象的id
     * @return mixed 成功返回true，失败返回false,超过关注数量返回-1
     */
    public function attent($targetId,$type=1) {
        //
        $brokerId = $this->broker['id'];
        $growthBidFollow = new GrowthBidFollow();
        $conf = "broker_id = '$brokerId' and target_id='$targetId' and type='$type'";
        $bidFollow = $growthBidFollow->findBy($conf);
        if($this->checkAttention()>=10) {
            return -1;
        }
        if($bidFollow) {

        } else {
            $fieldData = array('broker_id'=>$brokerId,'type'=>'1','target_id'=>$targetId,);
            if($growthBidFollow->insert($fieldData)) {
                return true;
            } else {
                return false;
            }
        }
    }
    
    /**
     * 取消已经关注的竞投
     * @param int $type 关注的对象的类型，1，小区，。。。。。
     * @param int $targetId 关注的对象的id
     * @return boolean 成功返回true，失败返回false
     */
    public function cancelAttention($targetId,$type=1) {
        $brokerId = $this->broker['id'];
        $growthBidFollow = new GrowthBidFollow();
        $conf = "broker_id = '$brokerId' and target_id='$targetId' and type='$type'";
        $fieldData = array('del'=>'1');
        if($growthBidFollow->update($fieldData, $conf)) {
            return true;;
        } else {
            return false;
        }
    }
    
    /**
     * 返回已关注的数量
     * @return int 已关注的数量
     */
    public function checkAttention($bidPeriodsId) {
        if(!$bidPeriodsId) return false;
        $brokerId = $this->broker['id'];
        $growthBidAttention = new GrowthBidAttention();
        $conf = "broker_id = '$brokerId' and bid_periods_id='$bidPeriodsId'";
        return $bidFollowNumber = $growthBidAttention->findNumberBy($conf);
    }
    
    public static function bidUrl($bidId,$type=1) {
        return "./market_bid_block_expert.php#bid$bidId";
    }
    
    public static function bidHouseUrl($type,$houseId) {
        return "./market_bid_house.php?type=$type&houseid=$houseId";
    }
    /**
     * 
     * @param type $winFlag
     * @return string
     */
    public static function getStatusDescription($bidStatus,$winFlag,$host='') {
        $d = '';
        if($bidStatus==3) {
            if($winFlag==-1) {
                $d = '未参与';
            } elseif($winFlag==0) {
                $d = '<img class="img" src="'.$host.'/zsb/images/v1.0/shibai_pop.gif" alt="" style="margin-top:12px;">';
            } else {
                $d = '<img class="img" alt="" src="'.$host.'/zsb/images/v1.0/chenggong_pop.gif" style="margin-top:12px;">';
            }
        } else {
            if($winFlag==-1) {
                $d = '暂未投放';
            } elseif($winFlag==0) {
                $d = '暂未投中';
            } else {
                $d = '暂投中第'.$winFlag.'位';
            }
        }
        
        return $d;
    }
    
    public static function MaxScore($records) {
        if($records) {
            $count = count($records);
            $max = $records[0]['score'];
            $min = $records[$count-1]['score'];
        } else {
            $max = '— —';
            $min = '— —';
        }
        return $max;
    }
    public static function MinScore($records) {
        if($records) {
            $count = count($records);
            if($count==1) {
                $max = '— —';//$records[0]['score'];
                $min = $records[0]['score'];//'— —';
            } else {
                $max = $records[0]['score'];
                $min = $records[$count-1]['score'];
            }
            
        } else {
            $max = '— —';
            $min = '— —';
        }
        return $min;
    }
    
    
    public static function totalNumber($broker) {
        $growthBidPeriods = new GrowthBidPeriods();
        $cBidPeriodsB = $growthBidPeriods->currentBidPeriods(1);
        $cBidPeriodsH = $growthBidPeriods->currentBidPeriods(2);
        if (!$cBidPeriodsB || !$cBidPeriodsH) {
            //return false;
        }
        $isBidDay = false;
        $growthBidHelper = new GrowthBidAttentionHelper($broker);
        //小区专家关注数量
        $attentionNumberB = 0;
        if($cBidPeriodsB) {
            $bidPeriodsIdB = $cBidPeriodsB['id'];
            $bidPeriodsStatusB = $cBidPeriodsB['status'];
            if($bidPeriodsStatusB == GrowthBidPeriods::BID_PERIODS_STATUS_ON||
                $bidPeriodsStatusB == GrowthBidPeriods::BID_PERIODS_STATUS_FINISH) {
            if (substr($cBidPeriodsB['start_time'], 0, 10) == date('Y-m-d')) {
            $attentionNumberB = $growthBidHelper->checkAttention($bidPeriodsIdB);
            $isBidDay = true;
            }
            }
        } 
        //房源竞投关注数量
        $attentionNumberH = 0;
        if($cBidPeriodsH) {
            $bidPeriodsIdH = $cBidPeriodsH['id'];
            $bidPeriodsStatusH = $cBidPeriodsH['status'];
            if($bidPeriodsStatusH == GrowthBidPeriods::BID_PERIODS_STATUS_ON||
                    $bidPeriodsStatusH == GrowthBidPeriods::BID_PERIODS_STATUS_FINISH) {
                if (substr($cBidPeriodsH['start_time'], 0, 10) == date('Y-m-d')) {
                $attentionNumberH = $growthBidHelper->checkAttention($bidPeriodsIdH);
                $isBidDay = true;
            }
            }
        }
        $attentionNumber = $attentionNumberB + $attentionNumberH;
        return $attentionNumber;
    }
}

?>
