<?php

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

class customerList extends WP_List_Table
{
    function __construct()
    {
        parent::__construct(array(
            'singular' => 'customerList',
            'plural' => 'customerList',
            'ajax' => false
        ));
    }

    function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'name':
                return '<a href="' . admin_url('admin.php?page=customer&edit=true&id=' . $item['id']) . '">' . $item[$column_name] . '</a>';
            default:
                return $item[$column_name];
        }
    }

    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['name'] = '姓名';
        $columns['demand_type'] = '需求类型';
        $columns['consultant_name'] = '置业顾问';
        $columns['status_name'] = '状态';
        $columns['customer_remark'] = '客户备注';
        return $columns;
    }
    function get_bulk_actions()
    {
        $actions = array(
            'allot' => '分配置业顾问'
        );
        return $actions;
    }

    function process_bulk_action()
    {
        $action = $this->current_action();
        if ($action) {
            $string = null;
            switch ($action) {
                case 'allot':
                    $consultant_id = $_POST['allot_consultant_id'];
                    if ($consultant_id) {
                        $string = '(' . implode(',', array_map('intval', $_POST['customerlist'])) . ')';
                        $result = DBManager::query('update ' . Config::TOSPUR_CUSTOMER_TABLE
                            . ' SET consultant_id = ' . $consultant_id
                            . ' where id in ' . $string);
                        if($result){
                            echo '<script>alert("分配置业顾问成功");</script>';
                        }
                    }
                    break;
            }
        }
    }

    function prepare_items()
    {
        $per_page = 10;
        $columns = $this->get_columns();
        $hidden = array();

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

        $this->process_bulk_action();

        $sql = "SELECT tcs.*,tc.name as consultant_name,ts.status_name,tc.subsidiaryId FROM tospur_customer tcs" .
            " left join (SELECT * FROM tospur_status where status_type = 5) as ts on tcs.status = ts.status_id" .
            " left join tospur_consultant tc on tcs.consultant_id = tc.id" .
            " left join tospur_organization torg on tc.subsidiaryId = torg.id" .
            " where 1 = 1";
        if (current_user_can('zygw')) {
            $sql = $sql . " and tcs.consultant_id = " . get_current_user_id();
        }
        if (isset($_REQUEST['organization']) && $_REQUEST['organization'] != -1) {
            $sql = $sql . " and tc.subsidiaryId = " . $_REQUEST['organization'];
        }
        if (isset($_REQUEST['status']) && $_REQUEST['status'] != -1) {
            $sql = $sql . " and tcs.status = " . $_REQUEST['status'];
        }
        if (isset($_REQUEST['customer_type']) && $_REQUEST['customer_type'] != -1) {
            $sql = $sql . " and tcs.customer_type = " . $_REQUEST['customer_type'];
        }
        if (isset($_REQUEST['demand_type']) && $_REQUEST['demand_type'] != -1) {
            $demand_type = null;
            switch ($_REQUEST['demand_type']) {
                case 0:
                    $demand_type = 'tcs.new_house';
                    break;
                case 1:
                    $demand_type = 'tcs.secondHand_house';
                    break;
                case 2:
                    $demand_type = 'tcs.rent_house';
                    break;
            }
            if ($demand_type) {
                $sql = $sql . " and " . $demand_type . " = 1";
            }
        }
        if (isset($_REQUEST['listCity']) && $_REQUEST["listCity"] != -1) {
            $sql = $sql . " and tcs.city_id = " . $_REQUEST["listCity"];
        }
        if (isset($_REQUEST['listDistrict']) && $_REQUEST["listDistrict"] != -1) {
            $sql = $sql . " and tcs.district_id = " . $_REQUEST["listDistrict"];
        }
        if (isset($_REQUEST['listPlate']) && $_REQUEST["listPlate"] != -1) {
            $sql = $sql . " and tcs.plate_id = " . $_REQUEST["listPlate"];
        }
        if (isset($_REQUEST['totalPrice']) && $_REQUEST["totalPrice"] != -1) {
            $priceArray = explode("-", $_REQUEST['totalPrice']);
            $sql = $sql . " and (tcs.min_totalPrice >= " . $priceArray[0] . " and tcs.max_totalPrice <= " . $priceArray[1] . ")";
        }
        if (isset($_REQUEST['rentalPrice']) && $_REQUEST["rentalPrice"] != -1) {
            $priceArray = explode("-", $_REQUEST['rentalPrice']);
            $sql = $sql . " and (tcs.min_rent >= " . $priceArray[0] . " and tcs.max_rent <= " . $priceArray[1] . ")";
        }
        if (isset($_REQUEST['buildProperty']) && $_REQUEST["buildProperty"] != -1) {
            if ($_REQUEST["buildProperty"] == 5) {
                $sql = $sql . " and (tcs.bedroom >= " . $_REQUEST["buildProperty"] . " or tcs.bedroom = -1)";
            } else {
                $sql = $sql . " and (tcs.bedroom = " . $_REQUEST["buildProperty"] . " or tcs.bedroom = -1)";
            }
        }
        if (isset($_REQUEST['acreage']) && $_REQUEST["acreage"] != -1) {
            $areaArray = explode("-", $_REQUEST['acreage']);
            $sql = $sql . " and (tcs.min_coveredArea >= " . $areaArray[0] . " and tcs.max_coveredArea <= " . $areaArray[1] . ")";
        }
        if (isset($_REQUEST['search_name'])) {
            $sql = $sql . " and tcs.name like '%" . $_REQUEST['search_name'] . "%'";
        }
        if (isset($_REQUEST['search_consultant_name'])) {
            $sql = $sql . " and tc.name like '%" . $_REQUEST['search_consultant_name'] . "%'";
        }
        if (isset($_REQUEST['search_phone'])) {
            $sql = $sql . " and tcs.phone like '%" . $_REQUEST['search_phone'] . "%'";
        }
        if (isset($_REQUEST['search_min_time']) && $_REQUEST['search_min_time'] != null) {
            $sql = $sql . " and tcs.time >= '" . $_REQUEST['search_min_time'] . "'";
        }
        if (isset($_REQUEST['search_max_time']) && $_REQUEST['search_max_time'] != null) {
            $sql = $sql . " and tcs.time <= '" . $_REQUEST['search_max_time'] . "'";
        }
        $result = DBManager::get_results($sql);
        $data = array();
        foreach ($result as $key => $value) {
            $demand_type_array = array(
                ($value->new_house == 1) ? '新房' : null,
                ($value->secondHand_house == 1) ? '二手房' : null,
                ($value->rent_house == 1) ? '租房' : null
            );
            $demand_type_array = array_filter($demand_type_array, function ($var) {
                return !is_null($var);
            });
            $data[$key] = array(
                'id' => $value->id,
                'name' => $value->name,
                'demand_type' => implode("、", $demand_type_array),
                'customer_remark' => $value->customer_remark,
                'consultant_id' => $value->consultant_id,
                'consultant_name' => $value->consultant_name,
                'status_name' => $value->status_name
            );
        }

        $current_page = $this->get_pagenum();

        $total_items = count($data);
        $total_pages = ceil($total_items / $per_page);

        if ($_REQUEST['paged'] > $total_pages) {
            $current_page = $total_pages;
        }

        $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 function_customerList()
{
    $context = array();

    $context['city'] = SearchDao::searchCity();
    if (isset($_REQUEST['hasSearch'])) {
        $context['req'] = $_REQUEST;
    }

    Timber::render("customerList.html", $context);
}

function addCustomerTable()
{
    $_SERVER['REQUEST_URI'] = remove_query_arg('_wp_http_referer', $_SERVER['REQUEST_URI']);
    $customerList = new customerList();
    $customerList->prepare_items();
    $customerList->display();
}

?>
