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

class secHandHouseList extends WP_List_Table
{
    function __construct()
    {
        global $status, $page;
        //Set parent defaults
        parent::__construct(array(
            'singular' => 'secHandHouseList',     //singular name of the listed records
            'plural' => 'secHandHouseLists',    //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 'community_name':
            case 'total_price':
            case 'buildproperty_id':
            case 'covered_area':
            case 'floor':
            case 'faceto':
            case 'decoration':
            case 'age':
            case 'flat':
            case 'suite':
            case 'user_id':
            case 'status':
            default:
                return '<a href="' . admin_url() . 'admin.php?page=secHandHouse&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()
    {
        $columns = array(
            'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
            'id' =>'ID',
            'name' => '二手房标题',
            'community_name' => '小区名称',
            'total_price' => '总价',
            'buildproperty_id' => '户型',
            'covered_area' => '面积',
            'floor' => '楼层',
            'faceto' => '朝向',
            'decoration' => '装修状况',
            'age' => '年代',
            'flat' => '楼号',
            'suite' => '室',
            'user_id' => '置业顾问',
            'status' => '状态'
        );
//        if (current_user_can('Administrator')) {
//            $columns['cb'] = '<input type="checkbox" />';
//        }
        return $columns;
    }

    function get_sortable_columns()
    {
        $sortable_columns = array(
            'id' => array('id', false),
            'name' => array('name', false),
            'community_name' => array('community_name', false),
            'total_price' => array('total_price', false),
            'buildproperty_id' => array('buildproperty_id', false),
            'covered_area' => array('covered_area', false),
            'floor' => array('floor', false),
            'faceto' => array('faceto', false),
            'decoration' => array('decoration', false),
            'age' => array('age', false),
            'flat' => array('flat', false),
            'suite' => array('suite', false),
            'user_id' => array('user_id', false),
            'status' => array('status', 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['sechandhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 0;
                    }
                    break;
                case 'check':
                    $id = $_POST['sechandhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 1;
                    }
                    break;
                case 'stopSale':
                    $id = $_POST['sechandhouselist'];
                    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 user_id as aus_id,house_id from a_house_user)  ahu on th.id = ahu.house_id
                 left join(select id as consul_id,name as consul_name from tospur_consultant) tc on ahu.aus_id = tc.consul_id
                 left join(select value,literal from dic_buildproperty) db on th.buildproperty_id = db.value
                 where 1=1 and house_type=1";
        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(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']."%'";
        }
        $result = $wpdb->get_results($sql);
        $data = array();
        foreach ($result as $key => $value) {
            $data[$key] = array(
                'id' => $value->id,
                'name' =>  $value->name,
                'community_name' =>  $value->community_name,
                'total_price' =>  $value->total_price,
                'buildproperty_id' =>  $value->literal,
                'covered_area' => $value->covered_area,
                'floor' =>  $value->floor,
                'faceto' =>  $value->faceto,
                'decoration' =>  $value->decoration,
                'age' => $value->age,
                'flat' =>  $value->flat,
                'suite' =>  $value->suite,
                'user_id' =>  $value->consul_name,
            );

            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 secHandHouseList()
{
    $secHandHouseList = new secHandHouseList();
    $secHandHouseList->prepare_items();
    ?>
    <div class="wrap">
        <h2>二手房列表</h2>
        <form id="scores-filter" method="POST">
            <!-- For plugins, we also need to ensure that the form posts back to our current page -->
            <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
            <select id="listCity" name="listCity">
                <option value="0"> 城市</option>
            </select>
            <select id="listDistrict" name="listDistrict">
                <option value="0">区域</option>
            </select>
            <select  id="listPlate" name="listPlate">
                <option value="0">板块</option>
            </select>
            <select id="totalPrice" name="totalPrice">
                <option value ="">价格</option>
            </select>
            <select id="buildProperty" name="buildProperty">
                <option value="0">房型</option>
            </select>
            <select id="acreage" name="acreage">
                <option value ="">面积</option>
            </select>
            <select id="characteristic" name="characteristic">
                <option value ="">特色</option>
                <option value ="">满5</option>
                <option value ="">唯一住房</option>
            </select>
            <select name="status" name="status">
                <option value="-1">状态</option>
                <option value="0">未审核</option>
                <option value="1">审核</option>
                <option value="2">下架</option>
            </select>
            <input type="text" placeholder="请出入楼盘名/地段名搜索" name="searchText">
            <input type="submit" id="submit" class="button action" value="搜索">
            <!-- Now we can render the completed list table -->
            <?php $secHandHouseList->display() ?>
        </form>
    </div>
    <script>
        (function ($) {
            $(document).ready(function(){
                //获取城市信息AJAX
                var listCity = $("#listCity");
                var room = $("#room");
                var buildProperty =$("#buildProperty");
                $.ajax({
                    type: "GET",
                    url: "/tospur/wp-admin/admin-ajax.php",
                    data: "action=serachCity",
                    success:function(data){
                        addOption(data,listCity)
                    }
                })
                //获取类型信息AJAX
                $.ajax({
                    type: "GET",
                    url: "/tospur/wp-admin/admin-ajax.php",
                    data: "action=searchRoom",
                    success:function(data){
                        addOption(data,room)
                    }
                })
                //获取房型信息AJAX
                $.ajax({
                    type: "GET",
                    url: "/tospur/wp-admin/admin-ajax.php",
                    data: "action=searchBuildProperty",
                    success:function(data){
                        addOption(data,buildProperty)
                    }
                })


                $("#listCity").change(function(){
                    var listCityId = $("#listCity").val();
                    var district =$("#listDistrict");
                    var acreage =$("#acreage");
                    var totalPrice = $("#totalPrice");
                    $('#listDistrict').find('option:not(:first-child)').remove();
                    $('#listPlate').find('option:not(:first-child)').remove();
                    $.ajax({
                        type: "GET",
                        url: "/tospur/wp-admin/admin-ajax.php",
                        data: "action=serachCity&cityId="+listCityId,
                        success:function(json){
                            addOption(json,district);
                        }
                    });
                    //面积
                    $.ajax({
                        type: "GET",
                        url: "/tospur/wp-admin/admin-ajax.php",
                        data: "action=searchArea&cityId="+listCityId,
                        success:function(json){
                            for(var i = 0; i <=json.length-1; i++){
                                var id = json[i]["id"];
                                var value = json[i]["value"];
                                var Option = $("<option>").attr({"value": value}).append(value);
                                $("#acreage").append(Option);
                            }
                        }
                    });
                    //城市联动房子价格
                    $.ajax({
                        type: "GET",
                        url: "/tospur/wp-admin/admin-ajax.php",
                        data: "action=searchUnitPriceRange&cityId="+listCityId,
                        success:function(json){
                            for(var i = 0; i <=json.length-1; i++){
                                var id = json[i]["id"];
                                var value = json[i]["value"];
                                var Option = $("<option>").attr({"value": value}).append(value);
                                $("#totalPrice").append(Option);
                            }
                        }
                    });
                })

                $("#listDistrict").change(function(){
                    var listCityId = $("#listCity").val();
                    var listDistrict = $("#listDistrict").val();
                    var listPlate = $("#listPlate");
                    $('#listPlate').find('option:not(:first-child)').remove();
                    $.ajax({
                        type: "GET",
                        url: "/tospur/wp-admin/admin-ajax.php",
                        data: "action=serachCity&cityId="+listCityId+"&districtId="+listDistrict,
                        success:function(json){
                            addOption(json,listPlate);
                        }
                    });
                })

                function addOption(json,select){
                    for(var i = 0; i <=json.length-1; i++){
                        var id = json[i]["id"];
                        var value = json[i]["value"];
                        var Option = $("<option>").attr({"value": id}).append(value);
                        select.append(Option);
                    }
                }
            });
        })(jQuery);
    </script>
<?php
}

?>