<?php
/**
 * Created by PhpStorm.
 * User: UGEN79
 * Date: 2015/8/6
 * Time: 16:51
 */


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


class consultantScoreList extends WP_List_Table
{
    function __construct()
    {
        global $status, $page;
        //Set parent defaults
        parent::__construct(array(
            'singular' => 'score',     //singular name of the listed records
            'plural' => 'scores',    //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 'consultant':
            case 'user':
            case 'score':
                return $item[$column_name];
            case 'valid':
                if ($item[$column_name]) {
                    return '<button data-valid="0" data-score-id="' . $item['id'] . '">设为无效</button>';
                } else {
                    return '<button data-valid="1" data-score-id="' . $item['id'] . '">设为有效</button>';
                }
            default:
                return print_r($item, true); //Show the whole array for troubleshooting purposes
        }
    }

    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',
            'consultant' => '置业顾问',
            'user' => '用户',
            'score' => '评分',
            'valid' => '状态'
        );
        return $columns;
    }

    function get_sortable_columns()
    {
        $sortable_columns = array(
            'id' => array('id', false),
            'consultant' => array('consultant', false),
            'user' => array('user', false),
            'score' => array('score', false),
            'valid' => array('valid', false)
        );
        return $sortable_columns;
    }

    function get_bulk_actions()
    {
        $actions = array(
            'invalid' => '设为无效',
            'valid' => '设为有效',
        );
        return $actions;
    }

    function process_bulk_action()
    {
        $action = $this->current_action();
        if ($action) {
            $string = null;
            $valid = null;
            switch ($action) {
                case 'invalid':
                    $score = $_GET['score'];
                    if ($score) {
                        $string = '(' . implode(',', array_map('intval', $score)) . ')';
                        $valid = 0;
                    }
                    break;
                case 'valid':
                    $score = $_GET['score'];
                    if ($score) {
                        $valid = 1;
                        $string = '(' . implode(',', array_map('intval', $score)) . ')';
                    }
                    break;
            }
            global $wpdb;
            $result = $wpdb->query('update tospur_consultant_score SET valid=' . $valid . ' where id in ' . $string);
        }
    }

    function prepare_items()
    {
        global $wpdb;

        $per_page = 5;
        $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 s.id,c.display_name as consultant,u.user_login as user,s.score,s.valid FROM tospur_consultant_score s " .
            "left join wp_users u on s.user_id = u.ID " .
            "left join wp_users c on s.consultant_id = c.ID";
        $result = $wpdb->get_results($sql);
        $data = array();
        foreach ($result as $key => $value) {
            $data[$key] = array(
                'id' => $value->id,
                'consultant' => $value->consultant,
                'user' => $value->user,
                'score' => $value->score,
                'valid' => $value->valid,
            );
        }

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

function add_consultant_score_menu()
{
    add_menu_page('置业顾问评分', '置业顾问评分', 'activate_plugins', 'consultant_score', 'consultant_score_page', 'dashicons-menu', 26);
}

add_action('admin_menu', 'add_consultant_score_menu');

function consultant_score_page()
{
    $consultantScoreList = new consultantScoreList();
    $consultantScoreList->prepare_items();

    ?>
    <div class="wrap">
        <h2>置业顾问评分列表</h2>

        <form id="scores-filter" method="get">
            <!-- 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'] ?>"/>
            <!-- Now we can render the completed list table -->
            <?php $consultantScoreList->display() ?>
        </form>
    </div>
    <script>
        (function ($) {
            $('button[data-score-id]').click(function () {
                var self = $(this);
                var score_id = $(this).data('score-id');
                var valid = $(this).data('valid');
                $.ajax({
                    type: 'POST',
                    url: '<?php echo admin_url()?>admin-ajax.php/',
                    data: 'action=valid_consultant_score&id=' + score_id + '&valid=' + valid,
                    success: function (data) {
                        if (data.code == 2000) {
                            if (valid == 0) {
                                self.text('设为有效');
                                self.data('valid', 1);
                            } else {
                                self.text('设为无效');
                                self.data('valid', 0);
                            }
                            alert('设置成功');
                        } else {
                            alert('设置失败');
                        }
                    }
                });
                return false;
            });
        })(jQuery);
    </script>
<?php
}

?>