<?php 
class CmsApi {
    static public $methods = array('getBlock','getSellHouse','blockPic','getTerm','insertBlockPic','blockPicSearch','getSpBlock','blockPicDel');
    public function __construct() {
        
    }

    static public function getBlock(){
        global $dbback;
        $blcokTable = 'block';
        $blockName = mysql_real_escape_string($_GET['blockName']);
        $resultType = intval($_GET['resultType']);
        $result = array();
        if(!$blockName) {
            $result['result'] ='error';
            $result['msg'] = '缺少参数:"blockName"！';
            //return serialize($result);
        } else {
        $sql = "select id,blockname,district,streetid,area,address,averprice,b_img from $blcokTable where  esta = 2 and blockname like '%$blockName%'";
        $block = $dbback->getAll($sql);
        if($block) {
            $result['result'] = 'success';
            //$result['block'] = $block;
            $barr = array();
            $domain = 'http://'.$_GET['city'].'.sell.house365.com';
            foreach($block as $b) {
                $bid = $b['id'];
                $temp['id'] = $b['id'];
                $temp['blockname'] = $b['blockname'];
                $temp['district'] = $b['district'];
                $temp['streetid'] = $b['streetid'];
                $temp['area'] = $b['area'];
                $temp['address'] = $b['address'];
                $temp['averprice'] = $b['averprice'];
                $temp['b_img'] = $b['b_img'];
                $temp['sell_url'] = $domain.'/xq_'.$bid.'/esf.html';
                $temp['rent_url'] = $domain.'/xq_'.$bid.'/zufang.html';
                if($_GET['city'] == 'nj') {
                    $temp['huxingtu_url'] = $domain.'/xq_'.$bid.'/huxingtu.html';
                    $temp['tuku_url'] = $domain.'/xq_'.$bid.'/xiangce.html';
                } else {
                    $temp['huxingtu_url'] = $domain.'/xq_'.$bid.'/xiangce.html';
                    $temp['tuku_url'] = $domain.'/xq_'.$bid.'/xc_b1.html';
                }
                $temp['streetname'] = get_block_street_name($temp['streetid']);
                $barr[] = $temp;
            }
            $result['block'] = $barr;
            //return serialize($result);
        } else {
            $result['result'] ='error';
            $result['msg'] = '未找到名字包含"'.$blockName.'"的小区！';
            //return serialize($result);
        }
        }
        return self::formatResult($result,$resultType);
    }
    
    /**
     *因为CMS服务器DNS解析的问题，此api转移到api服务器了。
     */
    static public function getSpBlock(){
        global $dbback;
        global $conf_house;
        $dists = array_keys($conf_house['district']);
        $blcokTable = 'block';
        $blockName = mysql_real_escape_string($_GET['blockName']);
        $resultType = intval($_GET['resultType']);
        $result = array();
        if(!$blockName) {
            $result['result'] ='error';
            $result['msg'] = '缺少参数:"blockName"！';
            //return serialize($result);
        } else {
        $sql = "select id,blockname,district,streetid,area,address,averprice,b_img from $blcokTable where  esta = 2 and blockname ='$blockName'";
        $block = $dbback->getAll($sql);
        if($block) {
            $result['result'] = 'success';
            //$result['block'] = $block;
            $barr = array();
            $domain = 'http://'.$_GET['city'].'.sell.house365.com';
            foreach($block as $b) {
                $bid = $b['id'];
                $temp['id'] = $b['id'];
                $temp['blockname'] = $b['blockname'];
                $temp['district'] = $b['district'];
                $temp['streetid'] = $b['streetid'];
                $temp['area'] = $b['area'];
                $temp['address'] = $b['address'];
                $temp['b_img'] = $b['b_img'];
                $temp['averprice'] = $b['averprice'];
                $temp['url'] = $domain.'/xq_'.$bid.'/';
                $temp['sell_url'] = $domain.'/xq_'.$bid.'/esf.html';
                $temp['rent_url'] = $domain.'/xq_'.$bid.'/zufang.html';
                if($_GET['city'] == 'nj') {
                    $temp['huxingtu_url'] = $domain.'/xq_'.$bid.'/huxingtu.html';
                    $temp['tuku_url'] = $domain.'/xq_'.$bid.'/xiangce.html';
                } else {
                    $temp['huxingtu_url'] = $domain.'/xq_'.$bid.'/xiangce.html';
                    $temp['tuku_url'] = $domain.'/xq_'.$bid.'/xc_b1.html';
                }
                
                $temp['jiage_url'] = $domain.'/xq_'.$bid.'/jiage.html';
                $distNumber = array_search($b['district'],$dists)+1;
                $temp['dist_url'] = $domain.'/xl_d'.$distNumber.'.html';
                $temp['streetname'] = get_block_street_name($temp['streetid']);
                $temp['house'] = self::getSellHouseAbs($bid,$resultType,3);
                $barr[] = $temp;
                break;
            }
            $result['block'] = $barr;
            //return serialize($result);
        } else {
            $result['result'] ='error';
            $result['msg'] = '未找到名字包含"'.$blockName.'"的小区！';
            //return serialize($result);
        }
        }
        cmsApiLog($result);
        return self::formatResult($result,$resultType);
    }

    static public function getTerm(){
        global $dbback;
        $blcokTable = 'block';//echo urldecode($_GET['term']);
        $blockName = urlencodingStringToUtf8($_GET['term']);
        $resultType = intval($_GET['resultType']);
        $result = array();
        if(!$blockName) {
            $result['result'] ='error';
            $result['msg'] = '缺少参数:"blockName"！';
            //return serialize($result);
        } else {
            $sqlblockname = mysql_real_escape_string($blockName);
        $sql = "select id,blockname,district,streetid,area,address,averprice from $blcokTable where  esta = 2 and blockname like '%$sqlblockname%'";
        $block = $dbback->getAll($sql);
        if($block) {
            $result = array();
            //$result['result'] = 'success';
            foreach($block as $v) {
                $temp= array();
                $temp['id']= $v['id'];
                $temp['label']= $v['blockname'];
                $result[] = $temp;
            }
            //$result = $block;
            //return serialize($result);
        } else {
            $result['result'] ='error';
            $result['msg'] = '未找到名字包含"'.$blockName.'"的小区！';
            //return serialize($result);
        }
        }
        return self::formatResult($result,$resultType);
    }

    static public function insertBlockPic() {
        print_r($_REQUEST);
    
    }
    static public function getSellHouse(){
        global $sell_server;
        global $dbback;
        $blockId = intval($_GET['blockid']);
        $resultType = intval($_GET['resultType']);
        return self::formatResult(self::getSellHouseAbs($blockId,$resultType),$resultType);
        //print_r($ary);
    }
    
    static public function getSellHouseAbs($blockId,$resultType,$number=15){
        global $sell_server;
        global $dbback;
        //$blockId = intval($_GET['blockid']);
        //$resultType = intval($_GET['resultType']);
        $result = array();
        if(!$blockId) {
            $result['result'] ='error';
            $result['msg'] = '缺少参数："小区ID"！';
        }else {
            //id,infofrom,district,creattime,address,blockid,blockshowname,buildarea,subfloor,floor,totalfloor,room,hall,renttype,remark,price,priceunit,updatetime,agentcode,uid,pic1,topic,isstar,istag,housekind,tradeclass,forward,fitment,contactor
            $fileds = 'ID,ADDRESS,BUILDAREA,PRICE,UID,ROOM,hall,toilet,kitchen';
            $q="select $fileds from sell where blockid='$blockId' and infofrom=5 order by updatetime desc limit 0, $number luc";
	        $ary = $sell_server->query($q);
            if($ary['MSG']=='ok') {
                $brokerid = array();
                $broker = array();
                if($ary['Record']) {//发布者
                    foreach($ary['Record'] as $v) {
                        $brokerid[] = $v['UID'];
                    }
                }
                if($brokerid) {
                    $brokerid = implode("','",array_unique($brokerid));
                    $qbroker = "select uid,truename,username,agentcode from broker where uid in('$brokerid') ";
                    $brokerTemp = $dbback->getAll($qbroker);
                    if($brokerTemp) {
                        foreach($brokerTemp as $b) {
                            $broker[$b['uid']] = $b;
                        }
                    }
                }
                //print_r($broker);exit;
                if($ary['Record']) {
                    foreach($ary['Record'] as &$r) {
                        $r['UNAME'] = $broker[$r['UID']]['truename'];
                        //添加房源地址
                        $domain = 'http://'.$_GET['city'].'.sell.house365.com';
                        $r['HOUSE_URL'] = $domain.'/s_'.$r['ID'].'.html';
                        //户型
                        $r['HUXING'] = '';
                        if($r['ROOM']) $r['HUXING'] .= $r['ROOM'].'室';
                        if($r['HALL']) $r['HUXING'] .= $r['HALL'].'厅';
                        if($r['TOILET']) $r['HUXING'] .= $r['TOILET'].'卫';
                        if($r['KITCHEN']) $r['HUXING'] .= $r['KITCHEN'].'厨';
                        //均价
                        if($r['BUILDAREA']>0){
                        $r['AVEPRICE'] = number_format ($r['PRICE']/$r['BUILDAREA']*10000,0,'.','');
                        $r['AVEPRICE'] .= '元/平米';
                        } else {
                        $r['AVEPRICE'] = '暂无均价';
                        }
                        
                    }
                }
                //print_r($ary['Record']);exit;
                $result['result'] = 'success';
                $result['sellHouse'] = $ary['Record'];
            } else {
                $result['result'] ='error';
                $result['msg'] = '中间件或sql出错！';
            }
        }
        return $result;
    }

    static public function blockPic() {
        global $conf_basedir;
        global $db;
        $city = $_GET['city'];
        	//if ($actiontype) doaction($actiontype,$actionid);

        $dwz_theme = 'default';
        $css="<link href='http://esfadmin.house365.com/script/css/autocomplete.css' rel='stylesheet' type='text/css' />
         <link rel='stylesheet' type='text/css' href='http://www.house365.com/public/js/swf/default1.css'  />";
        $jsfieles = array(
        'http://esfadmin.house365.com/script/js/showpic.js',
        'http://esfadmin.house365.com/script/js/public.js',
        'http://esfadmin.house365.com/script/js/formValidator.js',
        'http://esfadmin.house365.com/script/js/jquery_ui_autocomplete/ui/jquery.ui.core.js',
        'http://esfadmin.house365.com/script/js/jquery_ui_autocomplete/ui/jquery.ui.position.js',
        'http://esfadmin.house365.com/script/js/jquery_ui_autocomplete/ui/jquery.ui.widget.js',
        'http://esfadmin.house365.com/script/js/jquery_ui_autocomplete/ui/jquery.ui.autocomplete.js',
        'http://esfadmin.house365.com/script/js/swf/swfupload.js',
        'http://esfadmin.house365.com/script/js/handlers.js');
        $js = self::loadJs($jsfieles);
        $tbl='block_img';
        $action = $_GET['action']?$_GET['action']:'add';

        //print_r($_POST);exit;
        $p_filename = $_POST['p_filename'];
        if ($p_filename) {
            foreach ($p_filename as $key => $value) {
                //产生数据
                $ss = array();
                $ss["bi_title"] = $_POST['bi_title'];
                $ss["bi_img"] = $value;
                $ss["bi_blockid"] = $_POST['bi_blockid'];
                $ss["bi_type"] = $_POST['bi_type'];
                $ss["bi_add_time"] = time();
                $ss["bi_room"] = intval($_POST['bi_room']);
                $ss["bi_hall"] = intval($_POST['bi_hall']);
                $data_info = $ss; //返回值
                //写入数据库
                $q = insert_sql($tbl, $ss);
                $db->Execute($q);
             }
             
             echo "<script>alert('提交成功!');window.opener.location.reload();window.close();</script>";
             //echo "<script>alert('提交失败!请上传图片');window.opener.location.reload();window.close();</script>";

        } else {
            
            //exit;
        }




    //引用模版文件
    include_once(Template("header"));
    include_once(Template("cms_api/block_pic_add"));
    include_once(Template("footer"));
    }

    static public function blockPicSearch() {
        global $conf_basedir;
        global $dbback;
        $dwz_theme = 'default';
        $css="<link href='http://esfadmin.house365.com/script/css/autocomplete.css' rel='stylesheet' type='text/css' />
         <link rel='stylesheet' type='text/css' href='http://www.house365.com/public/js/swf/default1.css'  /><link href='http://esfadmin.house365.com/script/css/jquery.fancybox.css' rel='stylesheet' type='text/css' />";
        $jsfieles = array(
        'http://esfadmin.house365.com/script/js/showpic.js',
        'http://esfadmin.house365.com/script/js/public.js',
        'http://esfadmin.house365.com/script/js/formValidator.js',
        'http://esfadmin.house365.com/script/js/jquery_ui_autocomplete/ui/jquery.ui.core.js',
        'http://esfadmin.house365.com/script/js/jquery_ui_autocomplete/ui/jquery.ui.position.js',
        'http://esfadmin.house365.com/script/js/jquery_ui_autocomplete/ui/jquery.ui.widget.js',
        'http://esfadmin.house365.com/script/js/jquery_ui_autocomplete/ui/jquery.ui.autocomplete.js',
        'http://esfadmin.house365.com/script/js/swf/swfupload.js',
        'http://esfadmin.house365.com/script/js/handlers.js',
            'http://esfadmin.house365.com/script/js/jquery.fancybox.pack.js');
        $js = self::loadJs($jsfieles);

        $blockImgTbl = 'block_img';
        $method = $_GET['method'];
        $city = $_GET['city'];
        $blockid = intval($_GET['blockid']);
        $bi_type = intval($_GET['type']);
        $blockName = $_GET['blockname'];
        $bi_typeArr= array();
        $bi_typeArr["999"]	="请选择";
        $bi_typeArr["0"]	="户型图";
        $bi_typeArr["51"]	="小区正门";
        $bi_typeArr["52"]	="外立面";
        $bi_typeArr["53"]	="小区环境";
        $bi_typeArr["54"]	="内部设施";
        $bi_typeArr["55"]	="周边配套";
        $bi_typeArr["56"]	="小区评测";
        $blockPic = null;
        $blockPicNumber = 0;
        if($blockid) {
            $conf = "bi_blockid = '$blockid'";
            if($bi_type!=999) {
                $conf .= " and bi_type='$bi_type' ";
            }
            $sql = "select id,bi_title,bi_img,bi_big_img,bi_type from $blockImgTbl where $conf order by id desc";
            $blockPic = $dbback->getAll($sql);
            if($blockPic) { $blockPicNumber = count($blockPic); }
        }
        
        include_once(Template("header"));
        include_once(Template("cms_api/block_pic_search"));
        include_once(Template("footer"));
    }
    
    static public function blockPicDel() {
        global $conf_basedir;
        global $db;
        //暂时 不要
        exit;
        $method = $_GET['method'];
        $city = $_GET['city'];
        $id = intval($_GET['id']);
        if($id) {
        $blockImgTbl = 'block_img';
        $sql = "delete from $blockImgTbl where id='$id'";
        $blockPic = $db->execute($sql);
            echo 1;
        } else {
            echo -1;
        }

    }

    /**
     *
     */
    static public function formatResult(&$result,$type) {
        if($type==1) {
            return serialize($result);
        } else{
            self::gbk2uft8($result);
            //print_r($result);
            return json_encode($result);
        }
    }
    
    /**
     *
     */
    static public function gbk2uft8(&$data){
        if(is_array($data)) {
            foreach($data as $key=>&$v) {
                self::gbk2uft8($v);
            }
        } else {
            $data = iconv('gbk','utf8',$data);
        }
    }

    static public function loadJs(array $files) {
		foreach($files as $v) {
			$jsHtml .= '<script type="text/javascript" src="'.$v.'"></script>';
		}
		return $jsHtml;
	}
}

function getBi_typeString($bi_typeArr,$typeid){//echo $typeid;
    if($typeid==999||!in_array($typeid,array_keys($bi_typeArr))) {
        return "未分类图片";
    } else {
        return $bi_typeArr[$typeid];
    }
    
}
function get_block_street_name($streetid){
    global $dbback,$mc;
    $sql = "select id,streetname from street";
    $mcKey = md5($sql);
    $streets = array();
    if(!$streets = $mc->get($mcKey)) {
      $tempStreets = $dbback->getAll($sql);
      if($tempStreets) {
        foreach($tempStreets as $ts) {
            $streets[$ts['id']] = $ts['streetname'];
        }
      }
      $mc->set($mcKey,$streets,MEMCACHE_COMPRESSED,60*60*24);
    }
    if(array_key_exists($streetid,$streets)) {
        return $streets[$streetid];
    } else {
        return false;
    }
    
    
}

function urlencodingStringToUtf8($string) {
	$string = urldecode($string);
	$kcode = mb_detect_encoding($string,'UTF-8,GBK,GB2312,CP936');
	if($kcode!='GBK') {
		$string = iconv($kcode,'GBK',$string);
	}
	return $string;
}


?>