<?php

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


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

$growthBidPeriods = new GrowthBidPeriods();
$bidPeriods = $growthBidPeriods->findAll('type = 1 ORDER BY id DESC');

$settingSearch = array(0=>'请选择','block_name'=>'小区名称','block_id'=>'小区编号');
$settingOrderBy = array('number'=>'参与人数','block_id'=>'小区编号');
$settingAscDesc = array('desc'=>'倒序排列','asc'=>'正序排列',);
$settingDispRows = array(20=>'20',30=>'30',40=>'40');
$conf = array();
    
//查询条件，关键字
if($search_type&&$keyword) {
    $block = new Block();
    if ($search_type == 'block_name') {
        $conf['block_id'] = $block->findAllIdByLikeName($keyword);;
    } else {
        $conf[$search_type] = $keyword;
    }
}

//推广时间条件
if($tg_time) {
    $conf['bid_periods_id'] = $tg_time;
    //实际有多少人参与
    $sqlNumber = "SELECT broker_id FROM growth_bid_block_expert_record_history WHERE bid_periods_id= '".$conf['bid_periods_id']."' group by broker_id";
    $bidNumber = $dbback->getAll($sqlNumber);
    $bidNumber = count($bidNumber);
    //实际有多少成功参与
    $sqlSuccessNumber = "SELECT broker_id FROM growth_bid_block_expert_record_history WHERE bid_periods_id= '".$conf['bid_periods_id']."' 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($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";
}
$growthBid = new GrowthBidBlockExpert();
$bids = $growthBid->findBy($confx, $orderBy, $limit);
$block = new Block();
//$growthBidRecord = new GrowthBidBlockExpertRecordOn();
if(!$bids) {$bids = array();}
changeToBidManage(&$bids,$block,$bidPeriods);

//查所有经纪人
$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');

//获取某个时间内所有二手房源的点击量
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);
}
if ($action == 'downloadAccount') {
    require_once CORE_LIB.'/CommonStatisticDownloader.php';
    //合并竞投成功的房源编号为数组
    $houseDetails = array();
    if ($bids) {
        $houseClick = array();
        foreach($bids as $v) {
            if (is_array($v['detail'])) {
                $houseDetails = array_merge($houseDetails, $v['detail']);
            }
        }
        $houseClick = array();
        $brokerId = array();
        foreach($houseDetails as $v) {
            if (!in_array($v['broker_id'], $brokerId)) {
                $sql = "select sum(sell_click) from broker_stat where uid = $v[broker_id] and stattime >= '$brokerStatStartTime' and stattime <= '$brokerStatEndTime'";
                $num = $dbback->getOne($sql);
                $brokerId[] = $v['broker_id'];
                $brokerDetail = getBrokerDetail($mc, $dbback, $v['broker_id']);
                $houseClick[] = array(
                    'username' => $brokerDetail['username'],
                    'truename' => $brokerDetail['truename'],
                    'master'=>$brokerDetail['master'],
                    'companyname' => $brokerDetail['companyname'],
                    'agentname' => $brokerDetail['agentname'],
                    'block_name'=>$v['block_name'],
                    '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'=>$menuConf[$tab]['name'],'name'=>$menuConf[$tab]['name'],'field'=>'id', 
                'value'=>array()
                ),
            '2'=>array('key'=>$tgTime,'name'=>$tgTime,'field'=>'clickCount', 
                'value'=>array()
                ),
        );
        $tgTime = date('m.d', strtotime($brokerStatStartTime)) . '-' . date('m.d', strtotime($brokerStatEndTime));
        $allColumns = array(
            '1'=>array('key'=>'经纪人帐号','name'=>'经纪人帐号','field'=>'username', 
                'value'=>array()
                ),
            '2'=>array('key'=>'经纪人姓名','name'=>'经纪人姓名','field'=>'truename', 
                'value'=>array()
                ),
            '3'=>array('key'=>'公司名称','name'=>'公司名称','field'=>'companyname', 
                'value'=>array()
                ),
            '4'=>array('key'=>'竞投对象','name'=>'竞投对象','field'=>'block_name', 
                'value'=>array()
                ),
            '5'=>array('key'=>'客户经理','name'=>'客户经理','field'=>'master', 
                'value'=>array()
                ),
            '6'=>array('key'=>'门店名称','name'=>'门店名称','field'=>'agentname', 
                'value'=>array()
                ),
            '7'=>array('key'=>'投入房豆','name'=>'投入房豆','field'=>'score', 
                'value'=>array()
                ),
            '8'=>array('key'=>'竞投时间','name'=>'竞投时间','field'=>'utime', 
                'value'=>array()
                ),
            '9'=>array('key'=>'推广开始时间','name'=>'推广开始时间','field'=>'tg_start_time', 
                'value'=>array()
                ),
            '10'=>array('key'=>'推广结束时间','name'=>'推广结束时间','field'=>'tg_end_time', 
                'value'=>array()
                ),
            '11'=>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'=>'block_name', 
            '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'=>'block_level', 
            'value'=>array()
            ),
        '5'=>array('key'=>'推广时间','name'=>'推广时间','field'=>'tg_time', 
            'value'=>array()
            ),
        '6'=>array('key'=>'竞投现状','name'=>'竞投现状','field'=>'status', 
            'value'=>array()
            ),
        '7'=>array('key'=>'参与人数','name'=>'参与人数','field'=>'number', 
            'value'=>array()
            ),
        '8'=>array('key'=>'竞投成功','name'=>'竞投成功','field'=>'winNumber',
            'value'=>array()
            ),
        '9'=>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'=>''),
                        '3'=>array('name'=>'NO.3','displayname'=>'NO.3','field'=>'NO.2','prefix'=>''),
                        '4'=>array('name'=>'NO.4','displayname'=>'NO.4','field'=>'NO.3','prefix'=>''))
            ),
        );


    $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;
}

$total_num = $growthBid->findNumberBy($confx);
$page_total = ceil($total_num/$disp_rows);
$new_pagenavi = new_pagenavi2($page_now,$page_total,$total_num);

/**
 * 把数据转换成页面使用的格式
 * @param type $bids
 * @param type $block
 * @param type $bidPeriods
 */
function changeToBidManage(&$bids,$block,$bidPeriods) {
    foreach ($bids as &$value) {
        //小区名
        $bid = $value['id'];
        $blockInfo = $block->findOneBy($value['block_id']);
        if($blockInfo) {
            $value['block_name'] = $blockInfo['blockname'];
        }
        //推广时间
        $vBidPeriod = $bidPeriods[$value['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('blockExpert');
            $value['detail'] = $growthBidRecord->findByBid($bid,"score desc,utime asc","0,4");
            //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('blockExpert');
            $value['detail'] = $growthBidRecord->findByBid($bid,"score desc,utime asc","0,4");
            //$bidRecords = $growthBidRecord->findByBid($bid,"score desc,utime asc","0,4");
            $value['winNumber'] = count($value['detail']);
            $value['action'] = '-';
        }
        //$nowTime = new DateTime();
        //竞投成功人数

    }
}
//获取经纪人的详细信息
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']
    );
}

/**
 * 把数据转换成适合下载的格式
 * @param type $bids
 */
function changeToDownloadStyle(&$bids, $brokers) {
    global $conf_cityflag;
    $mc = Container::getInstance()->get('mc');
    $blockIds = SqlCombinHelper::getColumnDataByKey($bids, 'block_id');
    //print_r($blockIds);
    $memKey = array($conf_cityflag,'block',$blockIds);
    $blockInfos = $mc->get($memKey);
    if($blockInfos === false) {
        $sql = "select id,district,streetid from block where "."id in ('".  implode("','", $blockIds)."') ";
        $dbback = Container::getInstance()->get('dbback');
        $blockInfos = $dbback->getAll($sql);
        $blockInfos = SqlCombinHelper::changeToKeyArray($blockInfos, 'id');
        $mc->set($memKey,$blockInfos,3600);
    }
    $streetIds = SqlCombinHelper::getColumnDataByKey($blockInfos, 'streetid');
    $streetMemKey = array($conf_cityflag,'street',$streetIds);
    $streetInfos = $mc->get($streetMemKey);
    if($streetInfos === false) {
        $sql = "select id,streetname from street where "."id in ('".  implode("','", $streetIds)."') ";
        $dbback = Container::getInstance()->get('dbback');
        $streetInfos = $dbback->getAll($sql);
        $streetInfos = SqlCombinHelper::changeToKeyArray($streetInfos, 'id');
        $mc->set($streetMemKey,$streetInfos,3600);
    }
    //$block = new Block();
    //$blockInfos = $block->findAllBy("id in ('".  implode("','", $blockIds)."')");
    //print_r($blockInfos);
    foreach ($bids as &$value) {
        $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'];
        }
        }
        $value['block_district'] = $blockInfos[$value['block_id']]['district'];
        $value['block_street'] = $streetInfos[$blockInfos[$value['block_id']]['streetid']]['streetname'];
    }
}
include_once(Template("header"));
include_once(Template("growth_nj/bid_manage_block_expert"));
include_once(Template("footer"));
?>
