<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$conf_basedir	= "../../";	//相对主目录的位置
$conf_where		= "admin";	//选择调用相应模块
$directory		= basename(dirname(__FILE__));	//定义当前所在的目录，引入模块公用函数
$conf_server = 'statistics';
include_once($conf_basedir."base.inc.php");
checkAuth('88');	//判断登录和权限
$title = "房源竞投管理";
//房源竞投
$tab = $tab == '' ? 'blockwords' : $tab;

$menuConf = array(
    'blockwords' => array('name' => '小区词竞投', 'type' => 1),
    'hotsearchwords' => array('name' => '热搜词竞投', 'type' => 2), 
    /**'streetwords' => array('name' => '板块词竞投', 'type' => 3), **/
);
if ($tab == 'blockwords') {
    $block = new Block();
} else if ($tab == 'streetwords') {
    $street = new Street();
}
$type = $menuConf[$tab]['type'];
$growthBid = new GrowthBidHouse();
$growthBidPeriods = new GrowthBidPeriods();
$bidPeriods = $growthBidPeriods->findAll("type = 2 ORDER BY id DESC");
if ($tab == 'blockwords') {
   $settingSearch = array(0=>'请选择','keyword'=>'小区词'); 
} else {
   $settingSearch = array(0=>'请选择','keyword'=>'营销词');
}
$settingOrderBy = array('number'=>'参与人数');
$settingAscDesc = array('desc'=>'倒序排列','asc'=>'正序排列',);
$settingDispRows = array(20=>'20',30=>'30',40=>'40');
$conf = array();
$conf['type'] = $menuConf[$tab]['type'];
//查询条件，关键字
if($search_type&&$keyword) {
    if ($type == 2) {
         $conf[$search_type] = $keyword;
    } else if ($type == 3) {
        $conf['street_id'] = $street->findAllIdByLikeName($keyword);
    } else if ($type == 1) {
        $conf['block_id'] = $block->findAllIdByLikeName($keyword);
    }
}

//推广时间条件
if($tg_time) {
    $conf['bid_periods_id'] = $tg_time;
    //实际有多少人参与
    $sqlNumber = "SELECT broker_id FROM growth_bid_house_record_history WHERE bid_periods_id= '".$conf['bid_periods_id']."' and type= '".$conf['type']."' group by broker_id";
    $bidNumber = $dbback->getAll($sqlNumber);
    $bidNumber = count($bidNumber);
    $sqlSuccessNumber = "SELECT broker_id FROM growth_bid_house_record_history WHERE bid_periods_id= '".$conf['bid_periods_id']."' and type= '".$conf['type']."' and status=1 group by broker_id";
    $bidSuccessNumber = $dbback->getAll($sqlSuccessNumber);
    $bidSuccessNumber = count($bidSuccessNumber);
    
} else {
    $tg_timeArr = array();
    if($bidPeriods) {
        foreach ($bidPeriods as $value) {
            $tg_timeArr[] = $value['id'];
        }
    }
    $conf['bid_periods_id'] = $tg_timeArr;
}

$confx = array();
foreach ($conf as $key => $value) {
    if(is_array($value)) {
        $confx[]= "$key in ('".  implode("','", $value)."')";
    }
    if(is_string($value)) {
        $confx[]= "$key = '$value'";
    } 
    if (is_int($value)) {
        $confx[]= "$key = $value";
    }
    
}
if($confx) {
    $confx = implode(" and ", $confx);
}

if($action == 'download') {//如果是下载，只下载有人参加的竞投
    $confx .= ' and number>0 ';
}

//排序
$orderby = $orderby?$orderby:'number';
$asc_desc = $asc_desc?$asc_desc:'desc';
$orderBy = array($orderby=>$asc_desc);//"ORDER BY ".$orderby." ".$asc_desc;

//条数
$page_now = intval($page_now)==0?1:intval($page_now);
$disp_rows = intval($disp_rows)==0?20:intval($disp_rows);
$startRow = ($page_now-1)*$disp_rows;
if($action != 'download' && $action != 'downloadAccount') {
$limit = "limit $startRow, $disp_rows";
}

$bids = $growthBid->findBy($confx, $orderBy, $limit);
if(!$bids) {$bids = array();}
foreach ($bids as $key => &$value) {
    $bid = $bids[$key]['id'];
    switch($tab) {
        case 'hotsearchwords':
            $bids[$key]['name'] = $bids[$key]['keyword'];
            break;
        case 'streetwords':
            $streetInfo = $street->findOneBy($bids[$key]['street_id']);
            if($streetInfo) {
                $bids[$key]['name'] = $streetInfo['streetname'];
            }
            break;
        case 'blockwords':
            $blockInfo = $block->findOneBy($bids[$key]['block_id']);
            if($blockInfo) {
                $bids[$key]['name'] = $blockInfo['blockname'];
                //区属，板块
                $bids[$key]['block_district'] = $blockInfo['district'];
                $sql = "select streetname from street where id = '".$blockInfo['streetid']."'";
                $dbback = Container::getInstance()->get('dbback');
                $streetInfos = $dbback->getOne($sql);
                $bids[$key]['block_street'] = $streetInfos;
            }
            break;
        default:
    }
    //推广时间
    $vBidPeriod = $bidPeriods[$bids[$key]['bid_periods_id']];
    $value['tg_time'] = GrowthBidPeriods::formatTime($vBidPeriod['tg_start_time'],$vBidPeriod['tg_end_time']);
    //竞投现状/竞投成功人数
    $time = time();
    if($time>=strtotime($vBidPeriod['start_time'])&&$time<strtotime($vBidPeriod['end_time'])) {
        $value['status'] = "竞投中";
        $value['countDown'] = "剩余<span class='time' id='time{$bid}'>".date("m d,Y H:i:s",  strtotime($vBidPeriod['end_time']))."</span>";//03 07, 2014 16:00:00
        //查询竞投详情,去前4
        $growthBidRecord = GrowthBidRecordFactory::getRecordOnClass('house');
        $value['detail'] = $growthBidRecord->findByBid($bid,"score desc,utime asc","0,2");
        //print_r($value['detail']);exit;
        $value['winNumber'] = count($value['detail']);
        $value['action'] = 'stop';
        
    } elseif($time<strtotime($vBidPeriod['start_time'])) {
        $value['status'] = "未开始";
        $value['countDown'] = "离下期还有<span class='time' id='time{$bid}'>".date("m d,Y H:i:s",  strtotime($vBidPeriod['start_time']))."</span>";//03 07, 2014 16:00:00
        $value['winNumber'] = "-";
        $value['detail'] = "-";
        $value['action'] = 'stop';
    } else {
        $value['status'] = "已结束";
        $value['countDown'] = "";
        //
        $growthBidRecord = GrowthBidRecordFactory::getRecordHistoryClass('house');
        $value['detail'] = $growthBidRecord->findByBid($bid,"score desc,utime asc","0,2");
        /*$sqlNumber = "SELECT COUNT(*) as number FROM (
        SELECT * FROM growth_bid_house_record_history  WHERE bid_id='$bid' GROUP BY broker_id
        ) as a";
        $value['unique_number'] = $dbback->getOne($sqlNumber);
         * 
         */
        //$value['number'] = $growthBidRecord->findNumberBy("bid_id='$bid'");
        //$bidRecords = $growthBidRecord->findByBid($bid,"score desc,utime asc","0,4");
        $value['winNumber'] = count($value['detail']);
        $value['action'] = '-';
    }
}

//获取某个时间内所有二手房源的点击量
if ($tg_time) {
    $cPeriods = $bidPeriods[$tg_time];
    $tgStartTime = $cPeriods['tg_start_time'];
    $tgEndTime = $cPeriods['tg_end_time'];
    //查询此间断所有房源的点击量
    $brokerStatStartTime = date('Y-m-d', strtotime($tgStartTime));
    $brokerStatEndTime = date('Y-m-d', strtotime($tgEndTime));
    $sql = "select sum(sell_click) from broker_stat where stattime >= '$brokerStatStartTime' and stattime <= '$brokerStatEndTime'";
    $sumSellClick = $dbback->getOne($sql);
}

//查所有经纪人
$brokerIds = array();
foreach ($bids as $value) {
    if(isset($value['detail'])&&  is_array($value['detail'])) {
        foreach ($value['detail'] as $v) {
            $brokerIds[] = $v['broker_id'];
        }
    }
}
//去重
$brokerIds = array_unique($brokerIds);
$brokers = array();
$brokerSql = "select uid,username,truename from broker where uid in ('".  implode("','", $brokerIds)."')";
$brokers = $dbback->getAll($brokerSql);
$brokers = SqlCombinHelper::changeToKeyArray($brokers, 'uid');
//print_r($bids);
if ($action == 'downloadAccount') {
    //print_r($bids);
    //die();
    require_once CORE_LIB.'/CommonStatisticDownloader.php';
    //合并竞投成功的房源编号为数组
    $houseDetails = array();
    if ($bids) {
        $houseClick = array();
        $bidNameArray = array();//
        foreach($bids as $v) {
            if (is_array($v['detail'])) {
                $houseDetails = array_merge($houseDetails, $v['detail']);
                $bidNameArray[$v['id']] = $v['name'];
            }    
        }
        $diff_count = (strtotime($brokerStatEndTime) - strtotime($brokerStatStartTime)) / 86400 ;
        $i = 0;
        do {
            $countday_arr[$i] = date('Ymd',strtotime($brokerStatStartTime) + (86400 * $i) );
            ++ $i;
            -- $diff_count;
        }while($diff_count >= 0);
        $houseClick = array();
        $houseId = array();
        foreach($houseDetails as $v) {
            $num = 0;
            if (!in_array($v['house_id'], $houseId)) {
                foreach($countday_arr as $d) {
                   $num += $statistics->get_fidclickcount($d,$v['house_id'],'sell');
                }
                $brokerDetail = getBrokerDetail($mc, $dbback, $v['broker_id']);
                $houseId[] = $v['house_id'];
                $houseClick[] = array(
                    'id' => $v['house_id'], 
                    'username' => $brokerDetail['username'],
                    'truename' => $brokerDetail['truename'],
                    'master'=>$brokerDetail['master'],
                    'companyname' => $brokerDetail['companyname'],
                    'agentname' => $brokerDetail['agentname'],
                    'bid_type'=>$menuConf[$tab]['name'],
                    'bid_name'=>$bidNameArray[$v['bid_id']],//小区词或营销词
                    'score' => $v['score'],
                    'utime' => $v['utime'],
                    'tg_start_time' => $tgStartTime,
                    'tg_end_time' => $tgEndTime,
                    'clickCount' => $num
                );
            }
        }
        $tgTime = date('m.d', strtotime($brokerStatStartTime)) . '-' . date('m.d', strtotime($brokerStatEndTime));
        $allColumns = array(
            '1'=>array('key'=>'房源ID','name'=>'房源ID','field'=>'id', 
                'value'=>array()
                ),
            '2'=>array('key'=>'经纪人帐号','name'=>'经纪人帐号','field'=>'username', 
                'value'=>array()
                ),
            '3'=>array('key'=>'经纪人姓名','name'=>'经纪人姓名','field'=>'truename', 
                'value'=>array()
                ),
            '4'=>array('key'=>'竞投词','name'=>'竞投词','field'=>'bid_name', 
                'value'=>array()
                ),
            '5'=>array('key'=>'客户经理','name'=>'客户经理','field'=>'master', 
                'value'=>array()
                ),
            '6'=>array('key'=>'公司名称','name'=>'公司名称','field'=>'companyname', 
                'value'=>array()
                ),
            '7'=>array('key'=>'门店名称','name'=>'门店名称','field'=>'agentname', 
                'value'=>array()
                ),
            '8'=>array('key'=>'投入房豆','name'=>'投入房豆','field'=>'score', 
                'value'=>array()
                ),
            '9'=>array('key'=>'竞投时间','name'=>'竞投时间','field'=>'utime', 
                'value'=>array()
                ),
            '10'=>array('key'=>'推广开始时间','name'=>'推广开始时间','field'=>'tg_start_time', 
                'value'=>array()
                ),
            '11'=>array('key'=>'推广结束时间','name'=>'推广结束时间','field'=>'tg_end_time', 
                'value'=>array()
                ),
            '12'=>array('key'=>'房源点击量','name'=>'房源点击量','field'=>'clickCount', 
                'value'=>array()
                ),
        );
        $dataDownloadColumn = new DataDownloadColumn();
        $dataDownloadColumn->setAllColumns($allColumns);

        $downloader = new AgencyStatisticDownloader();

        $downloader->setDataDownloadColumn($dataDownloadColumn);

        $downloader->setData($houseClick);
        $downloader->setFileName('房源竞投统计数据.xls');
        $downloader->createTitle();
        $downloader->writeData();

        //开始下载

        //$downloader->setFileName($fileName);
        $downloader->output();
        exit;        
    }
} else if($action == 'download') {
    require_once CORE_LIB.'/CommonStatisticDownloader.php';
    $allColumns = array(
        '1'=>array('key'=>'关键词','name'=>'关键词','field'=>'keyword', 
            'value'=>array()
            ),
        '2'=>array('key'=>'区属','name'=>'区属','field'=>'block_district', 
            'value'=>array()
            ),
        '3'=>array('key'=>'板块','name'=>'板块','field'=>'block_street', 
            'value'=>array()
            ),
        '4'=>array('key'=>'推广时间','name'=>'推广时间','field'=>'tg_time', 
            'value'=>array()
            ),
        '5'=>array('key'=>'竞投现状','name'=>'竞投现状','field'=>'status', 
            'value'=>array()
            ),
        '6'=>array('key'=>'参与人数','name'=>'参与人数','field'=>'number', 
            'value'=>array()
            ),
        '7'=>array('key'=>'竞投成功','name'=>'竞投成功','field'=>'winNumber',
            'value'=>array()
            ),
        '8'=>array('key'=>'竞投详情',
                    'value'=>array(
                        '1'=>array('name'=>'NO.1','displayname'=>'NO.1','field'=>'NO.0','prefix'=>''),
                        '2'=>array('name'=>'NO.2','displayname'=>'NO.2','field'=>'NO.1','prefix'=>''),)
            ),
        );
    if($tab!='blockwords') {//如果是小区词,去除2列
        unset($allColumns[2]);
        unset($allColumns[3]);
    }
	
    $data = array();

    changeToDownloadStyle(&$bids, $brokers);

    $dataDownloadColumn = new DataDownloadColumn();
    $dataDownloadColumn->setAllColumns($allColumns);

    $downloader = new AgencyStatisticDownloader();

    $downloader->setDataDownloadColumn($dataDownloadColumn);

    $downloader->setData($bids);
    $downloader->setFileName('房源竞投数据.xls');
    $downloader->createTitle();
    $downloader->writeData();

    //开始下载

    //$downloader->setFileName($fileName);
    $downloader->output();
    exit;
}

/**
 * 把数据转换成适合下载的格式
 * @param type $bids
 */
function changeToDownloadStyle(&$bids, $brokers) {
    foreach ($bids as &$value) {
		if ($value['type'] == 1) {
			$value['keyword'] = $value['name'];
		}
        $detail = $value['detail'];
        //$detail = array_pad($detail, 4, array());
        if(is_array($detail)) {
        foreach ($detail as $key=>$v) {
            $broker = $brokers[$v['broker_id']];
            $value['NO.'.$key] = $broker['truename'].'('.$broker['username']."):".$v['score'];
        }
        }
    }
}

//获取经纪人的详细信息
function getBrokerDetail($mc, $dbback, $uid) {
	$sql = SqlCombinHelper::select_sql('broker', 'agentcode, master, username, truename', "uid =" . $uid);
	$brokerInfo = $mc->get($sql);
	if ($brokerInfo === false) {
		$brokerInfo = $dbback->getRow($sql);
		$mc->add($sql, $brokerInfo, 3600);
	}
	
	$sql = SqlCombinHelper::select_sql('agency', 'agentshortname, parentcode', "agentcode = '$brokerInfo[agentcode]'");
	$branchAgent = $mc->get($sql);
	if ($branchAgent === false) {
		$branchAgent = $dbback->getRow($sql);
		$mc->add($sql, $branchAgent, 3600);
	}
	$sql = SqlCombinHelper::select_sql('agency', 'agentshortname', "agentcode = '$branchAgent[parentcode]'");
	$companyName = $mc->get($sql);
	if ($companyName === false) {
		$companyName = $dbback->getOne($sql);
		$mc->add($sql, $companyName, 3600);
	}
	return array(
        'username' => $brokerInfo['username'], 'truename' => $brokerInfo['truename'],
        'companyname' => $companyName, 'agentname' => $branchAgent['agentshortname'], 
        'master' => $brokerInfo['master']
    );
}

$total_num = $growthBid->findNumberBy($confx);
$page_total = ceil($total_num/$disp_rows);
$new_pagenavi = new_pagenavi2($page_now,$page_total,$total_num);
//print_r($bids);
include_once(Template("header"));
include_once(Template("growth_nj/bid_manage_house"));
include_once(Template("footer"));
?>
