<?php
//exit('exit');
/**
 * @author solar
 * @todo 整理城市和邮编
 */
require_once ('config.php');
$flagFile = APPLICATION_PATH . '/../data/log/citypostcode.lock';
if (@file_exists($flagFile)) {
    echo 'Another process is running.'."\r\n";
    echo $flagFile."\r\n";
    exit();
}
$link = fopen($flagFile, 'wb');
fclose($link);
define('RUNTIME', '[' . date('Y-m-d H:i:s') . '] ');
echo RUNTIME . "Starting.\r\n\r\n";

$adapter = Service_City::getModelInstance()->getAdapter();
try {
	while (true) {
		$sql = "select * from city_postcode as cp where cp.flag=0 limit 1000;";
		$list = $adapter->fetchAll($sql);
		if(empty($list)) break;
		foreach($list as $row) {
			$city_name = trim($row['city_name']);
			$aCity = Service_City::getByWhere(array('country_id'=>$row['country_id'], 'city_name'=>$city_name));
			if(empty($aCity)) {
				$aCity['country_id'] = $row['country_id'];
				$aCity['country_name'] = $row['country_name'];
				$aCity['city_name'] = $city_name;
				$aCity['city_id'] = Service_City::add($aCity);
			}
			$postcode_start = trim($row['postcode_start']);
			$postcode_end = trim($row['postcode_end']);
			if(empty($postcode_start) && empty($postcode_end)) {
				$adapter->query("update city_postcode set state=3 where cp_id=".$row['cp_id']." limit 1");
			} else if($postcode_start == $postcode_end) {
				$aPostcode['city_id'] = $aCity['city_id'];
				$aPostcode['postcode_no'] = $postcode_start;
				$postcode_id = Service_Postcode::add($aPostcode);
			} else if(is_numeric($postcode_start) && is_numeric($postcode_end) && $postcode_end>$postcode_start) {
				for($i=$postcode_start; $i<=$postcode_end; $i++) {
					$aPostcode['city_id'] = $aCity['city_id'];
					$aPostcode['postcode_no'] = $i;
					$postcode_id = Service_Postcode::add($aPostcode);
				}
				$adapter->query("update city_postcode set state=1 where cp_id=".$row['cp_id']." limit 1");
			} else {
				$adapter->query("update city_postcode set state=2 where cp_id=".$row['cp_id']." limit 1");
			}
			$adapter->query("update city_postcode set flag=1 where cp_id=".$row['cp_id']." limit 1");
			echo '记录['.$row['cp_id'].']整理成功'."\r\n";
		}
		unset($list);
	}	
} catch (Exception $e) {
    @unlink($flagFile);
    echo '[' . date('Y-m-d H:i:s') . '] Fail Exception:' . $e->__toString() ."\r\n";
}

echo "\r\n[" . date('Y-m-d H:i:s') . "] End run\r\n";
@unlink($flagFile);
