<?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 get_views()
    {
        global $wpdb;
        $current_url = set_url_scheme('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        $current_url = remove_query_arg(array('paged', 'status'), $current_url);
        $sql = "select COUNT(*) as allNum,
                 COUNT(NULLIF(approval != -2, false)) as needCheckNum,
                 COUNT(NULLIF(status = 0, false)) as unCheckNum,
                 COUNT(NULLIF(status = 1, false)) as checkNum,
                 COUNT(NULLIF(status = -1, false)) as onSaleNum,
                  COUNT(NULLIF(status = 2, false)) as notSaleNum
                 from  " . Config::TOSPUR_HOUSE_TABLE . " where  house_type = 0";
        $result = $wpdb->get_results($sql);
        foreach ($result as $value) {
            $approvalParam = array(
                "allNum" => $value->allNum,
                "needCheckNum" => $value->needCheckNum,
                "unCheckNum" => $value->unCheckNum,
                "checkNum" => $value->checkNum,
                "onSaleNum" => $value->onSaleNum,
                "notSaleNum" => $value->notSaleNum
            );
        }

        return array(
            "allNum" => '<a href="' . $current_url . '"'.(isset($_REQUEST["status"])?"":' class="current"').'>全部<span class="count">（' . $approvalParam["allNum"] . '）</span></a>',
            "needCheckNum" => '<a href="' . $current_url . '&status=-2" '.($_REQUEST["status"]==-2?'class="current"':"").'>需审批<span class="count">（' . $approvalParam["needCheckNum"] . '）</span></a>',
            "unCheckNum" => '<a href="' . $current_url . '&status=0" '.($_REQUEST["status"]=="0"?'class="current"':"").'>未审核<span class="count">（' . $approvalParam["unCheckNum"] . '）</span></a>',
            "checkNum" => '<a href="' . $current_url . '&status=1" '.($_REQUEST["status"]==1?'class="current"':"").'>审核<span class="count">（' . $approvalParam["checkNum"] . '）</span></a>',
            "onSaleNum" => '<a href="' . $current_url . '&status=-1" '.($_REQUEST["status"]==-1?'class="current"':"").'>交易中<span class="count">（' . $approvalParam["onSaleNum"] . '）</span></a>',
            "notSaleNum" => '<a href="' . $current_url . '&status=2" '.($_REQUEST["status"]==2?'class="current"':"").'>下架<span class="count">（' . $approvalParam["notSaleNum"] . '）</span></a>'
        );




    }

    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()
    {
        $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()
    {
        if (current_user_can('houseApproval')) {
            $actions = array(
                "agree" => "通过",
                "goBack" => "退回"
            );
        } else {
            $actions = array(
                'unCheck' => '未审核',
                'check' => '审核',
                'onSale' => '交易中',
                'notSale' => '下架'
            );
        }
        return $actions;
    }

    function manage_bulk_action()
    {
        global $wpdb;
        $flag = 0;
        $action = $this->current_action();
        if ($action) {
            $string = null;
            $approval = null;
            switch ($action) {
                case"agree":
                    $id = $_REQUEST['newhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $approvalRes = $wpdb->get_results('select approval from tospur_house where id in ' . $string);
                        foreach ($approvalRes as $value) {
                            if ($value->approval == -2) {
                                print_r("您审批的房源中含有未申请审批的房源，请重新选择");
                                exit;
                            }
                        }
                        $result = $wpdb->query('update tospur_house th SET th.status= th.approval where id in ' . $string);
                        $flag = 1;
                    }
                    break;
                case"goBack":
                    $id = $_REQUEST['newhouselist'];
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $flag = 1;
                    }
                    break;

            }
            if ($flag == 1) {
                $wpdb->query('update tospur_house th SET th.approval= -2 where id in ' . $string);
            }
        }
    }

    function getCurrentStatus($houseId, $changeStatus = null)
    {
        global $wpdb;
        $sql = "select status from tospur_house where id in" . $houseId;
        $res = $wpdb->get_results($sql);
        if ($changeStatus != null || $changeStatus == 0) {
            foreach ($res as $value) {
                if ($value->status == $changeStatus) {
                    print_r("您申请的状态含有与原状态相同的房源，请重新选择");
                    return false;
                } else {
                    return $changeStatus;
                }
            }
        }
        return $res;
    }

    function process_bulk_action()
    {
        $action = $this->current_action();
        if ($action) {
            $string = null;
            $status = null;
            $id = $_REQUEST['newhouselist'];
            switch ($action) {
                case 'unCheck':
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $res = $this->getCurrentStatus($string, 0);
                        if ($res === false) {
                            exit;
                        }
                        $status = $res;
                    }
                    break;
                case 'check':
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $res = $this->getCurrentStatus($string, 1);
                        if (!$res) {
                            exit;
                        }
                        $status = $res;
                    }
                    break;
                case 'onSale':
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $res = $this->getCurrentStatus($string, -1);
                        if (!$res) {
                            exit;
                        }
                        $status = $res;
                    }
                    break;
                case 'notSale':
                    if ($id) {
                        $string = '(' . implode(',', array_map('intval', $id)) . ')';
                        $res = $this->getCurrentStatus($string, 2);
                        if (!$res) {
                            exit;
                        }
                        $status = $res;
                    }
                    break;
            }
            global $wpdb;
            $result = $wpdb->query($wpdb->prepare('update tospur_house SET approval=%d where id in ' . $string, $status));
        }
    }


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

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

        if (current_user_can('houseApproval')) {
            $this->manage_bulk_action();
        } else {
            $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
                 left join(select user_id as aus_id,house_id,user_type from a_house_user)  ahu on th.id = ahu.house_id and ahu.user_type=1
                 left join(select id as consul_id,name as consul_name,subsidiaryId from tospur_consultant) tc on ahu.aus_id = tc.consul_id
                 left join(select status_name,status_type,status_id from tospur_status)ts on th.status = ts.status_id and ts.status_type=1
                 left join(select status_name as approvalName,status_type,status_id from tospur_status)tss on th.approval = tss.status_id and tss.status_type=1
                 where 1=1 and house_type=0 ";

        if (isset($_REQUEST["listCity"]) && $_REQUEST["listCity"] != -1) {
            $params[] = $_REQUEST["listCity"];
            $sql = $sql . " and city_id=%d";
        }
        if (isset($_REQUEST["listDistrict"]) && $_REQUEST["listDistrict"] != -1) {
            $params[] = $_REQUEST["listDistrict"];
            $sql = $sql . " and district_id=%d";
        }
        if (isset($_REQUEST["listPlate"]) && $_REQUEST["listPlate"] != -1) {
            $params[] = $_REQUEST["listPlate"];
            $sql = $sql . " and plate_id=%d";
        }
        if (isset($_REQUEST["buildProperty"]) && $_REQUEST["buildProperty"] != -1) {
            $params[] = $_REQUEST["buildProperty"];
            $sql = $sql . " and buildproperty_id=%d";
        }
        if (isset($_REQUEST["room"]) && $_REQUEST["room"] != -1) {
            $params[] = $_REQUEST["room"];
            $sql = $sql . " and room_id=%d";
        }
        if (isset($_REQUEST["status"]) && $_REQUEST["status"] != -3&& $_REQUEST["status"]!="") {
            $params[] = $_REQUEST["status"];
            if($_REQUEST["status"] == -2){
                $sql = $sql . " and approval != %d";
            }else{
                $sql = $sql . " and status=%d";
            }
        }

        if ($_REQUEST["totalPrice"] != NULL) {
            $priceArray = explode("-", $_REQUEST['totalPrice']);
            $params[] = $priceArray[0];
            $params[] = $priceArray[1];
            $sql = $sql . " and average_price between %d and %d";
        }
        if ($_REQUEST["acreage"] != NULL) {
            $areaArray = explode("-", $_REQUEST['acreage']);
            $params[] = $areaArray[0];
            $params[] = $areaArray[1];
            $sql = $sql . " and covered_area between %d and %d";
        }

        if ($_REQUEST["beginDate"] != NULL && $_REQUEST["endDate"] != NULL) {
            $time = array($_REQUEST["beginDate"], $_REQUEST["endDate"]);
            $params[] = $time[0];
            $params[] = $time[1];
            $sql = $sql . " and creattime between %s and %s";
        }

        if (isset($_REQUEST["organization"]) && $_REQUEST["organization"] != -1) {
            $params[] = $_REQUEST["organization"];
            $sql = $sql . " and subsidiaryId=%d ";
        } else if ($_REQUEST["searchText"] != NULL) {
            $params[] = '%' . $_REQUEST['searchText'] . '%';
            $sql = $sql . " and name like %s";
        } else if ($_REQUEST["stuff"] != NULL) {
            $params[] = '%' . $_REQUEST['stuff'] . '%';
            $sql = $sql . " and consul_name like %s";
        }


        $sql = $sql . " group by id";

        if (isset($_REQUEST["orderby"])) {
            $orderby = $_REQUEST["orderby"];
            $order = $_REQUEST["order"];
            $sql = $sql . " order by " . $orderby . " " . $order;
        }

        $result = $wpdb->get_results($wpdb->prepare($sql, $params));
        $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->approval == -2) {
                $data[$key]['status'] = $value->status_name;
            } else {
                $data[$key]['status'] = $value->status_name . "(" . $value->approvalName . ")";
            }
        }

        $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($_REQUEST['hasSearch'])) {
        $contest['district'] = SearchDao::searchCity($_REQUEST['listCity']);
        $contest['plate'] = SearchDao::searchCity($_REQUEST['listCity'], $_REQUEST['listDistrict']);
        $contest['dicTotalPrice'] = searchDao::searchTotalPrice($_REQUEST['listCity']);
        $contest['dicArea'] = searchDao::searchArea($_REQUEST['listCity']);
        $contest['cityId'] = $_REQUEST['listCity'];
        $contest['districtId'] = $_REQUEST['listDistrict'];
        $contest['plateId'] = $_REQUEST['listPlate'];
        $contest['roomId'] = $_REQUEST['room'];
        $contest['buildPropertyId'] = $_REQUEST['buildProperty'];
        $contest['averagePrice'] = $_REQUEST['averagePrice'];
        $contest['acreage'] = $_REQUEST['acreage'];
        $contest['statusId'] = $_REQUEST['status'];
        $contest['req']['organization'] = $_REQUEST['organization'];
        $contest['req'] = $_REQUEST;
    }
    $contest["house_type"] = 0;
    Timber::render("houseList.html", $contest);
}

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

?>
