<?php

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

//有关本页面的信息
checkAuth('34');
//基本配置
include_once($conf_basedir."model/univercityChannel/univercityChannelFunction.php");
$uc = new UnivercityChannel('test');
$tbl = $uc->getSchoolTable();
$tblSchoolImg = $uc->getSchoolImgTable();
$tblSchoolBlock = $uc->getSchoolBlockTable();
$schoolEnableCity = array('nj','hz','sz','hf','wx','cz','cq','xa','ks','wh');
//基本配置结束
$school  = new School($db,$dbback,$uc);
//<script type='text/javascript' src='script/formValidator.js'></script><script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
$title = "学区房";
$css = "<link href='./css/cp.css' rel='stylesheet' type='text/css' />";
$js = "<script src='script/cp.js' type='text/javascript' ></script>".''."</script><script type='text/javascript' src='js/swf/swfupload.js'></script><script type='text/javascript' src='js/school_pic_upload_handlers.js'></script><script type='text/javascript' src='script/formValidator.js'></script>";
$css.='<link href="./css/jquery-ui.css" rel="stylesheet" type="text/css" />


<script type="text/javascript" src="script/flip.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>';
$empty = array("" => "*请选择*");
$house['district'] = $empty + $conf_house['district'];


$arrcbd = $db->GetAssoc("select id,cbdname from cbd ");
if ($arrcbd != '') {
	$house[cbd] = $empty + $arrcbd;
} else {
	$house[cbd] = $empty;
}

$arrsrte = $db->GetAssoc("select id,streetname from street");
if ($arrsrte != '') {
	$house[street] = $empty + $arrsrte;
} else {
	$house[street] = $empty;
}

if($action=="add") {
	$title .= "-添加";
}

//------------------------修改信息-------------------------------------------------------------------
if ($action == "modify") {
	$title .= "-修改";
    $q = "select * from $tbl where id=$id";
    if ($q_ext != "")
        $q.=" and " . $q_ext;
    $data_info = $db->GetRow($q);

    if (count($data_info) == 0) {
        echo "<script>alert('没有发现您查询的记录');window.opener.location.reload();window.close();</script>";
		exit;
	}
	$sp = new SchoolPic($db,$dbback,$uc);
	$schoolPics = $sp->getAll($id);
    $spic = array();
    if($schoolPics) {
	foreach( $schoolPics as &$spic ) {
		$spic['img_title'] = iconv('gbk', 'utf8', $spic['img_title']);
	}
    }
	//$schoolPics =getSchoolPics($db,$tblSchoolImg,$id);
	$sb = new SchoolBlock($db,$dbback,$uc);
	$sbOrder = new order('a');
	$sbOrder->setOrder('id','asc');
	$sbConf = new Conf();
	$sbConf->add('school_id',$id);
	$schoolBlock = $sb->getAllBy($sbConf,$sbOrder);
    convGbkArrToUtfArr(&$schoolBlock);
	//$schoolBlock = getSchoolBlock($db,$tblSchoolBlock,$id);
	$midSchoolName = $data_info['mid_school_name'];
	if($mid_school_id=$data_info['mid_school_id']) {
		$midSchool = $db->getRow("select schoolname from $tbl where id ='$mid_school_id' ");
		if($midSchool) {
			$midSchoolName = $midSchool['schoolname'];
		}
	}
    
    $street_array = $db->GetAssoc("select id,streetname from street where district='".$data_info['district']."'");
        if ($street_array != '') {
            $house['street'] = $empty + $street_array;
        } else {
            $house['street'] = $empty;
        }

}
$time = time();
$referer = $_SERVER['HTTP_REFERER'];
//print_r($_POST);
if ($action == 'insert') {
    //产生数据  
	$ss = getSchoolDataFromClient();
	/******************/
    //写入数据库
    $q = insert_sql($tbl, $ss);
	//echo $q;
	//exit;
    $db->Execute($q);

	//取得自增的id值
    $id = $db->Insert_ID(); //自增的用法
	if (in_array($conf_city,$schoolEnableCity)) {
		saveSchoolBlock($db,$tblSchoolBlock,array(),$id,$_POST['school_block_id'],$_POST['blockid'],$_POST['block_distance'],$_POST['louid']);

		saveSchoolPics($db,$tblSchoolImg,$p_filename,$p_imgtitle,$id,$p_fileid);
	}

    echo "<script>alert('提交成功!');window.opener.location.reload();window.close();</script>";
}

if ($action == 'update') {
    //产生数据  
    $ss = getSchoolDataFromClient();

    //写入数据库
    $q = update_sql($tbl, $ss, " where id=" . intval($id) . "");
	//exit;
    $db->Execute($q);
	if (in_array($conf_city,$schoolEnableCity)) {
		saveSchoolBlock($db,$tblSchoolBlock,array(),$id,$_POST['school_block_id'],$_POST['blockid'],$_POST['block_distance'],$_POST['louid']);
		saveSchoolPics($db,$tblSchoolImg,$p_filename,$p_imgtitle,$id,$p_fileid);
	}


    echo "<script>alert('提交成功!');window.opener.location.reload();window.close();</script>";
}


/* ------------------区属联动AJAX-------------------------- */
if ($action == 'getstreet') {
    $ss = '';
	$district = iconv('utf8', 'gbk', $district);
    if ($district != '' && $district != 'none') {
        $street_array = $db->GetAssoc("select id,streetname from street where district='$district'");
        if ($street_array != '') {
            $house['street'] = $empty + $street_array;
        } else {
            $house['street'] = $empty;
        }
        foreach ($house['street'] as $key => $value) {
            $ss.="<option value='" . $key . "'>" . $value . "</option>";
        }
        echo $ss;
    } else {
        echo "<option value=''>*请选择*</option>";
    }
    exit();
}

/*****************获取学校-中学*********************/
if ($action == 'getSchool') { 
	//print_r($_GET);
	$term = iconv('utf8', 'gbk', $term);
	$select = new Select();
	$select->add('id')->add('schoolname','value')->add('id');
	$schoolConf = new Conf();
	$schoolConf->add('schooltype','3');
	$rel = $school->getSchoolByKeyword($select,$schoolConf,$term);
	//print_r($rel);
	foreach($rel as &$v) {
		$v['value'] = iconv('GBK', 'UTF-8', $v['value']);
	}
	echo json_encode($rel);
	exit;
}
/*****************获取学校结束*********************/

/****************删除学校**********************/
if($action=='delSchool') {
	if($schoolId) {
		$sql = "delete from $tbl where id = '$schoolId'";
		$db->execute($sql);
		echo 1;
	} else {
		echo -1;
	}
	exit;
}
/****************删除学校结束**********************/

/****************删除多个学校**********************/
if($action=='delMutlSchool') {
	if($schoolIds) {
		$sql = "delete from $tbl where id in ($schoolIds)";
		$db->execute($sql);
		echo 1;
	} else {
		echo -1;
	}
	exit;
}
/****************删除多个学校结束**********************/


if ($action == 'del_pic' && $id != "") {

		$q = "update $tbl set coverphoto='' where id=$id";
		$db->Execute($q);

    echo "<script>alert('图片删除成功!');location.replace('" . $referer . "');</script>";
}

function getSchoolDataFromClient() {
	$ss = array();
    $ss["schoolname"] = $_POST['schoolname'];
    $ss["district"] = $_POST['district'];
	$ss["schooltype"] = $_POST['schooltype'];
	$ss["streetid"] = $_POST['streetid'];
	$ss["cbd"] = $_POST['cbd'];
	$ss["address"] = $_POST['address'];
	$ss["rank"] = $_POST['rank'];
	$ss["telno"] = $_POST['telno'];
	$ss["introduction"] = $_POST['introduction'];
	$ss["b_map_x"] = $_POST['b_map_x'];
	$ss["b_map_y"] = $_POST['b_map_y'];
	$ss["ispublic"] = $_POST['ispublic'];
	if($_POST['blockid']) {
	foreach($_POST['blockid'] as $key=>&$v) {
		if(!$v) {
			unset($_POST['blockid'][$key]);
			unset($_POST['block_distance'][$key]);
		}
		
	}
	//print_r($_POST['blockid']);print_r($_POST['block_distance']);exit;
	$ss["blockid"] = implode(",",$_POST['blockid']);
    } else {
    $ss["blockid"] = '';
    }
    if($_POST['block_distance']) {
	$ss["block_distance"] = implode(",",$_POST['block_distance']);
    }
	//$ss["coverphoto"] = $coverphoto;
	$ss["isshow"] = $_POST['isshow'];

	/******************/
	$ss['weight'] = $_POST['weight']?$_POST['weight']:9999;
	
	//学校类型是小学时填对应中学
	$ss['mid_school_name'] = $ss["schooltype"] ==2?$_POST['mid_school_name']:'';
	$ss['mid_school_id'] = $ss["schooltype"] ==2?$_POST['mid_school_id']:0;
	$ss['school_range'] = $_POST['school_range'];
	$ss['features'] = arrayToFeature($_POST['features']);//serialize($_POST['features']);
	$ss['school_year'] = $_POST['school_year'];
	$ss['school_area'] = $_POST['school_area'];
	$ss['class_number'] = $_POST['class_number'];
	$ss['student_number'] = $_POST['student_number'];
	$ss['teacher_intro'] = $_POST['teacher_intro'];
	$ss['website'] = $_POST['website'];
	$ss['bus_lines'] = $_POST['bus_lines'];
	$ss['subway'] = $_POST['subway'];
	$ss['street_map'] = $_POST['street_map'];
	
	//处理封面
	if($_POST['cover']) {
		$ss["coverphoto"] = str_replace("thumb/", "",$_POST['cover']);
	} else if($_POST['p_filename']) {
		//print_r($_POST['cover']);
		$ss["coverphoto"] = str_replace("thumb/", "",$_POST['p_filename'][0]);
	} else {
		$ss["coverphoto"] = '';
	}
	return $ss;
}

/**
 *@param $db
 *@param $tblSchoolImg 表名
 *@param $pics 图片地址的数组
 *@param $p_imgtitle 图片标题的数组
 *@param $picIds 图片id的数组
 *@param $id 学校ID
 */
function saveSchoolPics($db,$tblSchoolImg,$pics,$p_imgtitle,$id,$picIds) {
	$schoolImg = array();
	$schoolId = $id;
	//print_r($pics);
	//print_r($picIds);
	
	//var_dump($p_imgtitle);//图片名字

	//未删除的图片id
	$remainId= array();
	//新增加的图片id
	$newImg = array();
	//原来的图片id
	$orgIds = array();
	
	//初始化$remainId 和 $newImg
    if($picIds) {
	foreach($picIds as $key=>$id) {
		if($id) {
			$remainId[] = $id;
		} else {
			$temp['url'] = $pics[$key];
			$temp['title'] = $p_imgtitle[$key];
			//print_r($temp);
			$newImg[]=$temp;//$pics[$key];
		} 
	}
    }
	
	//初始化//初始化
	$orgPics = getSchoolPics($db,$tblSchoolImg,$schoolId);
    if($orgPics) {
	foreach($orgPics as $orgPic) {
		$orgIds[] = $orgPic['id'];
	}
	$delIds = array_diff($orgIds,$remainId);
    }
	//删除
	if($delIds) {
		$delSql = "delete from $tblSchoolImg where id in ('".implode("','",$delIds)."')";
		$db->execute($delSql);
	}
	
	//增加 新图片
	//print_r($newImg);
	if($newImg) {
		$schoolImg = array();
		foreach($newImg as $img) {
			$schoolImg['img_url']= $img['url'];
			$schoolImg['img_title'] = $img['title'];
			$schoolImg['school_id'] = $schoolId;
			$imgSql = insert_sql($tblSchoolImg, $schoolImg);
			$db->Execute($imgSql);
		}
		
	}
	//exit;
	/*
	foreach($pics as $key=>$pic) {
		$schoolImg['school_id'] = $schoolId;
		$schoolImg['img_url'] = $pic;

		if($picIds) {
			//删除 和增加
			//如果已有图片Id不在$picIds 中，del;
			
			//如果 $picIds 值为空的元素 insert 
			$imgSql = update_sql($tblSchoolImg, $schoolImg, " where id=" . intval($id) . "");
		} else {
			$imgSql = insert_sql($tblSchoolImg, $schoolImg);
		}
		$db->Execute($imgSql);
	}
	*/
	
}

/**
 *@param $db
 *@param $tblSchoolBlock 表名
 *@param $olderBlocks 已存在的学校小区数组
 *@param $schoolId 学校ID
 *@param $submitSchoolBlockIds SchoolBlock表ID的数组
 *@param $submitBlockIds 小区ID的数组
 *@param $submitBlockDistances 小区距离的数组
 */
function saveSchoolBlock($db,$tblSchoolBlock,$olderBlocks,$schoolId,$submitSchoolBlockIds,$submitBlockIds,$submitBlockDistances,$submitLous=null) {
	global $dbback;
	$schoolImg = array();
	//print_r($submitSchoolBlockIds);
	//print_r($submitBlockIds);
	//print_r($submitBlockDistances);
	//print_r($submitSchoolBlockIds);
	//未删除的小区id 和数据
	$remainId= array();
	$remains = array();
	//删除的小区
	$delId = array();
	//新增加的小区
	$newBlocks = array();
	//原来的id
	$orgIds = array();
	
	
	//初始化新增的小区 和 未删除的小区
    if($submitSchoolBlockIds) {
	foreach($submitSchoolBlockIds as $key=>$v) {
		if(!$v) {
		$temp = array();
		$temp['school_id'] = $schoolId;
		$temp['block_id'] = $submitBlockIds[$key];
		$temp['block_distance'] = $submitBlockDistances[$key];
        if($submitLous) {
            $temp['lou_id'] = $submitLous[$key];
        }
		$newBlocks[] = $temp;
		} else {
			$temp = array();
			$temp['school_id'] = $schoolId;
		$temp['block_id'] = $submitBlockIds[$key];
		$temp['id']=$v;
		$temp['block_distance'] = $submitBlockDistances[$key];
        if($submitLous) {
            $temp['lou_id'] = $submitLous[$key];
        }
		$remains[] = $temp;
		$remainId[]= $v;
		}
	}
    }
	global $uc;
	$sb = new SchoolBlock($db,$dbback,$uc);
	$olderBlocks = $sb->getAll($schoolId);
	//$olderBlocks = getSchoolBlock($db,$tblSchoolBlock,$schoolId);

	

	//删除的小区
	//初始化原来的id
    if($olderBlocks) {
	foreach($olderBlocks as $v) {
		$orgIds[] = $v['id'];
		if(!in_array($v['id'],$remainId)) {
			$delId[] = $v['id'];
		}
	}
    }
	
	//更新未删除的小区
	updateSchoolBlock($db,$tblSchoolBlock,$remains);

	//删除 要删除的小区
	delSchoolBlock($db,$tblSchoolBlock,$delId);

	//增加新添加的小区
	addSchoolBlock($db,$tblSchoolBlock,$newBlocks);
	//exit;
}

function updateSchoolBlock($db,$tblSchoolBlock,$remains) {
	//echo 'remainid-----';
	//print_r($remains);
	foreach($remains as $v ) {
		$id = $v['id'];
		unset($v['id']);
		$q = update_sql($tblSchoolBlock, $v, " where id=" . intval($id) . "");
		//exit;
		$db->Execute($q);
	} 
}

function delSchoolBlock($db,$tblSchoolBlock,$delId) {
	if($delId) {
		$sql = "delete from $tblSchoolBlock where id in ('".implode("','",$delId)."')";
		$db->execute($sql);
	}	
	//echo "delid";
	//print_r($delId);
}

function addSchoolBlock($db,$tblSchoolBlock,$newBlocks) {
	//print_r($newBlocks);
	foreach($newBlocks as $v) {
		$q = insert_sql($tblSchoolBlock, $v);
		//echo $q;
		//exit;
		$db->Execute($q);
	}
	
}

function getSchoolPics($db,$tblSchoolImg,$schoolId) {
	$schoolPics = array();
	if($schoolId) {
		$sql = "select * from $tblSchoolImg where school_id='$schoolId'";
		$schoolPics = $db->GetAssoc($sql);
	}
	//print_r($schoolPics);
	return $schoolPics;
}

function convGbkArrToUtfArr(&$schoolBlock) {
    if(is_array($schoolBlock)) {
        foreach($schoolBlock as &$v) {
            if(is_array($v)) {
                convGbkArrToUtfArr($v);
            } else {
                $v = iconv('GBK','UTF-8',$v);
            }
        }
    }
}

/*
function getSchoolBlock($db,$tblSchoolBlock,$schoolId) {
	$olderBlocks = array();
	if($schoolId) {
		$sql = "select * from $tblSchoolBlock where school_id='$schoolId'";
		$olderBlocks = $db->GetAssoc($sql);
	}
	//print_r($olderBlocks);
	return $olderBlocks;
}
*/
/* -------------------------------------------- */

//ALTER TABLE `school_block` ADD `lou_id` VARCHAR( 100 ) CHARACTER SET gbk COLLATE gbk_chinese_ci NULL DEFAULT '' COMMENT '楼号的字符串';
$nowCity = $_SESSION['esfadmin']['now_city'];

    $test = true;
$templateName = substr(basename ($_SERVER['SCRIPT_NAME']),0,-4);
include_once(Template("header"));
include_once(Template("xuequ/".$templateName));
include_once(Template("footer"));
?>