<?php
/**
 * 小区均价评估
 * 预计 1个月评估一次
 */
require('path.inc.php');

$housesell =  new HouseSell($query);
//计算二手房A+房源的单价比
/*$sql ="select * from fke_borough";
$query->open($sql);
while ($rs = $query->next()) {
	$house_num = $housesell->getCount(0,' and borough_id='.$rs['id']);
	if($house_num > 5){
		$sum_array = $query_mysql->getValue('select sum(house_price) as sum_p,sum(house_totalarea) as sum_t from fke_housesell where borough_id='.$rs['id']);
		if($sum_array){
			$avg_price = intval($sum_array['sum_p']*10000/$sum_array['sum_t']);
			$query_mysql->execute('update fke_borough set borough_avgprice='.$avg_price.' where id = '.$rs['id']);
		}
		echo $rs['id']."<br/>";
	}
}*/
$sql ="select * from fke_borough where isdel = 0";
$query->open($sql);
$threeMonthBefore = mktime(0,0,0,date('m')-3,date('d'),date('Y'));
while ($rs = $query->next()) {
	$percent_change = 0;
	$avg_price = 0;
	$sum_array = $query_mysql->getValue('select sum( t.house_price/t.house_totalarea ) as sum_p,count(*) as sum_c from fke_housesell as t where borough_id='.$rs['id'].' and created >='.$threeMonthBefore.' and house_type in (1,2)');
	if($sum_array['sum_c']<5){
		continue;
	}
	if($sum_array){
		$avg_price = intval($sum_array['sum_p']*10000/$sum_array['sum_c']);
		if($rs['borough_avgprice']){
			$percent_change = round(($avg_price-$rs['borough_avgprice'])/$rs['borough_avgprice']*100,2);
		}
		if($percent_change){
			$query_mysql->execute('update fke_borough set borough_avgprice='.$avg_price.',percent_change ='.$percent_change.' where id = '.$rs['id']);
		}else{
			$query_mysql->execute('update fke_borough set borough_avgprice='.$avg_price.' where id = '.$rs['id']);
		}
	}
	echo $rs['id']."<br/>";
	
	//记录LOG
	//now
	$now_date = mktime(0,0,0,date('m',$cfg['time']),date('d',$cfg['time']),date('Y',$cfg['time']));
	if($query_mysql->getValue("select id from fke_borough_avgprice where borough_id =".$rs['id']." and add_time = ".$now_date)){
		$query_mysql->execute("update fke_borough_avgprice set borough_avgprice=".$avg_price.",percent_change=".$percent_change." where borough_id =".$rs['id']." and add_time = ".$now_date);
	}else{
		$query_mysql->execute("insert into fke_borough_avgprice (borough_id, borough_avgprice,percent_change,add_time) values ('".$rs['id']."','".$avg_price."','".$percent_change."','".$now_date."')");
	}
	
}
echo "小区均价完成";

?>