<?php 
$conf_basedir = "../../"; //相对主目录的位置
$conf_where = "admin"; //选择调用相应模块
include_once($conf_basedir . "/base.inc.php");
include_once("univercity_func.php");

//有关本页面的信息
$page_id = 8130;
//header_auth_check($page_id);  //权限判断
error_reporting(7);
ini_set("display_errors", true);
//echo $dryRun;
//echo $a;
//$dryRun = true;
//基本配置
include_once($conf_basedir."model/univercityChannel/univercityChannelFunction.php");
$env = 'test';
$uc = new UnivercityChannel($env);
$tbl = $uc->getSchoolTable();
$tblSchoolImg = $uc->getSchoolImgTable();
$tblSchoolBlock = $uc->getSchoolBlockTable();

$sql_table = "show tables like 'school%'";
print_r($db);
$tablesTemp = $db->getAll($sql_table);
$tables = array();
foreach($tablesTemp as $v) {
	$tables[] = $v[0];
}

//print_r($uc);
//print_r($db);
//print_r($conf_city);
//exit;
$self = $_SERVER['PHP_SELF'];
echo "<h2>".$conf_city."</h2>";
echo "<h3>------".$env."------</h3>";
if(!$a) {
echo "<ul>";
if(!in_array('school',$tables)) {
//echo "<li><a href='".$self.'?a=install_new'."' ><em>新安装</em></a></li>";
}
//echo "<li><a href='".$self.'?a=update_1.0_2.0'."' ><em>升级从1.0到2.0</em></a></li>";
//echo "<li><a href='".$self.'?a=install'."' >创建表</a></li>";
//echo "<li><a href='".$self.'?a=import_1.0_2.0'."' >原数据导入新表</a></li>";
//echo "<li><a href='".$self.'?a=rename'."' >重命名</a></li>";
//echo "<li><a href='".$self.'?a=undorename'."' >取消重命名</a></li>";
echo "</ul>";
$x = '//学区属性 -- 兼顾数据库存在的数据
$school_type = array(0 => "请选择", 2 => "小学", 3 => "初中", 4 => "九年一贯制(小学+初中)",5 => "完中(初中+高中)");
$school_pap = array(0 => "请选择",1 => "公立", 2 => "私立", 3 => "国有民办");
$school_rank = array(0 => "请选择",1 => "普通",  3 => "市重点", 9 => "省重点", 14 => "区重点");
$school_features = array(1=>"双语","小班教学","名校附属","体育","心理健康","科技","涉外交流","动漫","艺术","专业课程类","现代技术");';
$x = highlight_string($x,true);
//学区房资讯常量配置
$y = '//学区房资讯配置
define("XQFTUZX","/xqfpd/xqftpzx/");
define("XQFMXTF","/xqfpd/xqfmxtf/");
define("XQFXQPC","/xqfpd/xqfxqpc/");
define("XQFZSZC","/xqfpd/xqfzszc/");
define("DD_XQFTUZX","xqfpd-tpzx");
define("DD_XQFMXTF","xqfpd-mxtf");
define("DD_XQFXQPC","xqfpd-xqpc");
define("DD_XQFZSZC","xqfpd-zszc");';
?>
<div>
<form action="<?php echo $self; ?>" method="get" >
<div style="float:left">
选择：
<select name = "a">
<?php if(!in_array('school',$tables)) {
?>
<option value="install_new" >新安装</option>
<?php
} ?>
<option value="update_1.0_2.0" >升级从1.0到2.0</option>
<option value="down_2.0_1.0" >降级从2.0到1.0</option>
<option value="install" >创建表</option>
</select></div>
<div style="float:left;padding:0 0 0 10px" >
dryRun:
<input type="checkbox" checked name = "dryRun" value="1">
</div>
<div ><input type="submit" value="执行" /></div>
</form>
</div>
<div><p>完成升级后请请修改配置文件$conf_<?php echo $conf_city; ?>.php。添加以下内容：</p><p><?php echo $x; ?></p>
<p><?php echo $y; ?></p></div>
<?php
} else {
	echo '<p><a href="'.$self.'" >返回</a></p>';
}

//exit;
//基本配置结束
$school = new School($db,$db_back1,$uc);
//print_r($school->getKeySchoolNumber());
//$x = $school->getKeySchoolBlock();
//print_r($x);
//$schoolConf = new Conf();
//$schoolConf->add('district','上城区')->add('schooltype','2')->add('rank','1');
//$x = $school->getSchoolBlock(199);
//print_r($x);

//获取学校小区详细信息
//$schoolBlock = new SchoolBlock($db,$db_back1);
//$x = $schoolBlock->getAll(199);
//print_r($x);
//echo $schoolBlock->getMaxPrice();
//echo "<br/>";
//echo $schoolBlock->getMinPrice();
//exit;
//RENAME TABLE `hz_house`.`school_test` TO `hz_house`.`school` ;
$sql_school = getSchoolSql($tbl);
function getSchoolSql($tbl) {
	return $sql_school = "CREATE TABLE IF NOT EXISTS `".$tbl."` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `schoolname` varchar(20) NOT NULL DEFAULT '',
  `district` varchar(10) NOT NULL DEFAULT '',
  `schooltype` smallint(5) NOT NULL,
  `streetid` smallint(5) NOT NULL,
  `weight` int(5) NOT NULL DEFAULT '9999' COMMENT '权重，权重设为1，代表该学校在列表页默认排第一位',
  `mid_school_id` varchar(10) NOT NULL DEFAULT '0' COMMENT '默认0，表示对应中学不是已存在的学校；大于0表示school表的主键',
  `mid_school_name` varchar(50) DEFAULT NULL COMMENT '对应中学的名字',
  `school_range` varchar(300) DEFAULT NULL COMMENT '学区范围',
  `features` text COMMENT '学校特色',
  `school_year` int(4) NOT NULL DEFAULT '0' COMMENT '学校年代',
  `school_area` int(8) NOT NULL DEFAULT '0' COMMENT '学校占地面积',
  `class_number` int(4) NOT NULL DEFAULT '0' COMMENT '班级总数',
  `student_number` int(6) NOT NULL DEFAULT '0' COMMENT '生源总量',
  `teacher_intro` text COMMENT '师资力量',
  `website` varchar(100) DEFAULT NULL COMMENT '网址',
  `bus_lines` text COMMENT '公交',
  `subway` varchar(50) DEFAULT NULL COMMENT '地铁',
  `street_map` mediumtext COMMENT 'soso街景地图',
  `cbd` smallint(5) NOT NULL,
  `address` varchar(100) NOT NULL,
  `rank` smallint(5) NOT NULL,
  `introduction` text NOT NULL,
  `b_map_x` double NOT NULL COMMENT 'baidu lng',
  `b_map_y` double NOT NULL COMMENT 'baidu lat',
  `telno` varchar(50) NOT NULL,
  `ispublic` tinyint(1) NOT NULL COMMENT '是否公私',
  `blockid` text NOT NULL COMMENT '相关小区',
  `block_distance` text COMMENT '小区距离',
  `coverphoto` varchar(100) NOT NULL COMMENT '封面照',
  `isshow` tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否展示',
  `HomepageKeySchool` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否是首页上显示的重点学区：0不是；1是',
  PRIMARY KEY (`id`),
  KEY `baidu map` (`b_map_x`,`b_map_y`)
) ENGINE=MyISAM  DEFAULT CHARSET=gbk AUTO_INCREMENT=0 ;";
}


$sql_school_img = getSchoolImgSql($tblSchoolImg);
function getSchoolImgSql($tblSchoolImg) {
	return $sql_school_img = "
CREATE TABLE IF NOT EXISTS `".$tblSchoolImg."` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `school_id` int(10) NOT NULL,
  `img_url` varchar(100) NOT NULL,
  `img_title` varchar(20) NOT NULL,
  `img_type` tinyint(4) NOT NULL,
  `isCover` tinyint(4) NOT NULL DEFAULT '0',
  `img_creatime` int(10) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `school_id` (`school_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=gbk COMMENT='学区图片表' AUTO_INCREMENT=0 ;";

}

$sql_school_block = getSchoolBlockSql($tblSchoolBlock);
function getSchoolBlockSql($tblSchoolBlock) {
	return $sql_school_block ="CREATE TABLE IF NOT EXISTS `".$tblSchoolBlock."` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `school_id` int(11) NOT NULL COMMENT '学校id',
  `block_id` int(11) NOT NULL COMMENT '小区id',
  `block_distance` float DEFAULT '0' COMMENT '小区和学校的距离',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=gbk COMMENT='学校和小区关系' AUTO_INCREMENT=0 ;";
}


if($_GET['a'] == 'install_new') {
	function installNew($db) {
		$uc = new UnivercityChannel('prod');
		//print_r($uc);
		$tbl = $uc->getSchoolTable();
		createUCTable($db,$tbl);
		echo '<p>create table <span style="color:green;font-weight: bold;">'.$tbl.'</span> complete</p>';
		$tblSchoolImg = $uc->getSchoolImgTable();
		createUCTable($db,$tblSchoolImg);
		echo '<p>create table <span style="color:green;font-weight: bold;">'.$tblSchoolImg.'</span> complete</p>';
		$tblSchoolBlock = $uc->getSchoolBlockTable();
		createUCTable($db,$tblSchoolBlock);
		echo '<p>create table <span style="color:green;font-weight: bold;">'.$tblSchoolBlock.'</span> complete</p>';
		//createUCTableByName($tbl);
		//createUCTableByName($tblSchoolImg);
		//createUCTableByName($tblSchoolBlock);
	}
	
	installNew($db);
	echo '<p>============install new complete=============</p>';

}
function createUCTableByName($tableName) {
		global $db;
		if($tableName) {
		}
		$sql_table = getSchoolSql($tableName);
		$sql_table = getSchoolImgSql($tblSchoolImg);
		$sql_table = getSchoolBlockSql($tblSchoolBlock);
		createUCTable($db,$sql_table);
		echo '<p>create table <span style="color:green;font-weight: bold;">'.$tableName.'</span> complete</p>';
}

if($_GET['a'] == 'update_1.0_2.0') {
	createUCTable($db,$sql_school);
	echo '<p>create table <span style="color:green;font-weight: bold;">'.$tbl.'</span> complete</p>';
	createUCTable($db,$sql_school_block);
	echo '<p>create table <span style="color:green;font-weight: bold;">'.$tblSchoolImg.'</span> complete</p>';
	createUCTable($db,$sql_school_img);
	echo '<p>create table <span style="color:green;font-weight: bold;">'.$tblSchoolBlock.'</span> complete</p>';

	//createUCTableByName($tbl);
	//createUCTableByName($tblSchoolImg);
	//createUCTableByName($tblSchoolBlock);
	echo '<p>============create table complete=============</p>';
	
	updateSchoolData($db,$uc);
	echo '<p>============update school data complete=============</p>';
	
	$name = 'school';
	$newName = $tbl;
	renameTbl($db,$name,$newName);

	$name = 'school_block';
	$newName = $tblSchoolBlock;
	renameTbl($db,$name,$newName);
	
	$name = 'school_img';
	$newName = $tblSchoolImg;
	renameTbl($db,$name,$newName);
	echo '<p>============rename complete=============</p>';
}

if($_GET['a'] == 'down_2.0_1.0') {
	$sql_d = "alter table school rename school_test";
	$sql_d2 = "alter table school_bak rename school";
	echo '<p>'.$sql_d.'</p>';
	echo '<p>'.$sql_d2.'</p>';
	if(!$dryRun) {
	$db->execute($sql_d);
	$db->execute($sql_d2);
	}
}

if($_GET['a'] == 'install') {
createUCTable($db,$sql_school);
createUCTable($db,$sql_school_img);
createUCTable($db,$sql_school_block);
}
function createUCTable($db,$tbl) {
	global $dryRun;
	echo htmlentities($tbl);
	if(!$dryRun) {
	$db->execute($tbl);
    echo '<p>'.mysql_error().'</p>';
	}
	echo "<p>create table<$tbl> complete!</p>";
}

function toThumb($imgUrl) {
	//echo $imgUrl;
	//var_dump(stripos($imgUrl,'/thumb/'));exit;
	if(!stripos($imgUrl,'/thumb/')) {
		$bn = basename($imgUrl);
		return str_replace($bn,"thumb/".$bn,$imgUrl);
	} else {
		return $imgUrl;
		//return false;
	}
	

}

//把大图地址转成小图地址
if($_GET['a'] == 'mpic') {
	$sql = "select * from $tblSchoolImg";
	$imgs = $db->getAll($sql);
	foreach($imgs as $v) {
		$newImgUrl = toThumb($v['img_url']);
		if($newImgUrl) {
		$iid = $v['id'];
		$sql = "update $tblSchoolImg set img_url = '$newImgUrl' where id = $iid";
		$db->execute($sql);
		}
	}
}


if($_GET['a'] == 'import_1.0_2.0') {
//导入原来数据
$sql_school = "select * from school";
$schools = $db->GetAssoc($sql_school);
foreach($schools as $v) {
	foreach($v as $key=>&$x) {
		if(is_int($key)) {
			unset($v[$key]);
		}
	}
	$value = implode("','",$v);
	$sql_s = "insert into $tbl (id,schoolname,district,schooltype,streetid,cbd,address,rank,introduction,b_map_x,b_map_y,telno,ispublic,blockid,coverphoto,isshow) value ('$value')";
    $db->Execute($sql_s);	
	$id = $db->Insert_ID();

	//小区
	$btemp = $v['blockid'];
	$btemp = explode(",",$btemp);
	foreach($btemp as $vb) {
		$sql_sb = "insert into $tblSchoolBlock (school_id,block_id) value ( '$id','$vb' )";
		$db->execute($sql_sb);
	}
	
	//图片
	$coverphoto = toThumb($v['coverphoto']);
	$time =time();
	echo $sql_img = "insert into $tblSchoolImg (school_id,img_url,img_creatime) value ('$id','$coverphoto','$time')";
	$db->execute($sql_img);
	echo "<br/>";
	//exit;
}

}

if($_GET['a'] == 'changeFeature') {
	exit;
	$select = new Select();
	$select->add('id')->add('id')->add('features');
	$conf = new Conf();
	$conf->add('features','','!=');
	$rel = $school->getSchoolByKeyword($select,$conf);
	//print_r($rel);
	foreach($rel as $v) {
		print_r($v);echo "<br/>";
		$f = arraySerToFeature($v['features']);
		var_dump($v['features']);
		if(1) {
		echo $sql = "update $tbl set features ='$f'  where id='".$v['id']."'";
		$db->execute($sql);
		}
		
		echo "<br/>";
	}

}

//部署数据库表
if($a=='rename') {
	//alter table my rename to mytime;
	//$sql[]= 'alter table school rename to school_bak';
	//$sql[]='alter table $tbl rename to school'; 
	$name = 'school';
	$newName = $tbl;
	renameTbl($db,$name,$newName);

	$name = 'school_block';
	$newName = $tblSchoolBlock;
	renameTbl($db,$name,$newName);
	
	$name = 'school_img';
	$newName = $tblSchoolImg;
	renameTbl($db,$name,$newName);

}
if($a=='undorename') {
	$name = 'school';
	$newName = $tbl;
	renameTbl($db,$name,$newName,true);

	$name = 'school_block';
	$newName = $tblSchoolBlock;
	renameTbl($db,$name,$newName,true);
	
	$name = 'school_img';
	$newName = $tblSchoolImg;
	renameTbl($db,$name,$newName,true);

}
function renameTbl($db,$name,$testName,$undo=false) {
	$bakname = $name.'_bak';
	global $tables;
	global $dryRun;
	if($undo) {
		$sql = "alter table $name rename to $testName";
		if(in_array($backname,$tables)) {
		$sql2 = "alter table $bakname rename to $name";
		}
	} else {
		if(in_array($name,$tables)) {
		$sql = "alter table $name rename to $bakname";
		}
		$sql2 = "alter table $testName rename to $name";
	}
	if($sql) {
	echo $sql;echo "<br/>";
	if(!$dryRun) { 
	$db->execute($sql);
	}
	}
	if($sql2) {
	echo $sql2;echo "<br/>";
	if(!$dryRun) { 
	$db->execute($sql2);
	}
	}
	//alter table school1 rename school_test;# MySQL 返回的查询结果为空(即零行)。
	//alter table school1_bak rename school1;# MySQL 返回的查询结果为空(即零行)。
	
	
}

function import($v,$tbl,$tblSchoolImg,$tblSchoolBlock) {
	foreach($v as $key=>&$x) {
		if(is_int($key)) {
			unset($v[$key]);
		}
	}
	$value = implode("','",$v);
	$sql_s = "insert into $tbl (id,schoolname,district,schooltype,streetid,cbd,address,rank,introduction,b_map_x,b_map_y,telno,ispublic,blockid,coverphoto,isshow) value ('$value')";
    $db->Execute($sql_s);	
	$id = $db->Insert_ID();
	//小区
	$btemp = $v['blockid'];
	$btemp = explode(",",$btemp);
	foreach($btemp as $vb) {
		if($vb) {
		echo $sql_sb = "insert into $tblSchoolBlock (school_id,block_id) value ( '$id','$vb' )";
		$db->execute($sql_sb);
		}
	}
	
	//图片
	if($v['coverphoto']) {
	$coverphoto = toThumb($v['coverphoto']);
	$time =time();
	echo $sql_img = "insert into $tblSchoolImg (school_id,img_url,img_creatime) value ('$id','$coverphoto','$time')";
	$db->execute($sql_img);
	}
	echo "<br/>";

}

function updateSchoolData($db,$uc) {
	global $dryRun;
    $tbl = $uc->getSchoolTable();
    $tblSchoolImg = $uc->getSchoolImgTable();
    $tblSchoolBlock = $uc->getSchoolBlockTable();
    $sql_school = "select id,schoolname,district,schooltype,streetid,cbd,address,rank,introduction,b_map_x,b_map_y,telno,ispublic,blockid,coverphoto,isshow from school";
    $schools = $db->GetAssoc($sql_school);
	if(!is_array($schools)) {
		return false;
	}
    foreach($schools as $v) {
            foreach($v as $key=>&$x) {
                    if(is_int($key)) {
                            unset($v[$key]);
                    }
            }
            $value = implode("','",$v);
            $sql_s = "insert into $tbl (id,schoolname,district,schooltype,streetid,cbd,address,rank,introduction,b_map_x,b_map_y,telno,ispublic,blockid,coverphoto,isshow) value ('$value')";
			if(!$dryRun) { 
			$db->Execute($sql_s);
			}
			echo '<p>'.$sql_s.'</p>';
            $id = $db->Insert_ID();
            //小区
            $btemp = $v['blockid'];
            $btemp = explode(",",$btemp);
            foreach($btemp as $vb) {
				if($vb) {
                    $sql_sb = "insert into $tblSchoolBlock (school_id,block_id) value ( '$id','$vb' )";
					if(!$dryRun) { 
                    $db->execute($sql_sb);
					}
					echo '<p>'.$sql_sb.'</p>';
				}
            }

            //图片
			if($v['coverphoto']) {
            $coverphoto = toThumb($v['coverphoto']);
            $time =time();
            echo $sql_img = "insert into $tblSchoolImg (school_id,img_url,img_creatime) value ('$id','$coverphoto','$time')";
			if(!$dryRun) { 
            $db->execute($sql_img);
			}
            echo "<br/>";
			}
            //exit;
    }
}

?>