<?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()
    {
        if( current_user_can('administrator') ) {
            $columns = array(
                'cb' => '<input type="checkbox" />'
            );
        }
        $columns['id']= 'ID';
        $columns['name']= '二手房标题';
        $columns['community_name']= '小区名称';
        $columns['total_price']= '总价';
        $columns['buildproperty_id']= '户型';
        $columns['covered_area']= '面积';
        $columns['floor']= '楼层';
        $columns['faceto']= '朝向';
        $columns['decoration']= '装修状况';
        $columns['age']= '年代';
        $columns['flat']= '楼号';
        $columns['suite']= '室';
        $columns['user_id']= '置业顾问';
        $columns['status']= '状态';
        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' => '审核',
            'selfSale'=>'自售',
            'otherSale'=>'他售',
            'invalid'=>'无效',
            'reactivation'=>'重激活'
        );
        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 'selfSale':
                    $id = $_POST['sechandhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 2;
                    }
                    break;
                case 'otherSale':
                    $id = $_POST['sechandhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 3;
                    }
                    break;
                case 'invalid':
                    $id = $_POST['sechandhouselist'];
                    print_r($id);
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 4;
                    }
                    break;
                case 'reactivation':
                    $id = $_POST['sechandhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $status = 5;
                    }
                    break;
            }
            global $wpdb;
            print_r('update tospur_house SET status='.$status .' where id in ' . $string);
            $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'] ="自售";
            }else if($value->status == 3){
                $data[$key]['status'] ="他售";
            }else if($value->status == 4){
                $data[$key]['status'] ="无效";
            }else if($value->status == 5){
                $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');

function secHandHouseList()
{
    $contest = array();
    $contest['page'] = $_REQUEST['page'];
    if(isset($_POST['hasSearch'])){
        $bpRes = SearchDao::searchBuildProperty();
        foreach($bpRes as $val){
            if($val->id == $_POST['buildProperty']){
                $contest['buildProperty'] = $val->value;
                $contest['buildPropertyId'] = $val->id;
            }
        }
        $contest['options']= SearchDao::searchForCDP($_POST['listCity'],$_POST['listDistrict'],$_POST['listPlate']);
        $contest['totalPrice'] = $_POST['totalPrice'];
        $contest['acreage'] = $_POST['acreage'];
        $contest['characteristic'] = $_POST['characteristic'];
        $contest['status'] = $_POST['status'];
        $contest['hasSearch'] = $_POST['hasSearch'];

    }
    Timber::render("secHandHouseList.html",$contest);
}
function addSecTable(){
    $secHandHouseList = new secHandHouseList();
    $secHandHouseList->prepare_items();
    $secHandHouseList->display();
}
?>



