<?php
/**
 * 竞投结束后统计经纪人一周的竞投情况
 * 星期日晚上1点31钟跑上一周的数据
 * 补跑数据，需指定竞投期次和统计时间，否则数据将是错误的（切记切记）
 */
set_time_limit(0);
error_reporting(7);
ini_set("display_errors", false);

$conf_basedir = "../../../../"; //相对主目录的位置
define('WEB_ROOT', $conf_basedir);
$conf_where = "admin"; //选择调用相应模块
$directory = basename(dirname(__FILE__)); //定义当前所在的目录，引入模块公用函数
include_once(  "./base.inc.php");
require_once '../function_crontab.php';
/**
 * 一、获取最新竞投的periodsId
 * 二、根据竞投期次id统计每位经纪人的情况
   三、格式经纪人参与数组及转换数据
    array(
        array('经纪人编号' => array())
    )
    一位经纪人插入一次竞投统计数据，然后获取插入id编号
    四、一次性插入多条经纪人竞投详情
 */

//竞投类型
$arrType = array('blockExpert', 'house');
//竞投房源记录
$bidHouseRecord = array();
//竞投小区专家记录
$bidBlockExpertRecord = array();

$growthBidHouse = new GrowthBidHouse();

//根据竞投期次查询数据
$brokerBid = array();
//竞投热搜词成功次数
$hotSearchWordsSuccessNum = array();
//竞投小区词成功次数
$blockWordsSuccessNum = array();
//竞投小区专家
$blockExpertSuccessNum = array();

//竞投热搜词消耗的总分
$hotSearchWordsExpendCredit = array();
//竞投小区词消耗的总分
$blockWordsExpendCredit = array();
//竞投小区专家消耗的总分
$blockExpertExpendCredit = array();

//竞投消耗的总分
$bidExpendCredit = array();
$runCount = 0;
$allRecordCount = 0;
$tempnum = 200;
foreach($arrType as $type) {

    //实例化竞投历史类
    $growthRecordHistory = GrowthBidRecordFactory::getRecordHistoryClass($type);
    
    //获取最新一次竞投期次id
    //SELECT bid_periods_id  FROM `growth_bid_block_expert_record_history` group by bid_periods_id order by bid_periods_id  desc limit 1
    $newBidPeriods = $growthRecordHistory->findBy('1=1 group by bid_periods_id', 'bid_periods_id desc', '1');
    $pid = $newBidPeriods[0]['bid_periods_id'];

    $recordHistoryCount = $growthRecordHistory->findNumberBy("bid_periods_id='$pid' and status = 1");
    $allRecordCount += $recordHistoryCount;
	$fornum = ceil($recordHistoryCount / $tempnum);
	for($i=0; $i<$fornum; $i++) { 
        $startnum = $i * $tempnum;
        $recordHistory = $growthRecordHistory->findBy(
            "bid_periods_id='$pid' and status = 1", 'id asc', "$startnum, $tempnum");
        if($recordHistory) {
            $bidNum = count($recordHistory);
            foreach ($recordHistory as $r) {
                $runCount++;
                //记录有多少人参与竞投, 除去重复的
                if (!in_array($r['broker_id'], $brokerBid)) {
                    $brokerBid[] = $r['broker_id'];
                }   
                if ($type == 'blockExpert') {
                    $bidBlockExpertRecord[$r['broker_id']][] = array(
                        'bid_periods_id' => $r['bid_periods_id'],
                        'bid_id' => $r['bid_id'],
                        'type' => 1,
                        'keyword' => $r['block_name'],
                        'score' => $r['score'],
                    );
                    $blockExpertSuccessNum[$r['broker_id']] +=1;
                    $blockExpertExpendCredit[$r['broker_id']] += $r['score'];
                    $bidExpendCredit[$r['broker_id']] += $r['score'];
                } else {
                    //热搜词需要通过bid获取
                    if($r['type'] == 2) {
                        $keyword = $growthBidHouse->getBidHotWordsByBid($r['bid_id']);
                        $hotSearchWordsSuccessNum[$r['broker_id']] +=1;
                        $type = 3;
                        $hotSearchWordsExpendCredit[$r['broker_id']] += $r['score'];
                    } else {
                        $keyword = $r['blockname'];
                        $blockWordsSuccessNum[$r['broker_id']] +=1;
                        $type = 2;
                        $blockWordsExpendCredit[$r['broker_id']] += $r['score'];
                    }
                    $bidHouseRecord[$r['broker_id']][] = array(
                        'bid_periods_id' => $r['bid_periods_id'],
                        'bid_id' => $r['bid_id'],
                        'type' => $type,
                        'keyword' => $keyword,
                        'score' => $r['score'],
                    );
                    $bidExpendCredit[$r['broker_id']] += $r['score'];
                }
            }
        }
    }
}
//获取经纪人的登陆名和公司编号
function getBroker($brokerId) {
    global $dbback;
    $sql = 'select username, agentcode from broker where uid = ' . $brokerId;
    return $dbback->getRow($sql);
}

//设定统计时间 开始时间向前推七天，结束时间向前推一天
$nowTime = date('Y-m-d', time());
//$nowTime = '2014-07-14';
$starttime = date('Y-m-d', strtotime("-7 days", strtotime($nowTime)));
$endtime = date('Y-m-d', strtotime("-1 days", strtotime($nowTime)));

//统计数据
if ($brokerBid) {
    $growthCredit = new GrowthCredit();
    $growthExp = new GrowthExp();
    $growthLevel = new GrowthLevel();
    //200个经纪人休息一秒
    $num = 0;
    foreach($brokerBid as $brokerId) {
        /***
        $content = file_get_contents("accountBidFinish.log");
        if ($content) {
            echo 'over';
            die();
        }****/
        GrowthLog::log("开始刷{$brokerId}竞投结果数据", array());
        //查找经纪人的基本条件
        $broker = getBroker($brokerId);
        //积分
        $brokerCredit = $growthCredit->findByBrokerId($brokerId);
        $credit = $brokerCredit['credit'] == '' ? 0 :$brokerCredit['credit']-$brokerCredit['frozen'];
        //成长值
        $brokerExp = $growthExp->findOneByBrokerId($brokerId);
        $exp = $brokerExp['exp'] == '' ? 0 :$brokerExp['exp'];
        //成长值换等级
        $brokerLevel = $growthLevel->findLevelNameByExp($exp);
        
        //一周获得的积分值
        $sql = "select sum(day_credit) from growth_credit_day_count where broker_id = $brokerId and day_credit >0 and ctime >='$starttime' and ctime<='$endtime'";
        $weekSaveScore = $dbback->getOne($sql);
        $bidFieldsValues = array(
            'broker_id' => $brokerId, 'username' => $broker['username'],
            'agentcode' => $broker['agentcode'], 'level' => $brokerLevel,
            'credit' => $credit, 
            'hotsearch_words_success_num' => $hotSearchWordsSuccessNum[$brokerId],
            'hotsearch_words_expend_credit' => $hotSearchWordsExpendCredit[$brokerId],
            'block_words_success_num' => $blockWordsSuccessNum[$brokerId],
            'block_words_expend_credit' => $blockWordsExpendCredit[$brokerId],
            'block_expert_success_num' => $blockExpertSuccessNum[$brokerId],
            'block_expert_expend_credit' => $blockExpertExpendCredit[$brokerId],
            'bid_success_expend_credit' => $bidExpendCredit[$brokerId],
            'week_save_score' => $weekSaveScore, 'start_time' => $starttime, 'end_time' => $endtime
        );
        $sql = SqlCombinHelper::insert_sql('growth_account_bid_finish', $bidFieldsValues);
        $db->execute($sql);
        /*** 暂时不统计竞投的详情信息，等需要的时候再开放
        $id = $db->insert_id();
        $bidAllRecord = array();
        //合并竞投记录
        if (isset($bidHouseRecord[$brokerId])) {
            $bidAllRecord = array_merge($bidAllRecord, $bidHouseRecord[$brokerId]);
        }
        if (isset($bidBlockExpertRecord[$brokerId])) {
            $bidAllRecord = array_merge($bidAllRecord, $bidBlockExpertRecord[$brokerId]);
        }
        foreach($bidAllRecord as &$v) {
            $v['account_id'] = $id;
        }
        $sql = SqlCombinHelper::insertMutil_sql('growth_account_bid_finish_detail', $bidAllRecord);
        if ($db->execute($sql)) {
            GrowthLog::log("结束刷{$brokerId}竞投结果数据", $bidAllRecord);
        }***/
        $num++;
        if($num % 200 == 0){
            sleep(1);
        }
    }
}
if ($runCount == $allRecordCount) {
    sendMessage("统计{$starttime}至{$endtime}竞投数据成功");
}
echo 'over';
