import React from 'react';
import { Icon, Button, Spin, message, Table, Input, Tabs, Select } from 'antd';
//import { getActivityForm, getActivityType } from '../../../tools';
//import { activityForm, activityType } from '../../../dataDic';
//import moment from 'moment';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';

const ActivityTable = React.createClass({
    loadData(pageNo, apiUrl) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + (apiUrl || this.props.apiUrl),
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                activityName: this.state.searchName,
                mobile: this.state.searchMobile,
                username: this.state.searchUsername,
                unitName: this.state.searchUnitName,
                number: this.state.searchNumber,
            },
            success: function (data) {
                let theArr = [];
                if (!data.data || !data.data.list) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    for (let i = 0; i < data.data.list.length; i++) {
                        let thisdata = data.data.list[i];
                        theArr.push({
                            key: i,
                            aid: thisdata.aid,
                            uid: thisdata.uid,
                            createTime: thisdata.createTime,
                            lastUpdateTime: thisdata.lastUpdateTime,
                            activityName: thisdata.activityName,
                            number: thisdata.number,
                            mobile: thisdata.mobile,
                            username: thisdata.username,
                            unitName: thisdata.unitName,
                            theName: thisdata.username || thisdata.unitName,
                            startTime: thisdata.startTime,
                            endTime: thisdata.endTime,
                            enrollDeadline: thisdata.enrollDeadline,
                            createTimeFormattedDate: thisdata.createTimeFormattedDate,
                            enrollDeadlineFormattedDate: thisdata.enrollDeadlineFormattedDate,
                            startTimeFormattedDate: thisdata.startTimeFormattedDate,
                            endTimeFormattedDate: thisdata.endTimeFormattedDate,
                            lastUpdateTimeFormattedDate: thisdata.lastUpdateTimeFormattedDate,
                        });
                    };
                    this.state.pagination.current = data.data.pageNo;
                    this.state.pagination.total = data.data.totalCount;
                };
                this.setState({
                    tableData: theArr,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            visible: false,
            selectedRowKeys: [],
            selectedRows: [],
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function (total) {
                    return '共' + total + '条数据';
                }
            },
            columns: [
                {
                    title: '报名用户名称',
                    dataIndex: 'theName',
                    key: 'theName'
                }, {
                    title: '活动名称',
                    dataIndex: 'activityName',
                    key: 'activityName',
                }, {
                    title: '阿凡提号',
                    dataIndex: 'number',
                    key: 'number'
                }, {
                    title: '联系方式',
                    dataIndex: 'mobile',
                    key: 'mobile'
                }, {
                    title: '首次报名/咨询时间',
                    dataIndex: 'createTimeFormattedDate',
                    key: 'createTimeFormattedDate'
                }, {
                    title: '最近一次报名/咨询时间',
                    dataIndex: 'lastUpdateTimeFormattedDate',
                    key: 'lastUpdateTimeFormattedDate'
                }, {
                    title: '活动截止报名时间',
                    dataIndex: 'enrollDeadlineFormattedDate',
                    key: 'enrollDeadlineFormattedDate'
                }
            ],
            tableData: []
        };
    },
    componentWillMount() {
        this.loadData();
    },
    componentWillReceiveProps(nextProps) {
        if (this.props.tableType !== nextProps.tableType) {
            this.loadData(nextProps.apiUrl)
        }
    },
    delectRow() {
        let theAid = null, theUid = null;
        if (this.state.selectedRows && this.state.selectedRows.length) {
            theAid = this.state.selectedRows[0].aid;
            theUid = this.state.selectedRows[0].uid;
        } else {
            return;
        }
        this.setState({
            selectedRowKeys: [],
            loading: true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/activityUser/delete',
            data: {
                aid: theAid,
                uid: theUid
            }
        }).done(function (data) {
            if (data.error && data.error.length) {
                message.warning(data.error[0].message);
            } else {
                message.success('删除成功！');
            };
            this.setState({
                loading: false,
            });
            this.loadData();
        }.bind(this));
    },
    cleanCache() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/activity/cleanCache',
            data: {
                'cacheKey': 'activity_portal_list_cache_key'
            },
            success: function (data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success('清除缓存成功!');
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    reset() {
        this.state.searchName = undefined;
        this.state.searchMobile = undefined;
        this.state.searchUsername = undefined;
        this.state.searchUnitName = undefined;
        this.state.searchNumber = undefined;
        this.loadData();
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows.slice(-1),
                    selectedRowKeys: selectedRowKeys.slice(-1),
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <div className="admin-content-warp">
                <div className="admin-content-search">
                    <Input placeholder="活动名称" style={{ width: 200 }}
                        value={this.state.searchName}
                        onChange={(e) => { this.setState({ searchName: e.target.value }); }} />
                    <Input placeholder="报名人电话" style={{ width: 200 }}
                        value={this.state.searchMobile}
                        onChange={(e) => { this.setState({ searchMobile: e.target.value }); }} />
                    {(() => {
                        switch (this.props.tableType) {
                            case 'user':
                                return <Input placeholder="报名人名称" style={{ width: 200 }}
                                    value={this.state.searchUsername}
                                    onChange={(e) => { this.setState({ searchUsername: e.target.value }); }} />
                            case 'org':
                                return <Input placeholder="报名人名称" style={{ width: 200 }}
                                    value={this.state.searchUnitName}
                                    onChange={(e) => { this.setState({ searchUnitName: e.target.value }); }} />
                        };
                    })()}
                    <Input placeholder="报名人阿凡提号" style={{ width: 200 }}
                        value={this.state.searchNumber}
                        onChange={(e) => { this.setState({ searchNumber: e.target.value }); }} />
                    <Button type="primary" onClick={() => { this.loadData() }}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <Button type='danger' disabled={!hasSelected} onClick={this.delectRow}>
                        删除<Icon type="minus" />
                    </Button>
                    <Button type="primary" onClick={() => { this.cleanCache() }}>清除缓存</Button>
                </div>
                <Spin spinning={this.state.loading}>
                    <Table className="no-all-select"
                        columns={this.state.columns}
                        dataSource={this.state.tableData}
                        pagination={this.state.pagination}
                        rowSelection={rowSelection} />
                </Spin>
            </div>
        )
    }
});

const ActivityUserList = React.createClass({
    getInitialState() {
        return {
            userApiUrl: '/api/admin/activityUser/userList',
            orgApiUrl: '/api/admin/activityUser/orgList',
            tableType: 'user'
        };
    },
    tabChange(key) {
        this.setState({ tableType: key });
    },
    render() {
        return (
            <div className="admin-content" >
                <div className="admin-content-title">
                    <span>活动圈报名管理</span>
                </div>
                <Tabs activeKey={this.state.tableType} onChange={this.tabChange}>
                    <Tabs.TabPane tab="个人报名管理" key="user">
                        <ActivityTable apiUrl={this.state.userApiUrl} tableType={'user'} />
                    </Tabs.TabPane>
                    <Tabs.TabPane tab="组织报名管理" key="org">
                        <ActivityTable apiUrl={this.state.orgApiUrl} tableType={'org'} />
                    </Tabs.TabPane>
                </Tabs>
            </div >
        );
    }
});
export default ActivityUserList;