<?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 get_views(){
        global $wpdb;
        $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
        $current_url = remove_query_arg( array( 'paged','type'), $current_url );
        $sql = "select COUNT(*) as allNum,
                 COUNT(NULLIF(approval != -2, false)) as needCheckNum,
                 COUNT(NULLIF(approval = 0, false)) as unCheckNum,
                 COUNT(NULLIF(approval = 1, false)) as checkNum,
                 COUNT(NULLIF(approval = -1, false)) as onSaleNum,
                 COUNT(NULLIF(approval = 2, false)) as selfSaleNum,
                 COUNT(NULLIF(approval = 3, false)) as otherSaleNum,
                 COUNT(NULLIF(approval = 4, false)) as invalidNum,
                 COUNT(NULLIF(approval = 5, false)) as reactivationNum
                 from  ".Config::TOSPUR_HOUSE_TABLE." where  house_type = 1";
        $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.'&approval" class="current">全部<span class="count">（'.$approvalParam["allNum"].'）</span></a>',
            "needCheckNum" => '<a href="'.$current_url.'&approval=-2" class="current">需审批<span class="count">（'.$approvalParam["needCheckNum"].'）</span></a>',
            "unCheckNum" => '<a href="'.$current_url.'&approval=0">未审核<span class="count">（'.$approvalParam["unCheckNum"].'）</span></a>',
            "checkNum" => '<a href="'.$current_url.'&approval=1">审核<span class="count">（'.$approvalParam["checkNum"].'）</span></a>',
            "onSaleNum" => '<a href="'.$current_url.'&approval=-1">交易中<span class="count">（'.$approvalParam["onSaleNum"].'）</span></a>',
            "selfSaleNum" => '<a href="'.$current_url.'&approval=2">自售<span class="count">（'.$approvalParam["selfSaleNum"].'）</span></a>',
            "otherSaleNum" => '<a href="'.$current_url.'&approval=3">他售<span class="count">（'.$approvalParam["otherSaleNum"].'）</span></a>',
            "invalidNum" => '<a href="'.$current_url.'&approval=4">无效<span class="count">（'.$approvalParam["invalidNum"].'）</span></a>',
            "reactivationNum" => '<a href="'.$current_url.'&approval=5">重激活<span class="count">（'.$approvalParam["reactivationNum"].'）</span></a>',
        );
    }
    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 'average_price':
            case 'buildproperty_id':
            case 'covered_area':
            case 'floor':
            case 'faceto':
            case 'decoration':
            case 'age':
            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()
    {
        $columns = array(
            'cb' => '<input type="checkbox" />'
        );
        $columns['id']= 'ID';
        $columns['name']= '二手房标题';
        $columns['community_name']= '小区名称';
        $columns['total_price']= '总价';
        $columns['average_price']='单价';
        $columns['buildproperty_id']= '户型';
        $columns['covered_area']= '面积';
        $columns['floor']= '楼层';
        $columns['faceto']= '朝向';
        $columns['decoration']= '装修状况';
        $columns['age']= '年代';
        $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),
            'average_price' => array('average_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),
            '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" =>"退回"
            );
        }else{
            $actions = array(
                'unCheck'=>'未审核',
                'check' =>'审核',
                'onSale'=>'交易中',
                'selfSale'=>'自售',
                'otherSale'=>'他售',
                'invalid'=>'无效',
                'reactivation'=>'重激活'
            );
        }
        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['sechandhouselist'];
                    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['sechandhouselist'];
                    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) {
            global $wpdb;
            $id = $_REQUEST['sechandhouselist'];
            $string = null;
            $status = null;
            if($action == 'allot'){
                HouseDao::houseAllotConsultant($_POST['allot_consultant_id'], $_POST['sechandhouselist']);
            }else{
                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 'selfSale':
                        if ($id) {
                            $string = '(' . implode(',', array_map('intval', $id)) . ')';
                            $res = $this->getCurrentStatus($string,2);
                            if(!$res){
                                exit;
                            }
                            $status = $res;
                        }
                        break;
                    case 'otherSale':
                        if ($id) {
                            $string = '(' . implode(',', array_map('intval', $id)) . ')';
                            $res = $this->getCurrentStatus($string,3);
                            if(!$res){
                                exit;
                            }
                            $status = $res;
                        }
                        break;
                    case 'invalid':
                        if ($id) {
                            $string = '(' . implode(',', array_map('intval', $id)) . ')';
                            $res = $this->getCurrentStatus($string,4);
                            if(!$res){
                                exit;
                            }
                            $status = $res;
                        }
                        break;
                    case 'reactivation':
                        if ($id) {
                            $string = '(' . implode(',', array_map('intval', $id)) . ')';
                            $sql = "select status from tospur_house where id in".$string;
                            $res = $wpdb->get_results($sql);
                           foreach($res as $value){
                              if($value->status == 4){
                                  $status = 5;
                              }else{
                                  print_r("只有无效房源可重激活,请重新选择");
                                  exit;
                              }
                           }
                        }
                        break;
                    case 'onSale':
                        if ($id) {
                            $string = '(' . implode(',', array_map('intval', $id)) . ')';
                            $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=1  ";
        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"]!=-1){
            $params[] = $_REQUEST["status"];
            $sql = $sql." and status=%d";
        }

        if( isset( $_REQUEST["organization"]) && $_REQUEST["organization"] != -1 ){
            $params[] = $_REQUEST["organization"];
            $sql = $sql." and subsidiaryId=%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["searchText"]!=NULL){
            $params[] = '%'.$_REQUEST['searchText'].'%';
            $sql = $sql . " and name like %s";
        }

        if(isset($_REQUEST["approval"]) && $_REQUEST["approval"]!=""){
            if($_REQUEST["approval"] == -2){
                $params[] = $_REQUEST["approval"];
                $sql = $sql . " and approval != %d";
            }else{
                $params[] = $_REQUEST["approval"];
                $sql = $sql . " and approval = %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($_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,
                'total_price' => $value->total_price,
                'average_price' => $value->average_price,
                'buildproperty_id' => $value->literal,
                'covered_area' => $value->covered_area,
                'floor' => $value->floor,
                'faceto' => $value->faceto,
                'decoration' => $value->decoration,
                'age' => $value->age,
                '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');

function function_secHandHouseList()
{
    $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['dicTotalPrice'] = searchDao::searchTotalPrice($_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['totalPrice'] = $_REQUEST['totalPrice'];
        $contest['acreage'] = $_REQUEST['acreage'];
        $contest['statusId']  =  $_REQUEST['status'];
        $contest['req']['organization'] = $_REQUEST['organization'];
        $contest['req'] = $_REQUEST;
    }
    $contest["house_type"] = 1;
    Timber::render("houseList.html",$contest);
}
function addSecTable(){
    $secHandHouseList = new secHandHouseList();
    $secHandHouseList->prepare_items();
    $secHandHouseList->views();
    $secHandHouseList->display();
}
?>



