<?php
class House {
    public static function init_view(){
        wp_enqueue_script('jquery-ui');
        wp_enqueue_script('bootstrapjs');
        wp_enqueue_style('jquery-ui_css');
        wp_enqueue_style('bootstrapcss');

        if(isset($_GET["updated"])){
            echo "updated success";
        }else{
            global $wpdb;
            $context = array();
            $citysql ="select DISTINCT cityId,cityName from";
            $cityRes =  $wpdb->get_results($citysql.' dic_city');
            foreach($cityRes as $value){
                $cityParams = array(
                    "cityId" => $value->cityId,
                    "cityName" => $value->cityName
                );
                $context["city"][] = $cityParams;
            }
            $sql = "select * from";
            $buildpropertyRes =  $wpdb->get_results($sql.' dic_buildproperty');
            foreach($buildpropertyRes as $v){
                $buildpropertyParams = array(
                    "value" => $v->value,
                    "literal" => $v->literal
                );
                $context["buildproperty"] []= $buildpropertyParams;
            }

            $buildpropertyRes =  $wpdb->get_results($sql.' dic_room');
            foreach($buildpropertyRes as $v){
                $roomParams = array(
                    "value" => $v->value,
                    "literal" => $v->literal
                );
                $context["room"] []= $roomParams;
            }
            House::data_insert();
            Timber::render("newhouse.html",$context);
        }
    }

    public static function data_insert(){
        global $wpdb;
        date_default_timezone_set("Etc/GMT-8");;
        //图片信息
        $uploadedfile = $_FILES['files'];
        //房源与类型以及面积信息
        $data = $_POST["data"];
        //获取新房信息，存入tospur_house表
        $insert_tospur_house_array = array(
            'name' => $_POST['name'],
            'average_price' => $_POST['average_price'],
            'latest_news' => $_POST['event'],
            'address' => $_POST['address'],
            'traffic' => $_POST['traffic'],
            'periphery' => $_POST['periphery'],
            'developer' => $_POST['developers'],
            'check_in_time' => $_POST['check_in_time'],
            'building_type' => $_POST['building_type'],
            'property_age' => $_POST['property_age'],
            'decoration' => $_POST['decoration'],
            'covered_area' => $_POST['acreage'],
            'volume_rate' => $_POST['volume_rate'],
            'greening_rate' => $_POST['greening_rate'],
            'households' => $_POST['households'],
            'parking_spaces' => $_POST['parking_spaces'],
            'property_management' => $_POST['property_management'],
            'overview' => $_POST['overview'],
            'plate_id'=>$_POST["basePlateId"],
            "room_id"=>$_POST["baseRoom"],
            "property_money" =>$_POST["property_money"],
            'creattime'=>date("Y-m-d H:i:s")
        );
        $res = $wpdb->get_results( 'SELECT * FROM tospur_house WHERE name="'.$_POST['name'].'" and address="'.$_POST['address'].'"', OBJECT );
        if(!$res){
            $houseRes = $wpdb->insert('tospur_house', $insert_tospur_house_array);
            if(!$houseRes){
                return 500;
            }
            $houseid = $wpdb->insert_id;
        }
        for ($x=0; $x<=count($uploadedfile["name"])-1; $x++) {
            $uploadParam = array(
                "name"=>$uploadedfile["name"]["$x"],
                "type"=>$uploadedfile["type"]["$x"],
                "tmp_name"=>$uploadedfile["tmp_name"]["$x"],
                "error"=>$uploadedfile["error"]["$x"],
                "size"=>$uploadedfile["size"]["$x"]
            );
            //因为file提交过来有一个空的数组，所以这里判断在filename不为空的情况下，再做后续操作
            if($uploadParam["name"]!=""){
                //从wp_options中获取地址域名
                $results = $wpdb->get_row( 'SELECT * FROM wp_options WHERE option_name = "home"', OBJECT );
                $patharray = explode("/", $results->option_value);
                $path = "/".$patharray[3]."/wp-content/uploads/2015/08/".$uploadParam['name'];
                //上传图片
                if (!function_exists('wp_handle_upload')){
                    require_once(ABSPATH.'wp-admin/includes/file.php');
                }
                $overrides = array( 'test_form' => false);
                $movefile = wp_handle_upload($uploadParam,$overrides);
                if ( $movefile && !isset( $movefile['error'] ) ) {
                    //上传成功后将图片信息存入tospur_image表
                    $insert_image_array = array(
                        'name' => $uploadParam['name'],
                        'path' => $path,
                        'creattime' => date("Y-m-d H:i:s"),
                        'alt' => "",
                        'image_type' =>$uploadParam['type']
                    );
                    //插入图片表
                    $imgRes = $wpdb->insert('tospur_image', $insert_image_array);
                    if(!$imgRes){
                        return 501;
                    }
                    //获取插入图片的id
                    $imgid = $wpdb->insert_id;
                    //echo "File is valid, and was successfully uploaded.\n";
                } else {
                    echo $movefile['error'];
                }

                //房源类型、面积与图片关联表
                $houseTypeArea = array(
                    'house_id' =>$houseid,
                    "buildproperty_id" => $data["$x"]["buildproperty"],
                    "house_area" => $data["$x"]["housearea"],
                    "image_id" =>$imgid
                );
                $houseTypeAreaRes = $wpdb->insert('a_district_area', $houseTypeArea);
                if(!$houseTypeAreaRes){
                    return 502;
                }
                //将房源id与图片id储存到关联表中
                $house_img_array = array(
                    'house_id' =>$houseid,
                    'image_id'=>$imgid
                );
                $houseImgRes = $wpdb->insert('a_house_image', $house_img_array);
                if(!$houseImgRes){
                    return 503;
                }
            }
        }
    }
} 