<?php


if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}


class newHouseList extends WP_List_Table
{
    function __construct()
    {
        global $status, $page;
        //Set parent defaults
        parent::__construct(array(
            'singular' => 'newHouseList',     //singular name of the listed records
            'plural' => 'newHouseLists',    //plural name of the listed records
            'ajax' => false        //does this table support ajax?
        ));
    }

    function column_default($item, $column_name)
    {
        switch ($column_name) {
            case'id':
            case 'name':
            case 'address':
            case 'average_price':
            case 'developer':
            case 'check_in_time':
            case 'room_id':
            case 'property_age':
            case 'decoration':
            case 'covered_area':
            case 'status':
            case 'volume_rate':
            case 'greening_rate':
            case 'households':
            case 'parking_spaces':
            case 'property_management':
            case 'property_money':
            default:
                return '<a href="' . admin_url() . 'admin.php?page=newHouse&edit=true&id=' . $item['id'] . '">' . $item[$column_name] . '</a>';
        }
    }

    function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="%1$s[]" value="%2$s" />',
            /*$1%s*/
            $this->_args['singular'],  //Let's simply repurpose the table's singular label ("score")
            /*$2%s*/
            $item['id']                //The value of the checkbox should be the record's id
        );
    }

    function get_columns()
    {
        if( current_user_can('administrator') ) {
            $columns = array(
                'cb' => '<input type="checkbox" />'
            );
        }
        $columns['id']= 'ID';
        $columns['name']= '楼盘名';
        $columns['address']= '地址';
        $columns['average_price']= '单价';
        $columns['developer']= '开发商';
        $columns['check_in_time']= '入住时间';
        $columns['room_id']= '建筑类型';
        $columns['property_age']= '产权年限';
        $columns['decoration']= '装修状况';
        $columns['covered_area']= '建筑面积';
        $columns['volume_rate']= '容积率';
        $columns['greening_rate']= '绿化率';
        $columns['households']= '规划户数';
        $columns['parking_spaces']= '车位数';
        $columns['property_management']= '物业公司';
        $columns['property_money']= '物业费';
        $columns['status']= '状态';
        return $columns;
    }

    function get_sortable_columns()
    {
        $sortable_columns = array(
            'id' => array('id', false),
            'name' => array('name', false),
            'address' => array('address', false),
            'average_price' => array('average_price', false),
            'developer' => array('developer', false),
            'check_in_time' => array('check_in_time', false),
            'room_id' => array('room_id', false),
            'property_age' => array('property_age', false),
            'decoration' => array('decoration', false),
            'covered_area' => array('covered_area', false),
            'status' => array('status', false),
            'volume_rate' => array('valvolume_rateid', false),
             'greening_rate' => array('greening_rate', false),
            'households' => array('households', false),
            'parking_spaces' => array('parking_spaces', false),
            'property_management' => array('property_management', false),
            'property_money' => array('property_money', false),
        );
        return $sortable_columns;
    }

    function get_bulk_actions()
    {
        $actions = array(
            'noCheck' => '未审核',
            'check' => '审核',
            'stopSale' =>'下架'
        );
        return $actions;
    }

    function process_bulk_action()
    {
        $action = $this->current_action();
        if ($action) {
            $string = null;
            $status = null;
            switch ($action) {
                case 'noCheck':
                    $id = $_POST['newhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 0;
                    }
                    break;
                case 'check':
                    $id = $_POST['newhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 1;
                    }
                    break;
                case 'stopSale':
                    $id = $_POST['newhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 2;
                    }
                    break;
            }
            global $wpdb;
            $result = $wpdb->query('update tospur_house SET status='.$status .' where id in ' . $string);
        }
    }



 function prepare_items()
    {
        global $wpdb;
        $per_page = 10;
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();

        $this->_column_headers = array($columns, $hidden, $sortable);

        $this->process_bulk_action();

        //$data = $this->example_data;

        $sql = "select * from tospur_house th
                 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 did,literal as room_type from dic_room) dr on dr.did = th.room_id
                 where 1=1 and house_type=0";
        if($_POST["listCity"]!=0  ){
            $sql = $sql." and city_id=".$_POST["listCity"];
        }
        if($_POST["listDistrict"] != 0 ){
            $sql = $sql." and district_id=".$_POST["listDistrict"];
        }
        if($_POST["listPlate"] != 0){
            $sql = $sql." and plate_id=".$_POST["listPlate"];
        }
        if($_POST["buildProperty"]!=0){
            $sql = $sql." and buildproperty_id=".$_POST["buildProperty"];
        }
        if($_POST["room"]!=0){
            $sql = $sql." and room_id=".$_POST["room"];
        }
        if(isset($_POST["status"]) && $_POST["status"]!=-1){
            $sql = $sql." and status=".$_POST["status"];
        }
        if($_POST["totalPrice"]!=NULL){
            $priceArray = explode("-", $_POST['totalPrice']);
            $sql = $sql . " and average_price between ".$priceArray[0]." and ".$priceArray[1];
        }
        if($_POST["acreage"]!= NULL){
            $areaArray = explode("-", $_POST['acreage']);
            $sql = $sql . " and covered_area between ".$areaArray[0]." and ".$areaArray[1];
        }
        if($_POST["searchText"]!=NULL){
            $sql = $sql . " and name like '%".$_POST['searchText']."%'";
        }
        $sql = $sql . " group by id";
        $result = $wpdb->get_results($sql);
        $data = array();
        foreach ($result as $key => $value) {
            $data[$key] = array(
                'id' => $value->id,
                'name' =>  $value->name,
                'address' =>  $value->address,
                'average_price' =>  $value->average_price,
                'developer' =>  $value->developer,
                'check_in_time' => $value->check_in_time,
                'room_id' =>  $value->room_type,
                'property_age' =>  $value->property_age,
                'decoration' =>  $value->decoration,
                'covered_area' => $value->covered_area,
                'volume_rate' =>  $value->volume_rate,
                'greening_rate' =>  $value->greening_rate,
                'households' =>  $value->households,
                'parking_spaces' => $value->parking_spaces,
                'property_management' =>  $value->property_management,
                'property_money' =>  $value->property_money
            );
            if($value->status == 0){
                $data[$key]['status'] ="未审核";
            }else if($value->status == 1){
                $data[$key]['status'] ="审核";
            }else if($value->status == 2){
                $data[$key]['status'] ="下架";
            }
        }

        function usort_reorder($a, $b)
        {
            $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'valid'; //If no sort, default to title
            $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'desc'; //If no order, default to asc
            $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order
            return ($order === 'asc') ? $result : -$result; //Send final sort direction to usort
        }

        usort($data, 'usort_reorder');

        $current_page = $this->get_pagenum();

        $total_items = count($data);

        $data = array_slice($data, (($current_page - 1) * $per_page), $per_page);

        $this->items = $data;

        $this->set_pagination_args(array(
            'total_items' => $total_items,                  //WE have to calculate the total number of items
            'per_page' => $per_page,                     //WE have to determine how many items to show on a page
            'total_pages' => ceil($total_items / $per_page)   //WE have to calculate the total number of pages
        ));
    }
}
add_action( 'wp_ajax_updateList', 'newHouseList::prepare_items');
add_action( 'wp_ajax_nopriv_updateList', 'newHouseList::prepare_items');
add_action( 'wp_ajax_searchListCity', 'SearchDao::ajax_searchListCity');
add_action( 'wp_ajax_nopriv_searchListCity', 'SearchDao::ajax_searchListCity');

function function_newHouseList()
{
    $contest = array();
    $contest['page'] = $_REQUEST['page'];
    $contest['city'] = SearchDao::searchCity();
    $contest['status'] = SearchDao::searchStatusType(1);
    $contest['buildProperty'] = SearchDao::searchBuildProperty();
    $contest['room'] = searchDao::searchRoom();
    if(isset($_POST['hasSearch'])){
        $contest['district'] = SearchDao::searchCity($_POST['listCity']);
        $contest['plate'] = SearchDao::searchCity($_POST['listCity'],$_POST['listDistrict']);
        $contest['dicTotalPrice'] = searchDao::searchTotalPrice($_POST['listCity']);
        $contest['dicArea'] = searchDao::searchArea($_POST['listCity']);
        $contest['cityId'] = $_POST['listCity'];
        $contest['districtId'] = $_POST['listDistrict'];
        $contest['plateId' ]= $_POST['listPlate'];
        $contest['roomId']= $_POST['room'];
        $contest['buildPropertyId']= $_POST['buildProperty'];
        $contest['totalPrice'] = $_POST['totalPrice'];
        $contest['acreage'] = $_POST['acreage'];
        $contest['statusId']  =  $_POST['status'];
    }
    Timber::render("newHouseList.html",$contest);
}

function addNewHouseTable(){
    $newHouseList = new newHouseList();
    $newHouseList->prepare_items();
    $newHouseList->display();
}
?>
