import React from 'react';
import { Icon, Button, Spin, message, Table, Cascader, Input, Modal, DatePicker, Upload, Checkbox } from 'antd';
import { techFieldList, getTechField } from '../../../DicTechFieldList';
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({
    loadLectureData(pageNo) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/lecture/list',
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.lecturePagination.pageSize,
                username: this.state.searchLectureUser, //用户名称
                name: this.state.searchLectureName, //讲座名称
                startLectureTime: this.state.startLectureTime,
                endLectureTime: this.state.endLectureTime
            },
            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,
                            uid: thisdata.uid,
                            lectureTime: thisdata.lectureTime,
                            lecturer: thisdata.lecturer,
                            endTime: thisdata.endTime,
                            name: thisdata.name,
                            summary: thisdata.summary,
                            username: thisdata.username,
                            lectureUrl: thisdata.lectureUrl,
                            lectureTimeFormattedDate: thisdata.lectureTimeFormattedDate,
                            endTimeFormattedDate: thisdata.endTimeFormattedDate,
                            hot: thisdata.hot,
                            dynamic: thisdata.dynamic
                        });
                    };
                    this.state.lecturePagination.current = data.data.pageNo;
                    this.state.lecturePagination.total = data.data.totalCount;
                };
                this.setState({
                    lectureTableData: theArr,
                    lecturePagination: this.state.lecturePagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    loadHotData() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/lecture/hotList',
            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,
                            uid: thisdata.uid,
                            lectureTime: thisdata.lectureTime,
                            lecturer: thisdata.lecturer,
                            endTime: thisdata.endTime,
                            name: thisdata.name,
                            summary: thisdata.summary,
                            username: thisdata.username,
                            lectureUrl: thisdata.lectureUrl,
                            lectureTimeFormattedDate: thisdata.lectureTimeFormattedDate,
                            endTimeFormattedDate: thisdata.endTimeFormattedDate,
                            hot: thisdata.hot,
                            dynamic: thisdata.dynamic
                        });
                    };
                };
                this.setState({
                    hotTableData: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    loadDynamicData() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/lecture/dynamic',
            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,
                            uid: thisdata.uid,
                            lectureTime: thisdata.lectureTime,
                            lecturer: thisdata.lecturer,
                            endTime: thisdata.endTime,
                            name: thisdata.name,
                            summary: thisdata.summary,
                            username: thisdata.username,
                            lectureUrl: thisdata.lectureUrl,
                            lectureTimeFormattedDate: thisdata.lectureTimeFormattedDate,
                            endTimeFormattedDate: thisdata.endTimeFormattedDate,
                            hot: thisdata.hot,
                            dynamic: thisdata.dynamic
                        });
                    };
                };
                this.setState({
                    dynamicTableData: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    loadData() {
        this.loadLectureData();
        this.loadHotData();
        this.loadDynamicData();
    },
    getInitialState() {
        return {
            loading: false,
            addVisible: false,
            addModal: {},
            selectedRowKeys: [],
            selectedRows: [],
            lecturePagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadLectureData(page);
                }.bind(this),
                showTotal: function (total) {
                    return '共' + total + '条数据';
                }
            },
            lectureColumns: [
                {
                    title: '讲堂名称',
                    dataIndex: 'name',
                    key: 'name',
                }, {
                    title: '开讲人姓名',
                    dataIndex: 'lecturer',
                    key: 'lecturer',
                }, {
                    title: '描述',
                    dataIndex: 'summary',
                    key: 'summary',
                    width: '50%'
                }, {
                    title: '开始时间',
                    dataIndex: 'lectureTimeFormattedDate',
                    key: 'lectureTimeFormattedDate',
                }, {
                    title: '结束时间',
                    dataIndex: 'endTimeFormattedDate',
                    key: 'endTimeFormattedDate',
                }, {
                    title: '展示图',
                    dataIndex: 'lectureUrl',
                    key: 'lectureUrl',
                    render: text => {
                        if (text) {
                            return '已上传'
                        } else {
                            return '未上传'
                        };
                    }
                }
            ],
            userTableData: [],
            lectureTableData: [],
            hotTableData: [],
            dynamicTableData: []
        };
    },
    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/lecture/delete",
            data: {
                ids: deletedIds
            }
        }).done(function (data) {
            if (data.error && data.error.length) {
                message.warning(data.error[0].message);
            } else {
                message.success('删除成功！');
                this.loadData();
            };
            this.setState({
                loading: false,
            });
        }.bind(this));
    },
    componentWillMount() {
        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,
                "lecturer": this.state.addModal.lecturer,
                "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));
    },
    cleanCache(sign) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/lecture/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));
    },
    // resetUser() {
    //     this.state.searchUserNumber = undefined;
    //     this.state.searchUserName = undefined;
    //     this.state.searchField = undefined;
    //     this.state.searchPfs = undefined;
    //     this.state.searchUnit = undefined;
    //     this.loadUserData();
    // },
    resetList() {
        this.state.searchLectureUser = undefined;
        this.state.searchLectureName = undefined;
        this.state.startLectureTime = undefined;
        this.state.endLectureTime = undefined;
        this.loadLectureData();
    },
    addClick() {
        this.setState({
            addVisible: true
        });
    },
    listTableRowClick(record, index) {
        this.state.addModal = record;
        this.state.addModal.showBig = record.hot ? true : false;
        this.state.addModal.showStar = record.dynamic ? true : false;
        this.setState({
            addVisible: true
        });
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <div className="admin-content" >
                <div className="admin-content-title">科技讲堂管理</div>
                <div className="admin-content-warp">
                    <div className="admin-content-header">
                        <span>讲堂列表</span>
                        <Button type="primary" onClick={() => { this.cleanCache('lecture_list_cache_key'); }}>清除缓存</Button>
                        <Button type='danger' disabled={!hasSelected} onClick={this.delectRow}>
                            删除<Icon type="minus" />
                        </Button>
                        <Button type="primary" onClick={() => { this.addClick(); }}>新增</Button>
                    </div>
                    <div className="admin-content-search">
                        <Input placeholder="开讲人名称" style={{ width: 160 }}
                            value={this.state.searchLectureUser}
                            onChange={(e) => { this.setState({ searchLectureUser: e.target.value }); }} />
                        <Input placeholder="讲座标题" style={{ width: 160 }}
                            value={this.state.searchLectureName}
                            onChange={(e) => { this.setState({ searchLectureName: e.target.value }); }} />
                        <span>开始时间</span>
                        <DatePicker
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder="选择开始搜索时间"
                            value={this.state.startLectureTime ? moment(this.state.startLectureTime, "YYYY-MM-DD HH:mm:ss") : undefined}
                            onChange={(t, str) => {
                                this.setState({ startLectureTime: str });
                            }} />
                        <span>到</span>
                        <DatePicker
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder="选择结束搜索时间"
                            value={this.state.endLectureTime ? moment(this.state.endLectureTime, "YYYY-MM-DD HH:mm:ss") : undefined}
                            onChange={(t, str) => {
                                this.setState({ endLectureTime: str });
                            }} />
                        <Button type="primary" onClick={() => { this.loadLectureData() }}>搜索</Button>
                        <Button onClick={this.resetList}>重置</Button>
                    </div>
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.lectureColumns}
                            dataSource={this.state.lectureTableData}
                            rowSelection={rowSelection}
                            onRowClick={this.listTableRowClick}
                            pagination={this.state.lecturePagination} />
                    </Spin>
                </div>
                <div className="clearfix">
                    <div className="admin-content-warp" style={{ width: '50%', float: 'left' }}>
                        <div className="admin-content-header">
                            <span>大咖页列表</span>
                            <Button type="primary" onClick={() => { this.cleanCache('big_shot_lecture_cache_key'); }}>清除缓存</Button>
                        </div>
                        <Spin spinning={this.state.loading}>
                            <Table columns={this.state.lectureColumns}
                                dataSource={this.state.hotTableData}
                                onRowClick={this.listTableRowClick}
                                pagination={false} />
                        </Spin>
                    </div>
                    <div className="admin-content-warp" style={{ width: '50%', float: 'left' }}>
                        <div className="admin-content-header">
                            <span>明星动态列表</span>
                            <Button type="primary" onClick={() => { this.cleanCache('lecture_dynamic_list_cache_key'); }}>清除缓存</Button>
                        </div>
                        <Spin spinning={this.state.loading}>
                            <Table columns={this.state.lectureColumns}
                                dataSource={this.state.dynamicTableData}
                                onRowClick={this.listTableRowClick}
                                pagination={false} />
                        </Spin>
                    </div>
                </div>
                <Modal
                    title="科技讲堂详情" width={600}
                    visible={this.state.addVisible}
                    maskClosable={false}
                    footer={null}
                    afterClose={() => { this.state.addModal = {} }}
                    onCancel={() => { this.setState({ addVisible: false }) }} >
                    <Spin spinning={this.state.loading}>
                        <div className="modal-box">
                            <span className="modal-box-title">开讲人</span>
                            <div className="modal-box-detail">
                                <Input value={this.state.addModal.lecturer}
                                    onChange={(e) => {
                                        this.state.addModal.lecturer = e.target.value;
                                        this.setState({ addModal: this.state.addModal });
                                    }} />
                            </div>
                        </div>
                        <div className="modal-box">
                            <span className="modal-box-title">讲堂标题</span>
                            <div className="modal-box-detail">
                                <Input value={this.state.addModal.name}
                                    onChange={(e) => {
                                        this.state.addModal.name = e.target.value;
                                        this.setState({ addModal: this.state.addModal });
                                    }} />
                            </div>
                        </div>
                        <div className="modal-box">
                            <span className="modal-box-title">讲堂描述</span>
                            <div className="modal-box-detail">
                                <Input type="textarea" value={this.state.addModal.summary} rows={4}
                                    onChange={(e) => {
                                        this.state.addModal.summary = e.target.value;
                                        this.setState({ addModal: this.state.addModal });
                                    }} />
                            </div>
                        </div>
                        <div className="modal-box">
                            <span className="modal-box-title">开讲时间</span>
                            <div className="modal-box-detail">
                                <DatePicker
                                    showTime
                                    format="YYYY-MM-DD HH:mm:ss"
                                    placeholder="选择开始时间"
                                    value={this.state.addModal.lectureTimeFormattedDate ? moment(this.state.addModal.lectureTimeFormattedDate, "YYYY-MM-DD HH:mm:ss") : undefined}
                                    onChange={(t, str) => {
                                        this.state.addModal.lectureTimeFormattedDate = str;
                                        this.setState({ addModal: this.state.addModal });
                                    }} />
                                <span>到</span>
                                <DatePicker
                                    showTime
                                    format="YYYY-MM-DD HH:mm:ss"
                                    placeholder="选择结束时间"
                                    value={this.state.addModal.endTimeFormattedDate ? moment(this.state.addModal.endTimeFormattedDate, "YYYY-MM-DD HH:mm:ss") : undefined}
                                    onChange={(t, str) => {
                                        this.state.addModal.endTimeFormattedDate = str;
                                        this.setState({ addModal: this.state.addModal });
                                    }} />
                            </div>
                        </div>
                        <div className="modal-box">
                            <span className="modal-box-title">讲堂图片</span>
                            <div className="modal-box-detail clearfix">
                                <Avatar uid={this.state.addModal.uid}
                                    imageUrl={this.state.addModal.lectureUrl ? (globalConfig.avatarHost + "/upload" + this.state.addModal.lectureUrl) : null}
                                    urlData={(url) => { this.state.addModal.lectureUrl = url }} />
                            </div>
                        </div>
                        <div className="modal-box">
                            <span className="modal-box-title">其他选项</span>
                            <div className="modal-box-detail clearfix">
                                <Checkbox checked={this.state.addModal.showBig}
                                    onChange={(e) => {
                                        this.state.addModal.showBig = e.target.checked;
                                        this.setState({ addModal: this.state.addModal });
                                    }}>显示到大咖说</Checkbox>
                                <Checkbox checked={this.state.addModal.showStar}
                                    onChange={(e) => {
                                        this.state.addModal.showStar = e.target.checked;
                                        this.setState({ addModal: this.state.addModal });
                                    }}>显示到明星动态</Checkbox>
                            </div>
                        </div>
                        <div className="modal-box">
                            <Button type="primary" onClick={this.submit}>提交</Button>
                            <Button type="ghost" onClick={() => { this.setState({ addVisible: false }) }}>取消</Button>
                        </div>
                    </Spin>
                </Modal>
            </div>
        );
    }
});

export default Lecture;

    // loadUserData(pageNo) {
    //     this.setState({
    //         loading: true
    //     });
    //     $.ajax({
    //         method: "get",
    //         dataType: "json",
    //         crossDomain: false,
    //         url: globalConfig.context + '/api/admin/lecture/starAndExpertList',
    //         data: {
    //             pageNo: pageNo || 1,
    //             pageSize: this.state.userPagination.pageSize,
    //             number: this.state.searchUserNumber, //编号
    //             username: this.state.searchUserName, //名称
    //             engagedField: this.state.searchField ? this.state.searchField.join(',') : undefined,
    //             professionalTitle: this.state.searchPfs,
    //             workUnit: this.state.searchUnit
    //         },
    //         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,
    //                         uid: thisdata.uid,
    //                         engagedField: thisdata.engagedField ? thisdata.engagedField.split(',') : [],
    //                         username: thisdata.username,
    //                         professionalTitle: thisdata.professionalTitle,
    //                         workUnit: thisdata.workUnit,
    //                         number: thisdata.number,
    //                         achievementNums: thisdata.achievementNums,
    //                     });
    //                 };
    //                 this.state.userPagination.current = data.data.pageNo;
    //                 this.state.userPagination.total = data.data.totalCount;
    //             };
    //             this.setState({
    //                 userTableData: theArr,
    //                 userPagination: this.state.userPagination
    //             });
    //         }.bind(this),
    //     }).always(function () {
    //         this.setState({
    //             loading: false
    //         });
    //     }.bind(this));
    // },

                // <div className="admin-content-warp">
                //     <div className="admin-content-header">专家明星列表</div>
                //     <div className="admin-content-search">
                //         <Input placeholder="编号" style={{ width: 100 }}
                //             value={this.state.searchUserNumber}
                //             onChange={(e) => { this.setState({ searchUserNumber: e.target.value }); }} />
                //         <Input placeholder="专家明星名称" style={{ width: 160 }}
                //             value={this.state.searchUserName}
                //             onChange={(e) => { this.setState({ searchUserName: e.target.value }); }} />
                //         <Cascader placeholder="请选择一个行业" style={{ width: 300 }}
                //             options={techFieldList}
                //             value={this.state.searchField}
                //             onChange={(e) => { this.setState({ searchField: e }) }} />
                //         <Input placeholder="职称名字" style={{ width: 160 }}
                //             value={this.state.searchPfs}
                //             onChange={(e) => { this.setState({ searchPfs: e.target.value }); }} />
                //         <Input placeholder="工作单位" style={{ width: 160 }}
                //             value={this.state.searchUnit}
                //             onChange={(e) => { this.setState({ searchUnit: e.target.value }); }} />
                //         <Button type="primary" onClick={() => { this.loadUserData() }}>搜索</Button>
                //         <Button onClick={this.resetUser}>重置</Button>
                //     </div>
                //     <Spin spinning={this.state.loading}>
                //         <Table columns={this.state.userColumns}
                //             dataSource={this.state.userTableData}
                //             pagination={this.state.userPagination}
                //             onRowClick={this.userTableRowClick} />
                //     </Spin>
                // </div>