<?php
/**
 * 竞投结束后的处理
 * 1，on表数据移动到history表
 * 2，对竞投成功的，扣除积分，且解冻相应积分
 * 3, 加成长值
 * 4，对竞投成功的，刷成功表
 * @param int $periodsId 期次id
 * @param string $type house 或者 blockExpert
 */
function bidFinishHandle($periodsId,$type) {
    $growthRecordOn = GrowthBidRecordFactory::getRecordOnClass($type);
    $pid = $periodsId;
    $growthRecordHistory = GrowthBidRecordFactory::getRecordHistoryClass($type);//new GrowthBidBlockExpertRecordHistory();
    //print_r($recordOn);
    
    $bidIds = array();
	$bidSuccessData = array();
    $fields = $growthRecordHistory->getFields();
    $recordOnCount = $growthRecordOn->findCountByPeriodsId($pid);
    $runCount = 0;
    $tempnum = 200;
	$fornum = ceil($recordOnCount / $tempnum);
	for($i=0; $i<$fornum; $i++) { 
		$j = 0;
        $startnum = $i * $tempnum;
        $recordOn = $growthRecordOn->findBy("bid_periods_id='$pid'", 'id asc', "$startnum, $tempnum");
        if($recordOn) {
            $bidNum = count($recordOn);
            foreach ($recordOn as $r) {
                $j++;
                $bidIds = $r['bid_id'];
                $temp = array();
                foreach ($fields as $value) {
                    if($value=='id') {continue;}
                    $temp[$value] = $r[$value];
                }
                $inserTemp[] = $temp;
                if ($bidNum == $j) {
                    GrowthLog::log('开始刷'.$growthRecordHistory->getTable(),'');
                    $affectedLineNumber = $growthRecordHistory->insertMutl($inserTemp);
                    GrowthLog::log('结束'.$growthRecordHistory->getTable().'共'.$affectedLineNumber.'条数据', $inserTemp);
                    $inserTemp = array();
                }
                if($temp['status']==1) {//暂时保存成功的数据
                    $bidSuccessData[] = $temp;
                }
            }
            $runCount += $affectedLineNumber;
            //更新前4名的status
            /*
            array_unique($bidIds);//去重复
            if($bidIds) {
                foreach ($bidIds as $bid) {
                    $tableName = $growthRecordHistory->getTable();
                    $sql = "update $tableName set status = ";
                }
            }
             * 
             */
        }
    }
    if ($recordOnCount == $runCount) {
        GrowthLog::log('成功，期次为'.$pid.'的所有竞投记录已刷到history表',array('total'=>$recordOnCount,'runcount'=>$runCount));
        sendMessage('成功，期次为'.$pid.'的所有竞投记录已刷到history表');
        handleBidSuccessData($bidSuccessData,$type,$pid);
        echo 'success';
        return true;
    } else {
        GrowthLog::log('失败，期次为'.$pid.'的竞投记录未全部刷到history表',array('number'=>$recordOnCount,'runcount'=>$runCount));
        echo 'failture';
        return false;
    }
}

/**
 * 保存竞投成功记录；扣除积分，解冻积分；加成长值
 * @param type $bidSuccessData 竞投成功记录
 * @param type $type 竞投类型，小区专家或房源竞投
 * @param type $pid 竞投期次id
 * @return null
 */
function handleBidSuccessData($bidSuccessData,$type,$pid,$debug=0) {
    //不是数组，或空数组
    global $conf_cityflag;
    if(!is_array($bidSuccessData)||empty($bidSuccessData)) {
        return null;
    }
    //查找期次的推广时间
    $growthBidPeriods = new GrowthBidPeriods();
    //$cPeriods
    $cPeriods = $growthBidPeriods->findById($pid);
    $growthRecordFinish = GrowthBidRecordFactory::getRecordFinishClass($type);//new GrowthBidBlockExpertRecordHistory();
    //print_r($recordOn);
    $wayBlock = new WayBlock();
    //房源竞投关键词
    $growthBidHouse = new GrowthBidHouse();
    $block = new Block();
    GrowthLog::log('开始刷竞投成功表，期次为'.$pid.'',array());
    foreach ($bidSuccessData as $temp) {
        if($type=='blockExpert') {//如果是小区专家竞投
            /*****************扣积分*****************/
            $blockId = $temp['block_id'];
            $creditWay = $wayBlock->getBlockExpertWayAlias($blockId);
            //刷成功记录表
            $tempBlock = array(
                    'broker_id' => $temp['broker_id'],
                    'block_id'  =>  $temp['block_id'],
                    'block_name' => $temp['block_name'],
                    'score'      => $temp['score'],
                    'utime'   => $temp['utime'],
                    'tg_start_time' => $cPeriods['tg_start_time'],
                    'tg_end_time' => $cPeriods['tg_end_time'],
            );
            $insertId = $growthRecordFinish->insert($tempBlock);
            if($insertId) {
                GrowthLog::log('成功，刷小区竞投id为'.$temp['bid_id'].'成功记录',$tempBlock);
            } else {
                GrowthLog::log('失败，刷小区竞投id为'.$temp['bid_id'].'成功记录',$tempBlock);
            }
        }
        if($type=='house') {//房源竞投
            $bidRow = $growthBidHouse->findById($temp['bid_id']);
            if ($temp['type'] == 1) {
                $blockInfo = $block->findOneBy($bidRow['block_id']);
                $keyword = $blockInfo['blockname'];
                $creditWay = 'bidHouseBlockWord';
            } else {
                $keyword = $bidRow['keyword'];
                $creditWay = 'bidHouseMarketWord';
            }
            $tempHouse = array(
                    'type' => $temp['type'],
                    'broker_id' => $temp['broker_id'],
                    'house_id' => $temp['house_id'],
                    'keyword' => $keyword,
                    'score'   => $temp['score'],
                    'utime'   => $temp['utime'],
                    'tg_start_time' => $cPeriods['tg_start_time'],
                    'tg_end_time' => $cPeriods['tg_end_time'],
            );
            $insertId = $growthRecordFinish->insert($tempHouse);
            if($insertId) {
                GrowthLog::log('成功，刷房源竞投id为'.$temp['bid_id'].'成功记录',$tempHouse);
            } else {
                GrowthLog::log('失败，刷房源竞投id为'.$temp['bid_id'].'成功记录',$tempHouse);
            }
        }
        if(!$debug) {
            $score = $temp['score'];
            $description = NULL;
            $brokerId = $temp['broker_id'];
            $broker = array('id'=>$brokerId);
            $brokerGroup = new BrokerGroup();
            $brokerRow = $brokerGroup->getBrokerGroupInfo($brokerId);
            if(!$brokerRow) {GrowthLog::log('经纪人'.$brokerId.'不存在'.$score,array());continue;}			
			$broker['groupid'] = $brokerRow['package_id']; 		
			

            $growthBrokerCredit = new GrowthBrokerCredit($broker);
            if($conf_cityflag=='nj') {
                $type2=2;$creditName="房豆";$creditUnit="房豆";
                $descriptionC = $growthBrokerCredit->getWayAliasName($creditWay);
                $descriptionC = $descriptionC . '扣除' . abs($score) . $creditUnit;
            }else {
                $type2=1;$creditName="积分";$creditUnit="分";
                $descriptionC = null;
            }
            $growthBrokerCredit->reduce($creditWay, $descriptionC, $score,$type2);
            GrowthLog::log('扣除'.$brokerId.'的'.$creditName.$score,array());
            /*************扣完积分,解除冻结*****************/
            $growthBrokerCredit->frozenCredit("-".$score,$brokerId,$alisWay='bidFinish','竞投结束，解除冻结'.$score,$type);
            GrowthLog::log('解除冻结'.$brokerId.'的'.$creditName.$score,array());
            /*************加成长值************************/
            $growthBrokerExp = new GrowthBrokerExp($broker);
            $growthBrokerExp->increase($creditWay, $description);
            GrowthLog::log('增加'.$brokerId.'的成长值'.$score,array());
        }
        
    }
    sendMessage('结束刷竞投成功表，期次为'.$pid);
    GrowthLog::log('结束刷竞投成功表，期次为'.$pid.'',array());
}

/**
 * 根据时间创建小区专家竞投
 * @param type $startTime 竞投开始时间Y-m-d H:i:s格式的字符串，下同
 * @param type $endTime 竞投结束时间
 * @param type $tgStartTime 推广开始时间
 * @param type $tgEndTime 推广结束时间
 */
function createNextBidBlockExpert($startTime,$endTime,$tgStartTime,$tgEndTime) {
    $growthBidPeriods = new GrowthBidPeriods();
    $growthBid = new GrowthBidBlockExpert();
    //竞投小区专家期次
    $fieldData = array(
        'type' => 1,
        'name' => '小区专家竞投',
        'start_time'=>$startTime,
        'end_time'=>$endTime,
        'tg_start_time'=>$tgStartTime,
        'tg_end_time'=>$tgEndTime);
    $bidPeriodsId = $growthBidPeriods->insert($fieldData);
    if($bidPeriodsId) {
        echo "创建小区专家竞投期次，id=".$bidPeriodsId."。"."时间：".$fieldData['tg_start_time']."到".$fieldData['tg_end_time'];
        echo "<br/>";
    } else {
        echo "创建小区专家竞投期次，失败";
    }

    //小区id和等级
    $blockLevelHeat = new BlockLevelHeat();
    $blocks = $blockLevelHeat->findAll();

    //起拍积分，参与等级
    $growthBidStartSetting = new GrowthBidStartSetting();
    $data_info = $growthBidStartSetting->getData();
    $data_info1 = array();
    foreach ($data_info as $key => $value) {
        $data_info1[$value['way_alias']] = $value; 
    }
    $bidData = array();
    if($blocks) {
        $cblocksNumber = getCustomBlockBidNumber();
        foreach ($blocks as $key => $value) {
            $blockId = $value['block_id'];
            if(array_key_exists($blockId, $cblocksNumber)){
                $number = $cblocksNumber[$blockId]['number'];
                if($number>=4){
                    continue;
                } else {
                    $number = 4-$number;
                }
            } else {
                $number = 4;
            }
            $temp = array();
            $temp['bid_periods_id'] = $bidPeriodsId;
            $temp['block_id'] = $value['block_id'];
            $temp['block_level'] = $value['level'];
            $temp['broker_level'] = $data_info1['bid'.$value['level'].'Experts']['levelnames'];
            $temp['min_score'] = $data_info1['bid'.$value['level'].'Experts']['start_credit'];
            $temp['valid'] = 1;
            $temp['max_win_number'] = $number;
            $temp['ctime'] = date("Y-m-d H:i:s");
            $inid = $growthBid->insert($temp);
            if($inid) {
                echo "创建小区竞投成功，id=".$inid."。小区id为".$value['id'];
            } else {
                echo "失败，小区id为".$value['id'];
            }
            echo "<br/>";
        }
    }
    sendMessage('创建小区竞投成功');
    //刷指定的小区专家
    refreshSpecBlockExpert($fieldData);
}

/**
 * 根据时间创建房源竞投
 * @param type $startTime 竞投开始时间Y-m-d H:i:s格式的字符串，下同
 * @param type $endTime 竞投结束时间
 * @param type $tgStartTime 推广开始时间
 * @param type $tgEndTime 推广结束时间
 */
function createNextBidHouse($startTime,$endTime,$tgStartTime,$tgEndTime) {
    $growthBidPeriods = new GrowthBidPeriods();
    $growthBid = new GrowthBidHouse();
    //竞投小区词期次
    $fieldData = array(
        'type' => 2,
        'name' => '房源竞投',
        'start_time'=>$startTime,
        'end_time'=>$endTime,
        'tg_start_time'=>$tgStartTime,
        'tg_end_time'=>$tgEndTime);
    $bidPeriodsId = $growthBidPeriods->insert($fieldData);
    if($bidPeriodsId) {
        echo "创建小区词竞投期次，id=".$bidPeriodsId."。"."时间：".$fieldData['tg_start_time']."到".$fieldData['tg_end_time'];
        echo "<br/>";
    } else {
        echo "创建小区词竞投期次，失败";
    }

    //小区id和等级
    $blockLevelHeat = new BlockLevelHeat();
    $blocks = $blockLevelHeat->findAll();

    //起拍积分，参与等级
    $growthBidStartSetting = new GrowthBidStartSetting();
    $data_info = $growthBidStartSetting->getData();
    $data_info1 = array();
    foreach ($data_info as $key => $value) {
        $data_info1[$value['way_alias']] = $value; 
    }
    if($blocks) {
        foreach ($blocks as $key => $value) {
            $temp = array();
            $temp['bid_periods_id'] = $bidPeriodsId;
            $temp['type'] = 1;
            $temp['block_id'] = $value['block_id'];
            $temp['block_level'] = $value['level'];
            $temp['broker_level'] = $data_info1['bidHouseBlockWord']['levelnames'];
            $temp['min_score'] = $data_info1['bidHouseBlockWord']['start_credit'];
            $temp['valid'] = 1;
            $temp['max_win_number'] = 2;
            $temp['ctime'] = date("Y-m-d H:i:s");
            $inid = $growthBid->insert($temp);
            if($inid) {
                echo "创建小区词竞投成功，id=".$inid."。小区id为".$value['id'];
            } else {
                echo "失败，小区id为".$value['id'];
            }
            echo "<br/>";
        }
    }
    
    //热搜词
    $growBidHotSearchSet = new GrowthBidHotSearchSet();
    $arrSearchWords = $growBidHotSearchSet->findWords();
    if($arrSearchWords) {
        foreach ($arrSearchWords as $key => $value) {
            $temp = array();
            $temp['bid_periods_id'] = $bidPeriodsId;
            $temp['type'] = 2;
            $temp['keyword'] = $value['words'];
            $temp['broker_level'] = $data_info1['bidHouseBlockWord']['levelnames'];
            $temp['min_score'] = $data_info1['bidHouseBlockWord']['start_credit'];
            $temp['valid'] = 1;
            $temp['max_win_number'] = 2;
            $temp['ctime'] = date("Y-m-d H:i:s");
            $inid = $growthBid->insert($temp);
            if($inid) {
                echo "创建热搜词竞投成功，id=".$inid."。热搜词为".$value['words'];
            } else {
                echo "失败，热搜词为".$value;
            }
            echo "<br/>";
        }
    }
    sendMessage('创建房源竞投成功');
}

/**
 * 更新竞投小区专家最低等级
 */
function updateBidBlockExpertLowLevel() {
	$growthBidStartSetting = new GrowthBidStartSetting();
	$data_info = $growthBidStartSetting->getData();
	$growthBidLowLevel = new GrowthBidLowLevel();
	$minBidBlockLevel = '';
	$bidBlockLevels = '';
	foreach ($data_info as $key => $value) {
	   //subclass = 1 小区竞投  subclass 2 房源竞投
	   if ($value['subclass'] == 1) {
		   $bidBlockLevels .= str_replace('LV', '', $value['levelnames']) . ',';
	   }
	}
	$bidBlockLevels = rtrim($bidBlockLevels, ',');
	$minBidBlockLevel = min(explode(',', $bidBlockLevels));
	$bolUpdateBlock = $growthBidLowLevel->updateBlockExpertLevel('LV' . $minBidBlockLevel);
	if ($bolUpdateBlock) {
		echo '更新小区专家最低竞投等级成功';
	}
}

/**
 * 更新竞投房源最低等级
 */
function updateBidHouseLowLevel() {
	$growthBidStartSetting = new GrowthBidStartSetting();
	$data_info = $growthBidStartSetting->getData();
	$growthBidLowLevel = new GrowthBidLowLevel();
	$minBidHouseLevel = '';
	$bidHouseLevels = '';
	foreach ($data_info as $key => $value) {
	   if ($value['subclass'] == 2) {
		   $bidHouseLevels .= str_replace('LV', '', $value['levelnames']) . ',';
	   }
	}
	$bidHouseLevels = rtrim($bidHouseLevels, ',');
	$minBidHouseLevel = min(explode(',', $bidHouseLevels));
	$bolUpdateHouse = $growthBidLowLevel->updateHouseLevel('LV' . $minBidHouseLevel);
	if ($bolUpdateHouse) {
		echo '<br>更新房源最低竞投等级成功';
	}
}

/**
 * 更新竞投房源中热搜词和小区词的相关等级
 */
function updateBidHouseLevel() {
	$growthBidStartSetting = new GrowthBidStartSetting();
    $data_info = $growthBidStartSetting->getData();
    $bidHouseBlockLevel = '';
    $bidHouseHotSearchLevel = '';
    if ($data_info) {
        foreach($data_info as $v) {
            if ($v['way_alias'] == 'bidHouseBlockWord') {
                $bidHouseBlockLevel = $v['levelnames'];
            }
            if ($v['way_alias'] == 'bidHouseMarketWord') {
                $bidHouseHotSearchLevel = $v['levelnames'];
            }
        }
        $growthBidHouseLevel = new GrowthBidHouseLevel();
        $updateBlockStatus = $growthBidHouseLevel->updateBlockLevel($bidHouseBlockLevel);
        $updateHotSearchStatus = $growthBidHouseLevel->updateHotSearchLevel($bidHouseHotSearchLevel);
        if($growthBidHouseLevel && $updateHotSearchStatus) {
            echo '竞投房源所需要的等级成功';
        }
    }
}

/**
 * 返回几天后的日期
 * @param type $date 日期，格式 Y-m-d H:i:s
 * @param int $days 天数
 * @return type
 */
function getNextBidDateFromBidDate($date,$days){
    return date("Y-m-d H:i:s",strtotime("+".$days." days", strtotime($date)));
}

/**
 * 保存执行过job的数据
 * @global type $db_sys
 * @global type $city
 * @param type $jobname
 * @param type $msg
 */
function insertJobData($jobname, $msg) {
    global $db_sys, $conf_city;
    $arrFiledValues = array();
    $arrFiledValues['city'] = $conf_city;
    $arrFiledValues['jobname'] = $jobname;
    $arrFiledValues['msg'] = $msg;
    $arrFiledValues['ymd'] = date('Ymd');
    $arrFiledValues['his'] = date("H:i:s");
    $sql = SqlCombinHelper::insert_sql('log_job', $arrFiledValues);
    $db_sys->execute($sql);
}

/**
 * 查找某个job是某已经执行成功
 * @global type $db_sys
 * @global type $city
 * @param type $jobname
 * @param type $msg
 */
function getJobState($jobname) {
	global $db_sys, $conf_city;
	$nowDate = date('Ymd');
	$sql = SqlCombinHelper::count_sql('log_job', "city = '$conf_city' AND jobname = '$jobname' AND ymd='$nowDate'");
	return $db_sys->getOne($sql);
}


//发送短信
function sendMessage($msg) {
    $telno = array('13851894682', '18260082244');
    $telno = array();
    foreach($telno as $v) {
        curl_get_contents("http://mysms.house365.com:81/index.php/Interface/apiSendMobil/jid/7/depart/3/city/nj/mobileno/".$v."/msg/".urlencode($msg));
    }
}

//http curl请求
if(!function_exists('curl_get_contents'))
{
	function curl_get_contents($str,$t_url="")
	{
		$ch = curl_init();
		$t_url = $t_url ? $t_url : "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		curl_setopt($ch, CURLOPT_URL, $str);
		curl_setopt($ch, CURLOPT_REFERER, $t_url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

		$str = curl_exec($ch);
		curl_close($ch);
		return $str;
	}
}

//自定义
function getCustomBlockBidNumber() {
    global $dbback;
    $time = time();
    $sql = "SELECT blockid,count(id) as number  FROM `block_apply` WHERE esta in(1,11) AND and endtime> ".$time."  group by blockid ";
    $res = $dbback->getAll($sql);
    $res = SqlCombinHelper::changeToKeyArray($res, 'blockid');
    return $res;
}

/**
 * 刷指定的小区专家
 */
function refreshSpecBlockExpert($cPeriods) {
    global $dbback;
    $time = time();
    $sql = "SELECT uid,blockid,blockname  FROM `block_apply` WHERE esta in(1,11) AND endtime> ".$time."  ";
    $res = $dbback->getAll($sql);
    if($res) {
        $growthRecordFinish = GrowthBidRecordFactory::getRecordFinishClass('blockExpert');
        foreach ($res as $temp) {
            $tempBlock = array(
                    'broker_id' => $temp['uid'],
                    'block_id'  =>  $temp['blockid'],
                    'block_name' => $temp['blockname'],
                    'score'      => -1,//表示是指定的，不是通过竞投的
                    //'utime'   => $temp['utime'],//使用默认值，创建竞投时
                    'tg_start_time' => $cPeriods['tg_start_time'],
                    'tg_end_time' => $cPeriods['tg_end_time'],
            );
            //var_dump($tempBlock);
            //continue;
            $insertId = $growthRecordFinish->insert($tempBlock);
            if($insertId) {
                GrowthLog::log('指定'.$temp['broker_id'].'为小区专家',$tempBlock);
            } else {
                GrowthLog::log('未能指定'.$temp['broker_id'].'为小区专家',$tempBlock);
            }
        }
    }

}
?>
