<?php

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

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

    function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'community_name':
                return '<a href="' . admin_url('admin.php?page=' . $_GET['page'] . '&id=' . $item['id']) . '">' . $item[$column_name] . '</a>';
            case 'consultant':
                $consultant = $item[$column_name] ? $item[$column_name] : '未分配';
                return $consultant;
            case 'handle':
                $handle = ($item[$column_name] == 1) ? '已处理' : '未处理';
                return $handle;
            default:
                return $item[$column_name];
        }
    }

    function get_columns()
    {
        $columns = array(
            'cityName' => '城市',
            'community_name' => '小区名',
            'apartment' => '户型',
            'covered_area' => '面积',
            'floor' => '楼层',
            'faceto' => '朝向',
            'price' => '期望售价',
            'description' => '房源描述',
            'phone' => '手机号',
            'submission_date' => '提交时间',
            'consultant' => '置业顾问',
            'handle' => '处理状态',
            'handle_date' => '处理时间'
        );
        return $columns;
    }

    function get_sortable_columns()
    {
        $sortable_columns = array();
        return $sortable_columns;
    }

    function extra_tablenav($which)
    {
        if ($which == 'top') {
            ?>
            <div>
                <label for="cityDropDown"></label>
                <select name="cityId" id="cityDropDown" style="vertical-align: initial;">
                    <?php
                    $cityId = (int)$_GET['cityId'];
                    $city = SearchDao::searchCity();
                    ?>
                    <option value="-1"<?php if ($cityId == -1) {
                        echo ' selected="selected"';
                    } ?>>城市
                    </option>
                    <?php
                    foreach ($city as $item) {
                        if ($item->id == $cityId) {
                            $selected = ' selected="selected"';
                        } else {
                            $selected = null;
                        }
                        echo '<option value="' . $item->id . '"' . $selected . '>' . $item->value . '</option>';
                    }
                    ?>
                </select>
                <span>
                    <label for="search"></label>
                    <input type="search" id="search" name="s" value="<?php echo $_GET['s']; ?>" placeholder="请输入关键字搜索"
                           style="height: 28px;">
                    <input type="submit" id="search-submit" class="button" value="搜索">
                </span>
            </div>
        <?php
        }
    }

    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);

        $house_type = $_GET['page'];
        if ($house_type == 'tospur_sale_secondhand') {
            $house_type = 1;
        } else if ($house_type == 'tospur_sale_rent') {
            $house_type = 2;
        }
        $sql = "SELECT ts.*,dc.cityName,u.display_name FROM tospur_sale ts" .
            " left join (SELECT cityId,cityName FROM dic_city group by cityId) dc on ts.cityId = dc.cityId" .
            " left join wp_users u on u.ID = ts.consultant_id" .
            " where ts.house_type = " . $house_type;
        $cityId = (int)$_GET['cityId'];
        if ($cityId > 0) {
            $sql .= " and ts.cityId = " . $cityId;
        }
        $s = $_GET['s'];
        if ($s) {
            $sql .= " and (ts.community_name like '%" . $s . "%' or ts.phone like '%" . $s . "%' or ts.faceto like '%" . $s . "%')";
        }
        $result = $wpdb->get_results($sql);
        $data = array();
        foreach ($result as $key => $value) {
            $unit = ($value->house_type == 1) ? '万元' : '元/月';
            $data[$key] = array(
                'id' => $value->id,
                'cityName' => $value->cityName,
                'community_name' => $value->community_name,
                'apartment' => $value->bedroom . '室' . $value->hall . '厅' . $value->kitchen . '厨' . $value->bathroom . '卫',
                'covered_area' => $value->covered_area . 'm²',
                'floor' => '第' . $value->floor . '层(共' . $value->total_floor . '层)',
                'faceto' => $value->faceto,
                'price' => $value->price . $unit,
                'description' => $value->description,
                'phone' => $value->phone,
                'submission_date' => $value->submission_date,
                'consultant' => $value->display_name,
                'handle' => $value->handle,
                'handle_date' => $value->handle_date
            );
        }

        function usort_reorder($a, $b)
        {
            $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'handle';
            $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
            $result = strcmp($a[$orderby], $b[$orderby]);
            return ($order === 'asc') ? $result : -$result;
        }

        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,
            'per_page' => $per_page,
            'total_pages' => ceil($total_items / $per_page)
        ));
    }
}

function add_tospur_sale_menu()
{
    add_menu_page('房东服务', '房东服务', 'activate_plugins', 'tospur_sale_secondhand', 'tospur_sale_page', 'dashicons-menu', 28);
    add_submenu_page('tospur_sale_secondhand', '出售', '出售', 'activate_plugins', 'tospur_sale_secondhand', 'tospur_sale_page');
    add_submenu_page('tospur_sale_secondhand', '出租', '出租', 'activate_plugins', 'tospur_sale_rent', 'tospur_sale_page');
}

add_action('admin_menu', 'add_tospur_sale_menu');

function tospur_sale_page()
{
    if ($_GET['id']) {
        require_once('tospur_sale_detail.php');
    } else {
        $tospurSaleList = new tospurSaleList();
        $tospurSaleList->prepare_items();
        $house_type = $_GET['page'];
        $title = null;
        if ($house_type == 'tospur_sale_secondhand') {
            $title = '房东服务列表—出售';
        } else if ($house_type == 'tospur_sale_rent') {
            $title = '房东服务列表—出租';
        }
        ?>
        <div class="wrap">
            <h2><?php echo $title; ?></h2>

            <form method="get">
                <input type="hidden" name="page" value="<?php echo $_REQUEST['page']; ?>"/>
                <?php $tospurSaleList->display(); ?>
            </form>
        </div>
        <style>
        </style>
        <script>
            (function ($) {
                var cityId = -1;
                $(document).ready(function () {
                    var cityDropDown = $('#cityDropDown');
                    cityId = Number(cityDropDown.find('option:selected').val());
                    cityDropDown.change(function () {
                        cityId = Number($(this).val());
                        window.location.href = '<?php
                        echo admin_url('admin.php?page='.$_GET['page'].'&paged=1');
                    ?>' + '&cityId=' + cityId;
                    });
                    $('#search-submit').click(function () {
                        var s = $('#search').val();
                        if (!s) {
                            alert('请输入关键字搜索');
                        } else {
                            window.location.href = '<?php
                        echo admin_url('admin.php?page='.$_GET['page'].'&paged=1');
                    ?>' + '&cityId=' + cityId + '&s=' + s;
                        }
                        return false;
                    });
                });
            })(jQuery);
        </script>
    <?php
    }
}

?>