import React from 'react';
import { Icon, Button, Spin, message, Table, Input, Modal, DatePicker, Upload, Select } from 'antd';
import { beforeUpload, getBase64 } from '../../../tools';
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.uid != nextProps.uid) {
            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/lecture/upload"}
                data={{ 'uid': this.props.uid, 'sign': 'lecture_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 Lecture = React.createClass({
    loadData(pageNo) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/banners/list',
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                key: this.state.searcchKey
            },
            success: function (data) {
                let theArr = [];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    for (let i = 0; i < data.data.length; i++) {
                        let thisdata = data.data[i];
                        theArr.push({
                            key: i,
                            id: thisdata.id, //主键
                            sign: thisdata.sign,  // 位置标示
                            text: thisdata.text,  //广告图描述
                            imgurl: thisdata.imgurl, //广告图url
                            url: thisdata.url, //跳转链接
                            width: thisdata.width, //宽度
                            height: thisdata.height, //高度
                            startDate: thisdata.startDate, //广告图开始时间
                            endDate: thisdata.endDate //广告图结束时间
                        });
                    };
                    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));
    },
    loadKeys() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            url: globalConfig.context + '/api/admin/banners/keys',
            success: function (data) {
                let theArr = [];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    for (let item in data.data) {
                        let thisdata = data.data[item];
                        theArr.push(
                            <Select.Option value={item} key={item}>{thisdata}</Select.Option>
                        );
                    };
                };
                this.setState({
                    keysOption: theArr,
                    keysObj: data.data
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            keysObj: {},
            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: 'sign',
                    key: 'sign',
                    render: text => { return keysObj[text] }
                }, {
                    title: '广告图描述',
                    dataIndex: 'text',
                    key: 'text',
                }, {
                    title: '广告图url',
                    dataIndex: 'imgurl',
                    key: 'imgurl',
                }, {
                    title: '跳转链接',
                    dataIndex: 'url',
                    key: 'url',
                }, {
                    title: '宽度',
                    dataIndex: 'width',
                    key: 'width',
                }, {
                    title: '高度',
                    dataIndex: 'height',
                    key: 'height',
                }, {
                    title: '开始时间',
                    dataIndex: 'startDate',
                    key: 'startDate',
                }, {
                    title: '结束时间',
                    dataIndex: 'endDate',
                    key: 'endDate',
                }
            ],
            tableData: []
        };
    },
    componentWillMount() {
        this.loadKeys();
        this.loadData();
    },
    submit() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + (this.state.addModal.id ? '/api/admin/lecture/update' : '/api/admin/lecture/add'),
            data: {
                'id': this.state.addModal.id,
                "uid": this.state.addModal.uid,
                "name": this.state.addModal.name,
                "summary": this.state.addModal.summary,
                "lectureUrl": this.state.addModal.lectureUrl,
                "lectureTimeFormattedDate": this.state.addModal.lectureTimeFormattedDate,
                "endTimeFormattedDate": this.state.addModal.endTimeFormattedDate,
                "hot": this.state.addModal.showBig ? 1 : 0,
                "dynamic": this.state.addModal.showStar ? 1 : 0
            },
            success: function (data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success('保存成功!');
                    this.setState({ addVisible: false });
                    this.loadData();
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    reset() {
        this.state.searchKey = undefined;
        this.loadData();
    },
    render() {
        return (
            <div className="admin-content" >
                <div className="admin-content-title">广告图管理</div>
                <div className="admin-content-warp">
                    <div className="admin-content-header">广告图列表</div>
                    <div className="admin-content-search">
                        <Select placeholder="选择广告图位置"
                            style={{ width: 200 }}
                            value={this.state.searchKey}
                            onChange={(e) => { this.setState({ searchKey: e }) }}>
                            {this.state.keysOption}
                        </Select>
                        <Button type="primary" onClick={this.loadData}>搜索</Button>
                        <Button onClick={this.reset}>重置</Button>
                    </div>
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.tableData}
                            pagination={this.state.pagination} />
                    </Spin>
                </div>
            </div>
        );
    }
});

export default Lecture;