<?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) {
    //�������飬�������
    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['groupid'];
            $growthBrokerCredit = new GrowthBrokerCredit($broker);
            $growthBrokerCredit->reduce($creditWay, $description, $score);
            GrowthLog::log('�۳�'.$brokerId.'�Ļ���'.$score,array());
            /*************�������,�������*****************/
            $growthBrokerCredit->frozenCredit("-".$score);
            GrowthLog::log('�������'.$brokerId.'�Ļ���'.$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) {
        foreach ($blocks as $key => $value) {
            $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'] = 4;
            $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('����С����Ͷ�ɹ�');
}

/**
 * ����ʱ�䴴����Դ��Ͷ
 * @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'");
	echo $sql;
	return $db_sys->getOne($sql);
}


//���Ͷ���
function sendMessage($msg) {
    $telno = array('13851894682', '18260082244');
    foreach($telno as $v) {
        curl_get_contents("http://mysms.house365.com/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;
	}
}
?>
