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


class rentHouseList 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 selfSaleNum,
                 COUNT(NULLIF(status = 3, false)) as otherSaleNum,
                 COUNT(NULLIF(status = 4, false)) as invalidNum,
                 COUNT(NULLIF(status = 5, false)) as reactivationNum
                 from  " . Config::TOSPUR_HOUSE_TABLE . " where  house_type = 2";
        $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,
                "selfSaleNum" => $value->selfSaleNum,
                "otherSaleNum" => $value->otherSaleNum,
                "invalidNum" => $value->invalidNum,
                "reactivationNum" => $value->reactivationNum
            );
        }
        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>',
            "selfSaleNum" => '<a href="' . $current_url . '&status=2"'.($_REQUEST["status"]==2?'class="current"':"").'>自售<span class="count">（' . $approvalParam["selfSaleNum"] . '）</span></a>',
            "otherSaleNum" => '<a href="' . $current_url . '&status=3"'.($_REQUEST["status"]==3?'class="current"':"").'>他售<span class="count">（' . $approvalParam["otherSaleNum"] . '）</span></a>',
            "invalidNum" => '<a href="' . $current_url . '&status=4"'.($_REQUEST["status"]==4?'class="current"':"").'>无效<span class="count">（' . $approvalParam["invalidNum"] . '）</span></a>',
            "reactivationNum" => '<a href="' . $current_url . '&status=5"'.($_REQUEST["status"]==5?'class="current"':"").'>重激活<span class="count">（' . $approvalParam["reactivationNum"] . '）</span></a>',
        );
    }

    function __construct()
    {
        global $status, $page;
        //Set parent defaults
        parent::__construct(array(
            'singular' => 'rentHouseList',     //singular name of the listed records
            'plural' => 'rentHouseList',    //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 'rent':
            case 'buildproperty_id':
            case 'covered_area':
            case 'floor':
            case 'faceto':
            case 'decoration':
            case 'age':
            case 'matching_facilities':
            case 'user_id':
            case 'status':
            default:
                return '<a href="' . admin_url() . 'admin.php?page=rentHouse&edit=true&id=' . $item['id'] . '">' . $item[$column_name] . '</a>';
        }
    }

    function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="%1$s[]" value="%2$s" data-consultant="%3$s"/>',
            $this->_args['singular'],
            $item['id'],
            $item['consultant_id']
        );
    }

    function get_columns()
    {
        $columns = array(
            'cb' => '<input type="checkbox" />'
        );
        $columns['id'] = 'ID';
        $columns['name'] = '租房标题';
        $columns['community_name'] = '小区名称';
        $columns['rent'] = '元/月';
        $columns['buildproperty_id'] = '户型';
        $columns['covered_area'] = '面积';
        $columns['floor'] = '楼层';
        $columns['faceto'] = '朝向';
        $columns['decoration'] = '装修状况';
        $columns['age'] = '年代';
        $columns['matching_facilities'] = '配套设施';
        $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),
            'rent' => array('rent', 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),
            'matching_facilities' => array('matching_facilities', false),
            'user_id' => array('user_id', false),
            'status' => array('status', false)
        );
        return $sortable_columns;
    }

    function get_bulk_actions()
    {
        if (current_user_can('houseApproval')) {
            $actions = array(
                "agree" => "通过",
                "goBack" => "退回",
                'allot' => '分配置业顾问'
            );
        } else {
            $actions = array(
                'unCheck' => '未审核',
                'check' => '审核',
                'onSale' => '交易中',
                'selfSale' => '自售',
                'otherSale' => '他售',
                'invalid' => '无效',
                'reactivation' => '重激活'
            );
        }
        return $actions;
    }

    function manage_bulk_action()
    {
        global $wpdb;
        $action = $this->current_action();
        $id = $_REQUEST['renthouselist'];
        if ($action && $id) {
            $string = '(' . implode(',', array_map('intval', $id)) . ')';
            $approval = null;
            $flag = 0;
            switch ($action) {
                case"agree":
                    $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":
                    $flag = 1;
                    break;
                case "allot":
                    HouseDao::houseAllotConsultant($_POST['allot_consultant_id'], $id);
                    break;
            }
            if ($flag == 1) {
                $wpdb->query('update tospur_house th SET th.approval= -2 where id in ' . $string);
            }
        }
    }

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

            if ($value->status == 2 || $value->status == 3) {
                print_r("自售与他售房源不能修改状态，请重新选择");
                return false;
            }

            if ($value->status == 4 && $changeStatus != 5) {
                print_r("无效房源必须先重激活才能继续修改，请重新选择");
                return false;
            }

            if ($changeStatus == 5 && $value->status != 4) {
                print_r("只有无效房源才可以重激活，请重新选择");
                return false;
            }
        }
        return $changeStatus;
    }

    function process_bulk_action()
    {
        $action = $this->current_action();
        global $wpdb;
        $id = $_REQUEST['renthouselist'];
        if ($action && $id) {
            $string = '(' . implode(',', array_map('intval', $id)) . ')';
            $status = null;
            switch ($action) {
                case 'unCheck':
                    $res = $this->getCurrentStatus($string, 0);
                    if ($res === false) {
                        exit;
                    }
                    $status = $res;
                    break;
                case 'check':
                    $res = $this->getCurrentStatus($string, 1);
                    if (!$res) {
                        exit;
                    }
                    $status = $res;
                    break;
                case 'selfSale':
                    $res = $this->getCurrentStatus($string, 2);
                    if (!$res) {
                        exit;
                    }
                    $status = $res;
                    break;
                case 'otherSale':
                    $res = $this->getCurrentStatus($string, 3);
                    if (!$res) {
                        exit;
                    }
                    $status = $res;
                    break;
                case 'invalid':
                    $res = $this->getCurrentStatus($string, 4);
                    if (!$res) {
                        exit;
                    }
                    $status = $res;
                    break;
                case 'reactivation':
                    $res = $this->getCurrentStatus($string, 5);
                    if (!$res) {
                        exit;
                    }
                    $status = $res;
                    break;
                case 'onSale':
                    $res = $this->getCurrentStatus($string, -1);
                    if (!$res) {
                        exit;
                    }
                    $status = $res;
                    break;
            }
            $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 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 value,literal from dic_buildproperty) db on th.buildproperty_id = db.value
                 left join(select status_name,status_type,status_id from tospur_status)ts on th.status = ts.status_id and ts.status_type=2
                 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=2
                 where 1=1 and house_type=2  ";
        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["rentalPrice"] != NULL) {
            $priceArray = explode("-", $_REQUEST['rentalPrice']);
            $params[] = $priceArray[0];
            $params[] = $priceArray[1];
            $sql = $sql . " and rent 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";
        }

        if (isset($_GET["orderby"])) {
            $orderby = $_GET["orderby"];
            $order = $_GET["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,
                'community_name' => $value->community_name,
                'rent' => $value->rent,
                'buildproperty_id' => $value->literal,
                'covered_area' => $value->covered_area,
                'floor' => $value->floor,
                'faceto' => $value->faceto,
                'decoration' => $value->decoration,
                'age' => $value->age,
                'matching_facilities' => $value->matching_facilities,
                'user_id' => $value->consul_name,
            );
            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_rentHouseList()
{
    $contest = array();
    $contest['page'] = $_REQUEST['page'];
    $contest['city'] = SearchDao::searchCity();
    $contest['status'] = SearchDao::searchStatusType(2);
    $contest['buildProperty'] = SearchDao::searchBuildProperty();
    if (isset($_REQUEST['hasSearch'])) {
        $contest['district'] = SearchDao::searchCity($_REQUEST['listCity']);
        $contest['plate'] = SearchDao::searchCity($_REQUEST['listCity'], $_REQUEST['listDistrict']);
        $contest['dicRentalPrice'] = searchDao::searchRentalPrice($_REQUEST['listCity']);
        $contest['dicArea'] = searchDao::searchArea($_REQUEST['listCity']);
        $contest['cityId'] = $_REQUEST['listCity'];
        $contest['districtId'] = $_REQUEST['listDistrict'];
        $contest['plateId'] = $_REQUEST['listPlate'];
        $contest['buildPropertyId'] = $_REQUEST['buildProperty'];
        $contest['rentalPrice'] = $_REQUEST['rentalPrice'];
        $contest['acreage'] = $_REQUEST['acreage'];
        $contest['statusId'] = $_REQUEST['status'];
        $contest['req']['organization'] = $_REQUEST['organization'];
        $contest['req'] = $_REQUEST;
    }
    $contest["house_type"] = 2;
    Timber::render("houseList.html", $contest);
}

function addRentTable()
{
    $rentHouseList = new rentHouseList();
    $rentHouseList->prepare_items();
    $rentHouseList->views();
    $rentHouseList->display();
}

?>




