import React from 'react';
import { Icon, Button, Spin, message, Table, Input, Modal, DatePicker, Upload, Select } from 'antd';
import { beforeUpload, getBase64, getActivityForm, getActivityType, splitUrl } 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 Avatar = React.createClass({
    getInitialState () {
        return {
            imageUrl: ''
        }
    },
    handleChange (info) {
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl }));
            this.props.urlData(info.file.response.data);
        }
    },
    componentWillReceiveProps (nextProps) {
        if (this.props.visible && !nextProps.visible) {
            this.state.imageUrl = null;
        };
    },
    render () {
        const imageUrl = this.state.imageUrl;
        return (
            <Upload
                className="avatar-uploader"
                name={this.props.name}
                showUploadList={false}
                action={globalConfig.context + "/api/admin/activity/upload"}
                data={{ 'sign': 'activity_title_picture' }}
                beforeUpload={beforeUpload}
                onChange={this.handleChange} >
                {
                    (imageUrl || this.props.imageUrl) ?
                        <img src={imageUrl || this.props.imageUrl} role="presentation" id={this.props.name} /> :
                        <Icon type="plus" className="avatar-uploader-trigger" />
                }
            </Upload>
        );
    }
});

const PicturesWall = React.createClass({
    getInitialState () {
        return {
            previewVisible: false,
            previewImage: '',
            fileList: [],
        }
    },
    handleCancel () {
        this.setState({ previewVisible: false })
    },
    handlePreview (file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    },
    handleChange (info) {
        let fileList = info.fileList;
        this.setState({ fileList });
        this.props.fileList(fileList);
    },
    componentWillReceiveProps (nextProps) {
        this.state.fileList = nextProps.pictureUrl;
    },
    render () {
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">点击上传</div>
            </div>
        );
        return (
            <div className="clearfix">
                <Upload
                    action={globalConfig.context + "/api/admin/activity/upload"}
                    data={{ 'sign': 'activity_content_picture' }}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange} >
                    {fileList.length >= 5 ? null : uploadButton}
                </Upload>
                <Modal maskClosable={false} visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
});

const Activity = React.createClass({
    loadData (pageNo) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/activity/list',
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                sTime: this.state.startDate, //活动开始时间(startTime起)
                eTime: this.state.endDate, //活动开始时间(startTime止)
                name: this.state.searchName,
                host: this.state.searchHost,
                type: this.state.searchType ? Number(this.state.searchType) : undefined, // 活动类型
                form: this.state.searchForm ? Number(this.state.searchForm) : undefined, //活动形式
            },
            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,
                            id: thisdata.id,
                            startTime: thisdata.startTime,
                            startTimeFormattedDate: thisdata.startTimeFormattedDate,
                            endTime: thisdata.endTime,
                            endTimeFormattedDate: thisdata.endTimeFormattedDate,
                            name: thisdata.name,
                            host: thisdata.host,
                            type: thisdata.type,
                            form: thisdata.form,
                            enrollDeadline: thisdata.enrollDeadline,
                            enrollDeadlineFormattedDate: thisdata.enrollDeadlineFormattedDate
                        });
                    };
                    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));
    },
    loadDetailData () {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/activity/detail',
            data: {
                id: this.state.RowData.id //新闻主键ID(数字类型,非字符串)
            },
            success: function (data) {
                let theObj = {}, theArr = [];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    theObj = data.data;
                    theArr = theObj.asist ? theObj.asist.split(',') : [];
                    theObj.imgUrls = theObj.imgUrls ? splitUrl(theObj.imgUrls, ',', globalConfig.avatarHost + '/upload') : [];
                };
                this.setState({
                    RowData: theObj,
                    asistArray: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState () {
        return {
            loading: false,
            visible: false,
            selectedRowKeys: [],
            selectedRows: [],
            asistArray: [],
            keysObj: {},
            RowData: {},
            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: 'name',
                    key: 'name',
                    width: '20%'
                }, {
                    title: '主办单位',
                    dataIndex: 'host',
                    key: 'host',
                }, {
                    title: '活动类型',
                    dataIndex: 'type',
                    key: 'type',
                    render: (text) => { return getActivityType(text); }
                }, {
                    title: '活动形式',
                    dataIndex: 'form',
                    key: 'form',
                    render: (text) => { return getActivityForm(text); }
                }, {
                    title: '报名截止时间',
                    dataIndex: 'enrollDeadlineFormattedDate',
                    key: 'enrollDeadlineFormattedDate'
                }, {
                    title: '活动开始时间',
                    dataIndex: 'startTimeFormattedDate',
                    key: 'startTimeFormattedDate'
                }
            ],
            tableData: []
        };
    },
    tableRowClick (record, index) {
        this.state.RowData = record;
        this.loadDetailData();
        this.setState({
            visible: true
        });
    },
    componentWillMount () {
        this.loadData();
        let theTypeOption = [], theFormOption = [];
        activityType.map((item) => {
            theTypeOption.push(
                <Select.Option key={item.value}>{item.key}</Select.Option>
            )
        });
        activityForm.map((item) => {
            theFormOption.push(
                <Select.Option key={item.value}>{item.key}</Select.Option>
            )
        });
        this.state.activityTypeOption = theTypeOption;
        this.state.activityFormOption = theFormOption;
    },
    submit () {
        if (!this.state.RowData.name) {
            message.warning('必须填写一个标题！');
            return;
        };
        if (!this.state.RowData.startTimeFormattedDate) {
            message.warning('必须选择一个活动开始时间！');
            return;
        };
        if (!this.state.RowData.type) {
            message.warning('必须选择一个活动类型！');
            return;
        };
        if (!this.state.RowData.form) {
            message.warning('必须选择一个活动形式！');
            return;
        };
        if (!this.state.RowData.address) {
            message.warning('必须选择一个活动地点！');
            return;
        };
        let imgUrls = null;
        if (this.state.RowData.imgUrls && this.state.RowData.imgUrls.length) {
            let picArr = [];
            this.state.RowData.imgUrls.map(function (item) {
                picArr.push(item.response.data);
            });
            imgUrls = picArr.join(",");
        };
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + (this.state.RowData.id ? '/api/admin/activity/update' : '/api/admin/activity/add'),
            data: {
                id: this.state.RowData.id || null, //主键，如果不填主键则为新增记录，填主键则为更新
                name: this.state.RowData.name,// 标题,
                address: this.state.RowData.address,// 活动地址,
                host: this.state.RowData.host,// 主办单位,
                undertake: this.state.RowData.undertake,// 承办单位,
                asist: this.state.asistArray ? this.state.asistArray.join(',') : undefined,// 协办单位A，协办单位B,
                type: this.state.RowData.type,// 0, //活动类型
                form: this.state.RowData.form,// 1, //活动形式
                imgUrls: imgUrls,// 活动图片,
                result: this.state.RowData.result,// 活动结果,
                titleUrl: this.state.RowData.titleUrl,// 题图URL,
                summary: this.state.RowData.summary,// 描述,
                startTimeFormattedDate: this.state.RowData.startTimeFormattedDate,// 2012-02-02, //活动开始时间 yyyy-MM-dd
                endTimeFormattedDate: this.state.RowData.endTimeFormattedDate,// 2012-09-09, //活动结束时间 yyyy-MM-dd
                enrollDeadlineFormattedDate: this.state.RowData.enrollDeadlineFormattedDate,// 2012-09-09, //报名结束时间 yyyy-MM-dd
            },
            success: function (data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success('保存成功!');
                    this.setState({ visible: false });
                    this.loadData();
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    cleanCache (sign) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/activity/cleanCache',
            data: {
                'cacheKey': sign
            },
            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));
    },
    delectRow () {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];
            if (rowItem.id) {
                deletedIds.push(rowItem.id)
            };
        };
        this.setState({
            selectedRowKeys: [],
            loading: deletedIds.length > 0
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/activity/delete",
            data: {
                ids: deletedIds
            }
        }).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));
    },
    reset () {
        this.state.startDate = undefined;
        this.state.endDate = undefined;
        this.state.searchName = undefined;
        this.state.searchHost = undefined;
        this.state.searchType = undefined;
        this.state.searchForm = 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" >
                <div className="admin-content-title">
                    <span>活动圈管理</span>
                    <Button type="primary" style={{ float: 'right' }}
                        onClick={() => { this.setState({ RowData: {}, visible: true }) }}>
                        添加<Icon type="plus" />
                    </Button>
                </div>
                <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.searchHost}
                            onChange={(e) => { this.setState({ searchHost: e.target.value }); }} />
                        <Select placeholder="活动类型"
                            style={{ width: 100 }}
                            value={this.state.searchType}
                            onChange={(e) => { this.setState({ searchType: e }) }}>
                            {this.state.activityTypeOption}
                        </Select>
                        <Select placeholder="活动形式"
                            style={{ width: 100 }}
                            value={this.state.searchForm}
                            onChange={(e) => { this.setState({ searchForm: e }) }}>
                            {this.state.activityFormOption}
                        </Select>
                        <span>活动时间</span>
                        <DatePicker style={{ width: 150 }}
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder="搜索开始时间"
                            value={this.state.startDate ? moment(this.state.startDate, "YYYY-MM-DD HH:mm:ss") : undefined}
                            onChange={(t, str) => {
                                this.setState({ startDate: str });
                            }} />
                        <span>到</span>
                        <DatePicker style={{ width: 150 }}
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder="搜索结束时间"
                            value={this.state.endDate ? moment(this.state.endDate, "YYYY-MM-DD HH:mm:ss") : undefined}
                            onChange={(t, str) => {
                                this.setState({ endDate: str });
                            }} />
                        <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('activity_portal_list_cache_key'); }}>清除缓存</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}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <Modal title="活动详情" width={600} className="activity-modal"
                    visible={this.state.visible}
                    maskClosable={false}
                    footer={null}
                    afterClose={() => { this.state.RowData = {}; this.state.asist = null; this.state.asistArray = []; }}
                    onCancel={() => { this.setState({ visible: false }) }} >
                    <Spin spinning={this.state.loading}>
                        <div className="clearfix">
                            <div className="modal-box">
                                <span className="modal-box-title">活动标题</span>
                                <div className="modal-box-detail">
                                    <Input value={this.state.RowData.name}
                                        onChange={(e) => {
                                            this.state.RowData.name = e.target.value;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">标题图片</span>
                                <div className="modal-box-detail clearfix" style={{ width: '360px' }}>
                                    <Avatar visible={this.state.visible}
                                        imageUrl={this.state.RowData.titleUrl ? (globalConfig.avatarHost + "/upload" + this.state.RowData.titleUrl) : null}
                                        urlData={(url) => { this.state.RowData.titleUrl = url }} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">活动描述</span>
                                <div className="modal-box-detail">
                                    <Input type="textarea" rows={4} value={this.state.RowData.summary}
                                        onChange={(e) => {
                                            this.state.RowData.summary = e.target.value;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">活动类型</span>
                                <div className="modal-box-detail" style={{ width: '160px' }}>
                                    <Select placeholder="选择活动类型"
                                        style={{ width: 120 }}
                                        value={this.state.RowData.type}
                                        onChange={(e) => {
                                            this.state.RowData.type = e;
                                            this.setState({ RowData: this.state.RowData });
                                        }}>
                                        {this.state.activityTypeOption}
                                    </Select>
                                </div>
                                <span className="modal-box-title">活动形式</span>
                                <div className="modal-box-detail" style={{ width: '160px' }}>
                                    <Select placeholder="选择活动形式"
                                        style={{ width: 120 }}
                                        value={this.state.RowData.form}
                                        onChange={(e) => {
                                            this.state.RowData.form = e;
                                            this.setState({ RowData: this.state.RowData });
                                        }}>
                                        {this.state.activityFormOption}
                                    </Select>
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">活动地址</span>
                                <div className="modal-box-detail">
                                    <Input value={this.state.RowData.address}
                                        onChange={(e) => {
                                            this.state.RowData.address = e.target.value;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">主办单位</span>
                                <div className="modal-box-detail">
                                    <Input value={this.state.RowData.host}
                                        onChange={(e) => {
                                            this.state.RowData.host = e.target.value;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">承办单位</span>
                                <div className="modal-box-detail">
                                    <Input value={this.state.RowData.undertake}
                                        onChange={(e) => {
                                            this.state.RowData.undertake = e.target.value;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">协办单位</span>
                                <div className="modal-box-detail">
                                    <Input value={this.state.asist} style={{ width: '320px', marginRight: '20px' }}
                                        onChange={(e) => { this.setState({ asist: e.target.value }); }} />
                                    <Button onClick={() => {
                                        let _me = this, theArr = this.state.asistArray.concat(), theBool = true;
                                        if (!theArr.length) {
                                            theArr.push(this.state.asist);
                                        } else {
                                            this.state.asistArray.map((item, i) => {
                                                if (item === _me.state.asist) {
                                                    theBool = false;
                                                };
                                            });
                                            if (theBool) {
                                                theArr.push(_me.state.asist);
                                            } else {
                                                message.warning('已经录入该单位!')
                                            }
                                        };
                                        this.setState({ asistArray: theArr, asist: null });
                                    }}>添加</Button>
                                </div>
                                <div className="modal-box-detail" style={{ marginLeft: '106px' }}>
                                    {this.state.asistArray.map((item, i) => {
                                        return <p key={i}>{item}</p>
                                    })}
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">活动时间</span>
                                <div className="modal-box-detail">
                                    <DatePicker style={{ width: '150px' }}
                                        showTime
                                        format="YYYY-MM-DD HH:mm:ss"
                                        placeholder="选择开始时间"
                                        value={this.state.RowData.startTimeFormattedDate ? moment(this.state.RowData.startTimeFormattedDate, "YYYY-MM-DD HH:mm:ss") : undefined}
                                        onChange={(t, str) => {
                                            this.state.RowData.startTimeFormattedDate = str;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                    <span>到</span>
                                    <DatePicker style={{ width: '150px' }}
                                        showTime
                                        format="YYYY-MM-DD HH:mm:ss"
                                        placeholder="选择结束时间"
                                        value={this.state.RowData.endTimeFormattedDate ? moment(this.state.RowData.endTimeFormattedDate, "YYYY-MM-DD HH:mm:ss") : undefined}
                                        onChange={(t, str) => {
                                            this.state.RowData.endTimeFormattedDate = str;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">报名截止时间</span>
                                <div className="modal-box-detail">
                                    <DatePicker style={{ width: '150px' }}
                                        showTime
                                        format="YYYY-MM-DD HH:mm:ss"
                                        placeholder="选择截止时间"
                                        value={this.state.RowData.enrollDeadlineFormattedDate ? moment(this.state.RowData.enrollDeadlineFormattedDate, "YYYY-MM-DD HH:mm:ss") : undefined}
                                        onChange={(t, str) => {
                                            this.state.RowData.enrollDeadlineFormattedDate = str;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">活动图片</span>
                                <div className="modal-box-detail">
                                    <PicturesWall
                                        fileList={(e) => { this.state.RowData.imgUrls = e; this.setState({ RowData: this.state.RowData }); }}
                                        pictureUrl={this.state.RowData.imgUrls || []} />
                                </div>
                            </div>
                            <div className="modal-box">
                                <span className="modal-box-title">活动结果描述</span>
                                <div className="modal-box-detail">
                                    <Input type="textarea" rows={4} value={this.state.RowData.result}
                                        onChange={(e) => {
                                            this.state.RowData.result = e.target.value;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                        </div>
                        <div className="modal-box">
                            <Button type="primary" onClick={this.submit}>提交</Button>
                            <Button type="ghost" onClick={() => { this.setState({ visible: false }) }}>取消</Button>
                        </div>
                    </Spin>
                </Modal>
            </div >
        );
    }
});

export default Activity;