<?php

require_once(PLUGIN_DIR . 'Config.php');
require_once(PLUGIN_DIR . 'Tools/Image.php');

class SearchDao
{
    public static function ajax_searchCity()
    {
        wp_send_json(SearchDao::searchCity($_GET["cityId"], $_GET['districtId']));
    }

    public static function searchCity($cityId = NULL, $districtId = NULL)
    {
        global $wpdb;
        $selectName = "cityId as id,cityName as value";
        $where = " where 1=1 ";
        $groupBy = " group by cityId";
        $params = array();
        if ($cityId != NULL && $districtId == NULL) {
            $selectName = "districtId as id,districtName as value";
            $where .= " and cityId = %d";
            $params[] = $cityId;
            $groupBy = " group by districtId";
        } else if ($cityId != NULL && $districtId != NULL) {
            $selectName = "plateId as id,plateName as value";
            $where .= " and cityId = %d and districtId = %d";
            $params[] = $cityId;
            $params[] = $districtId;
            $groupBy = "";
        }
        $result = $wpdb->get_results($wpdb->prepare('select ' . $selectName . ' from ' . Config::DIC_CITY_TABLE . $where . $groupBy, $params));
        return $result;
    }

    public static function ajax_searchArea()
    {
        wp_send_json(SearchDao::searchArea($_GET['cityId']));
    }

    public static function searchArea($cityId)
    {
        global $wpdb;
        $where = " where 1=1";
        if (isset($_GET['cityId'])) {
            $where .= " and cityId = %d";
        }
        $result = $wpdb->get_results($wpdb->prepare('select id,priceValue as value from ' . Config::DIC_AREA_TABLE . $where, $cityId));
        return $result;
    }

    public static function ajax_searchBuildProperty()
    {
        wp_send_json(SearchDao::searchBuildProperty());
    }

    public static function searchBuildProperty()
    {
        global $wpdb;
        $result = $wpdb->get_results('select value as id,literal as value from ' . Config::DIC_BUILDPROPERTY_TABLE);
        return $result;
    }

    public static function ajax_searchRoom()
    {
        wp_send_json(SearchDao::searchRoom());
    }

    public static function searchRoom()
    {
        global $wpdb;
        $result = $wpdb->get_results('select value as id,literal as value from ' . Config::DIC_ROOM_TABLE);
        return $result;
    }

    public static function ajax_searchUnitPriceRange()
    {
        wp_send_json(SearchDao::searchUnitPriceRange($_GET['cityId']));
    }

    public static function searchUnitPriceRange($cityId)
    {
        global $wpdb;
        $where = " where 1=1";
        if (isset($_GET['cityId'])) {
            $where .= " and cityId = %d";
        }
        $result = $wpdb->get_results($wpdb->prepare('select id,priceValue as value from ' . Config::DIC_UNITPRICERANGE_TABLE . $where, $cityId));
        return $result;
    }

    public static function ajax_searchTotalPrice()
    {
        wp_send_json(SearchDao::searchTotalPrice($_GET['cityId']));
    }

    public static function searchTotalPrice($cityId)
    {
        global $wpdb;
        $where = " where 1=1";
        if ($cityId) {
            $where .= " and cityId = " . $cityId;
        }
        $result = $wpdb->get_results($wpdb->prepare('select id,priceValue as value from ' . Config::DIC_TOTALPRICE_TABLE . $where, $cityId));
        return $result;
    }

    public static function ajax_searchRentalPrice()
    {
        wp_send_json(SearchDao::searchRentalPrice($_GET['cityId']));
    }

    public static function searchRentalPrice($cityId)
    {
        global $wpdb;
        $where = " where 1=1";
        if ($cityId) {
            $where .= " and cityId = " . $cityId;
        }
        $result = $wpdb->get_results($wpdb->prepare('select id,priceValue as value from ' . Config::DIC_RENTALPRICE_TABLE . $where, $cityId));
        return $result;
    }

    public static function ajax_searchOrganization()
    {
        wp_send_json(SearchDao::searchOrganization($_GET['parentId']));
    }

    public static function searchOrganization($parentId = NULL)
    {
        global $wpdb;
        $where = " where 1=1 ";
        if ($parentId != NULL) {
            $where .= " and ParentId =" . $parentId;
        }
        $result = $wpdb->get_results($wpdb->prepare('select Id as id,Name as name from ' . Config::TOSPUR_ORGANIZATION_TABLE . $where, $parentId));
        return $result;
    }

    public static function getCityNameWithId($cityId)
    {
        global $wpdb;
        $result = $wpdb->get_var($wpdb->prepare("select cityName from " . Config::DIC_CITY_TABLE . " where cityId = %d", $cityId));
        if ($result) {
            return $result;
        } else {
            return "未知";
        }
    }

	public static function ajax_searchHouse()
	{
		$house_result = SearchDao::searchHouse(
			array(
				'cityId' => $_POST['cityId'],
				'districtId' => $_POST['districtId'],
				'plateId' => $_POST['plateId'],
				'buildPropertyId' => $_POST['buildPropertyId'],
				'roomId' => $_POST['roomId'],
				'acreage' => $_POST['acreage'],
				'totalPrice' => $_POST['totalPrice'],
				'rentalPrice' => $_POST['rentalPrice'],
				'searchText' => $_POST['searchText'],
				'houseType' => $_POST['houseType'],
				'feature' => $_POST['feature'],
				'userType' => $_POST['userType'],
				'userId' => $_POST['userId'],
				'index' => $_POST['index']
			)
		);
		$array = SearchDao::get_house_image_and_tags($house_result);
		wp_send_json($array);
	}

	public static function searchHouse($array)
	{
		global $wpdb;
		$params = array();
		$addSql = null;
		$addWhereSql = null;
		$orderbySql = null;
		if ($array['houseType'] == 0) {
			$addSql = " left join (select buildproperty_id,house_area,image_id,house_id as bph_id from a_district_area) ada on th.id = ada.bph_id".
			          " left join (select value as bp_value,literal as bp_literal from dic_buildproperty) dbp on ada.buildproperty_id = dbp.bp_value";
			$orderbySql = " group by ada.bph_id order by th.creattime DESC";
		}else if ($array['houseType'] == 1) {
			$addSql = " left join (select value as bp_value,literal as bp_literal from dic_buildproperty) dbp on th.buildproperty_id = dbp.bp_value";
			if ($array['feature'] > -1) {
				$addSql .= " left join (select house_id,tag_id from a_house_tag) aht on th.id = aht.house_id";
				$addWhereSql = " and tag_id = ".$array['feature'];
			}
			$orderbySql = " order by th.creattime DESC";
		}else if($array['houseType'] == 2){
			$addSql = " left join (select value as bp_value,literal as bp_literal from dic_buildproperty) dbp on th.buildproperty_id = dbp.bp_value";
			$orderbySql = " order by th.creattime DESC";
		}
		$sql = "select * from tospur_house th".
		       $addSql.
		       " left join dic_city dc on th.plate_id = dc.plateId".
		       " left join (select id as rid,value as r_value,literal from dic_room) dr on th.room_id = dr.r_value".
		       " where 1=1";
		if ($array['cityId'] > -1) {
			$params[] = $array['cityId'];
			$sql = $sql . " and cityId=%d";
		}
		if ($array['districtId'] > -1) {
			$params[] = $array['districtId'];
			$sql = $sql . " and districtId=%d";
		}
		if ($array['plateId'] > -1) {
			$params[] = $array['plateId'];
			$sql = $sql . " and plateId=%d";
		}
		if ($array['buildPropertyId'] > -1) {
			$params[] = $array['buildPropertyId'];
			$sql = $sql . " and buildproperty_id=%d";
		}
		if ($array['roomId'] > -1) {
			$params[] = $array['roomId'];
			$sql = $sql . " and room_id=%d";
		}
		if ($array['acreage'] > -1) {
			$areaArray = explode("-", $array['acreage']);
			$params[] = $areaArray[0];
			$params[] = $areaArray[1];
			$sql = $sql . " and covered_area between %d and %d";
		}
		if ($array['totalPrice'] > -1) {
			$priceArray = explode("-", $array['totalPrice']);
			$params[] = $priceArray[0];
			$params[] = $priceArray[1];
			$sql = $sql . " and total_price between %d and %d";
		}
		if ($array['rentalPrice'] > -1) {
			$priceArray = explode("-", $array['rentalPrice']);
			$params[] = $priceArray[0];
			$params[] = $priceArray[1];
			$sql = $sql . " and rent between %d and %d";
		}
		if ($array['houseType'] > -1) {
			$params[] = $array['houseType'];
			$sql = $sql . " and house_type = %d";
		}
		if ($array['userType'] > -1 && $array['userId'] > -1) {
			$params[] = $array['userType'];
			$params[] = $array['userId'];
			$sql = $sql . " and id in (select house_id from a_house_user where user_type = %d and user_id = %d)";
		}
		if ($array['searchText'] != null) {
			$params[] = '%'.$array['searchText'].'%';
			$params[] = '%'.$array['searchText'].'%';
			$sql = $sql . " and (name like '%s' or address like '%s')";
		}

		if($addWhereSql){
			$sql = $sql . $addWhereSql;
		}
		$sql = $sql . $orderbySql;

		if ($array['index'] > -1) {
			$params[] = $array['index'];
			$sql = $sql . " limit %d,10";
		}
		$result = $wpdb->get_results($wpdb->prepare($sql, $params));
		return $result;
	}

    public static function ajax_searchPhotoType()
    {
        wp_send_json(SearchDao::searchPhotoType());
    }

    public static function searchPhotoType()
    {
        global $wpdb;
        $result = $wpdb->get_results('select id,photo_name as value from ' . Config::DIC_PHOTOTYPE_TABLE);
        return $result;
    }
    
        public static function ajax_searchConsultant(){
        wp_send_json(SearchDao::searchConsultant($_GET["consulCityId"],$_GET["consultantName"]));
    }

    public static function searchConsultant($consulCityId = NULL,$consultantName = NULL){
        global $wpdb;
        $sql = "select id,name as consultantName,imageUrl from  ".Config::TOSPUR_CONSULTANT." where 1=1";
        $params = array();
        if($consulCityId != NULL){
            $params[] = $consulCityId;
            $sql = $sql." and cityId=%d";
        }
        if($consultantName != NULL){
            $params[] = '%'.$consultantName.'%';
            $sql = $sql." and name  like %s";
        }
        $result = $wpdb->get_results($wpdb->prepare($sql,$params));
        return $result;
    }

    public static function get_house_image_and_tags($house_result)
    {
        $array = array();
        if ($house_result) {
            $array['code'] = 2000;
            $house_ids = array();
            foreach ($house_result as $key => $value) {
                $house_id = $value->id;
                $house_ids[] = $house_id;
            }
            $tag_result = SearchDao::search_house_tag($house_ids);
            //标签
            if ($tag_result) {
                foreach ($tag_result as $key => $value) {
                    $array['tags'][$value->house_id][] = $value->name;
                }
            }
            //图片
            $image_result = SearchDao::search_house_image($house_ids);
            if ($image_result) {
                foreach ($image_result as $key => $value) {
                    $array['images'][$value->house_id] = home_url() . Image::getImage($value->path,'small');
                }
            }
            $array['result'] = $house_result;
        } else {
            $array['code'] = 2001;
        }
        return $array;
    }

    public static function search_house_image($house_ids)
    {
        $string = '(' . implode(',', array_map('intval', $house_ids)) . ')';
        $sql = 'select * from (select ahi.house_id,ti.path,ti.image_type,case ti.image_type ' .
            'when 1 then 1 ' .
            'when 5 then 1 ' .
            'ELSE 2 ' .
            'end as type from ' . Config::A_HOUSE_IMAGE_TABLE . ' ahi ' .
            'left join ' . Config::TOSPUR_IMAGE_TABLE . ' ti on ahi.image_id = ti.id ' .
            'where house_id in ' . $string . ' order by type) as image group by house_id;';
        global $wpdb;
        return $wpdb->get_results($sql);
    }

	public static function search_house_tag($house_ids)
	{
		$string = '(' . implode(',', array_map('intval', $house_ids)) . ')';
		$sql = 'select aht.house_id,tt.name from ' . Config::A_HOUSE_TAG_TABLE . ' aht' .
		       ' left join ' . Config::TOSPUR_TAG_TABLE . ' tt on aht.tag_id = tt.id' .
		       ' where house_id in ' . $string . ' and tt.type = 0;';
		global $wpdb;
		return $wpdb->get_results($sql);
	}

	public static function searchFeature()
	{
		$sql = 'select id,name as value from '.Config::TOSPUR_TAG_TABLE.' where type = 1;';
		global $wpdb;
		return $wpdb->get_results($sql);
	}

	public static function setHouseNumber($houseId,$houseType,$cityId){
        global $wpdb;
        switch($houseType){
            case 0:
                $prefix = "xf";
                break;
            case 1:
                $prefix = "CS";
                break;
            case 2:
                $prefix = "CZ";
                break;
        }
        $house_number = $prefix.str_pad($cityId,4,'0',STR_PAD_LEFT).str_pad($houseId,8,'0',STR_PAD_LEFT);
        return $wpdb->update(Config::TOSPUR_HOUSE_TABLE,
            array(
                'house_number' => $house_number
            ),
            array(
                "id" => $houseId
            )
        );
    }

    public static function getDetailInfo($hid,$type = NULL){
        global $wpdb;
        $sql = "select * from ".Config::TOSPUR_HOUSE_TABLE." where id = %d";
        $result = $wpdb->get_row($wpdb->prepare($sql,$hid));
        $context = array();
        $context['result'] = $result;
        $houseType = $result->house_type;
        $context['cityName'] = SearchDao::getCityNameWithId($result->city_id);
        $consultantLimit = 1;
        if($houseType == 0){
            $consultantLimit = 5;
            $mainImagesSql = "SELECT ti.id,ada.buildproperty_id,db.literal as type,ada.house_area as area,ti.path FROM ".Config::A_DISTRICT_AREA_TABLE." ada
            LEFT JOIN ".Config::DIC_BUILDPROPERTY_TABLE." db on db.value = ada.buildproperty_id
            LEFT JOIN ".Config::TOSPUR_IMAGE_TABLE." ti on ti.id = ada.image_id
            where ada.house_id = %d";
            $mainImage = $wpdb->get_results($wpdb->prepare($mainImagesSql,$hid));
            foreach($mainImage as $key => $value){
                $value->path = Image::getImage($value->path,'small');
            }
            $context['mainImage'] = $mainImage;
        }

        $recommendSql = "select ahi.house_id as id,ti.path from a_house_image ahi
            left join tospur_image ti on ahi.image_id = ti.id
            where ti.image_type in (1,5) and house_id
            in (select recommend_id from a_house_recommend where house_id = %d) group by house_id";
        $recommends = $wpdb->get_results($wpdb->prepare($recommendSql,$hid));
        if(count($recommends) == 0){
            $recommendSql = "select ahi.house_id as id,ti.path from a_house_image ahi
            left join tospur_image ti on ahi.image_id = ti.id
            where house_id in (select recommend_id from a_house_recommend where house_id = %d) group by house_id";
            $recommends = $wpdb->get_results($wpdb->prepare($recommendSql,$hid));
        }
        foreach($recommends as $key => $value){
            $value->path = Image::getImage($value->path,'small');
        }
        $context['recommends'] = $recommends;

        $consultantSql = "select id,name,mobile,imageUrl,s.average_score from tospur_consultant c
            LEFT JOIN (select consultant_id,sum(score)/count(score) as average_score
            from tospur_consultant_score
            where valid=1 group by consultant_id) s on c.id = s.consultant_id
            where id in(select user_id from a_house_user where user_type = 1 and house_id = %d) limit {$consultantLimit};";
        $consultant = $wpdb->get_results($wpdb->prepare($consultantSql,$hid));
        $context['consultant'] = $consultant;

        if($type == 'edit'){
            $imagesSql = 'select * from a_house_image ahi
            LEFT JOIN tospur_image ti on ti.id = ahi.image_id
            where ahi.house_id = %d and ahi.image_id not in (select image_id from a_district_area where house_id = %d);';
        }else{
            $imagesSql = 'select * from tospur_image ti
            LEFT JOIN a_house_image ahi on ti.id = ahi.image_id
            WHERE ahi.house_id = %d order by image_type;';

        }
        $images = $wpdb->get_results($wpdb->prepare($imagesSql,$hid,$hid));
        foreach($images as $key => $value){
            $value->path = Image::getImage($value->path,'big');
        }
        $context['images'] = $images;


        return $context;
    }

    public static function searchHouseTag($houseId){
        global $wpdb;
        $sql = "select tt.name from a_house_tag aht
        LEFT JOIN tospur_tag tt on aht.tag_id = tt.id
        where aht.house_id = %d;";
        $results = $wpdb->get_results($wpdb->prepare($sql,$houseId));
        $tags = array();
        foreach($results as $item){
            $tags[] =$item->name;
        }
        return implode(",",$tags);
    }

    public static function searchStatusType($statusType){
        global $wpdb;
	    $sql="select status_id as id,status_name as value from tospur_status where status_type = %d";
        $results = $wpdb->get_results($wpdb->prepare($sql,$statusType));
        return $results;

    }
}