import React from 'react';
import { Icon, Button, Spin, message, Table, Input, Modal, DatePicker, Upload, Select, Radio, Tabs } from 'antd';
import { beforeUpload, getBase64 } from '../../../tools';
import theme from 'react-quill/dist/quill.snow.css'
import ReactQuill from 'react-quill'
import moment from 'moment';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';

function uploadImg(s) {
    let myform = new FormData();
    myform.append('file', document.getElementById("fileToUpload").files[0]);
    myform.append('sign', 'news_content_picture');
    $.ajax({
        method: "post",
        dataType: "json",
        url: location.origin + "/api/admin/news/upload",
        data: myform,
        contentType: false,
        processData: false,
        success: function (data) {
            if (data.error && data.error.length) {
                message.warning(data.error[0].message);
            } else {
                let theUrl = data.data;
                const cursorPosition = s.quill.getSelection().index
                s.quill.insertEmbed(cursorPosition, 'image', globalConfig.avatarHost + '/upload' + theUrl)
                s.quill.setSelection(cursorPosition + 1)
            };
        }
    })
}
function fileSelect() {
    let uploader = document.getElementById("fileToUpload"), _me = this;
    uploader.onchange = () => {
        uploadImg(_me);
    };
    uploader.click();
}
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/news/upload"}
                data={{ 'sign': this.props.sign }}
                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 News = React.createClass({
    loadData(pageNo, theType) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/news/list',
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                type: theType || this.props.newsType || 0, //新闻类型
                title: this.state.searchTitle,
                author: this.state.searchAuthor,
                startCreateTime: this.state.startDate, //新闻开始时间 yyyy-MM-dd
                endCreateTime: this.state.endDate, //新闻结束时间 yyyy-MM-dd
                source: this.state.searchSource,
                hot: this.state.searchHot, //是否放在首页
            },
            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,
                            createTime: thisdata.createTime,
                            editTime: thisdata.editTime,
                            title: thisdata.title,
                            titleImg: thisdata.titleImg,
                            author: thisdata.author,
                            type: thisdata.type,
                            hot: thisdata.hot,
                            source: thisdata.source,
                            sourceUrl: thisdata.sourceUrl,
                            summary: thisdata.summary,
                            content: thisdata.content,
                            createTimeFormattedDate: thisdata.createTimeFormattedDate,
                        });
                    };
                    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/news/detail',
            data: {
                id: this.state.RowData.id //新闻主键ID(数字类型,非字符串)
            },
            success: function (data) {
                let theObj = {};
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    theObj = data.data;
                };
                this.setState({
                    RowData: theObj,
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            visible: false,
            selectedRowKeys: [],
            selectedRows: [],
            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: 'title',
                    key: 'title',
                    width: '20%'
                }, {
                    title: '发布时间',
                    dataIndex: 'createTimeFormattedDate',
                    key: 'createTimeFormattedDate',
                }, {
                    title: '作者',
                    dataIndex: 'author',
                    key: 'author',
                }, {
                    title: '来源',
                    dataIndex: 'source',
                    key: 'source',
                }, {
                    title: '简介',
                    dataIndex: 'summary',
                    key: 'summary',
                    width: '50%'
                }
            ],
            tableData: []
        };
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        this.loadDetailData();
        this.setState({
            visible: true
        });
    },
    componentWillMount() {
        this.loadData();
    },
    componentWillReceiveProps(nextProps) {
        if (this.props.newsType != nextProps.newsType) {
            this.loadData(1, nextProps.newsType);
        };
    },
    handleRichText(value) {
        console.log(value);
        this.state.RowData.content = value;
        this.setState({ RowData: this.state.RowData });
    },
    submit() {
        if (!this.state.RowData.title) {
            message.warning('必须填写一个标题！');
            return;
        };
        if (!this.state.RowData.createTime) {
            message.warning('必须选择一个发布时间！');
            return;
        };
        if (!this.state.RowData.author) {
            message.warning('必须填写一个作者！');
            return;
        };
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + (this.state.RowData.id ? '/api/admin/news/update' : '/api/admin/news/add'),
            data: {
                id: this.state.RowData.id || null, //主键，如果不填主键则为新增记录，填主键则为更新
                title: this.state.RowData.title,
                titleImg: this.state.RowData.titleImg,
                author: this.state.RowData.author,
                type: this.props.newsType,
                hot: this.state.RowData.hot,
                source: this.state.RowData.source,
                sourceUrl: this.state.RowData.sourceUrl,
                summary: this.state.RowData.summary,
                content: this.state.RowData.content,
                createTimeFormattedDate: this.state.RowData.createTimeFormattedDate,
            },
            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));
    },
    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/news/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.searchKey = 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;
        const modules = {
            toolbar: {
                container: [
                    [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
                    [{ 'header': [1, 2, 3, false] }],

                    ['bold', 'italic', 'underline', 'strike', 'blockquote'],        // toggled buttons

                    //  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
                    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                    //  [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
                    [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
                    //  [{ 'direction': 'rtl' }],                         // text direction

                    [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
                    //  [{ 'font': [] }],
                    [{ 'align': [] }],
                    ['link', 'image'],
                    ['clean']
                ],
                handlers: { 'image': fileSelect }
            }
        };
        const formats = [
            'size', 'header',
            'bold', 'italic', 'underline', 'strike', 'blockquote',
            'list', 'bullet', 'indent',
            'color', 'background',
            'align',
            'link', 'image'
        ];
        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">
                        <Input placeholder="标题" style={{ width: 200 }}
                            value={this.state.searchTitle}
                            onChange={(e) => { this.setState({ searchTitle: e.target.value }); }} />
                        <Input placeholder="作者" style={{ width: 100 }}
                            value={this.state.searchAuthor}
                            onChange={(e) => { this.setState({ searchAuthor: e.target.value }); }} />
                        <Input placeholder="来源" style={{ width: 100 }}
                            value={this.state.searchSource}
                            onChange={(e) => { this.setState({ searchSource: e.target.value }); }} />
                        <Select placeholder="显示在首页"
                            style={{ width: 100 }}
                            value={this.state.searchHot}
                            onChange={(e) => { this.setState({ searchHot: e }) }}>
                            <Select.Option value="0" >不显示</Select.Option>
                            <Select.Option value="1" >显示</Select.Option>
                        </Select>
                        <span>发布时间</span>
                        <DatePicker style={{ width: 110 }}
                            format="YYYY-MM-DD"
                            placeholder="选择开始时间"
                            value={this.state.startDate ? moment(this.state.startDate, "YYYY-MM-DD") : undefined}
                            onChange={(t, str) => {
                                this.setState({ startDate: str });
                            }} />
                        <span>到</span>
                        <DatePicker style={{ width: 110 }}
                            format="YYYY-MM-DD"
                            placeholder="选择结束时间"
                            value={this.state.endDate ? moment(this.state.endDate, "YYYY-MM-DD") : 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" style={{ float: 'right' }}
                            onClick={() => { this.setState({ RowData: {}, visible: true }) }}>
                            添加<Icon type="plus" />
                        </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={1000} className="news-modal"
                    visible={this.state.visible}
                    maskClosable={false}
                    footer={null}
                    afterClose={() => { this.state.RowData = {}; }}
                    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.title}
                                        onChange={(e) => {
                                            this.state.RowData.title = 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.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">
                                    <Input value={this.state.RowData.source}
                                        onChange={(e) => {
                                            this.state.RowData.source = 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.sourceUrl}
                                        onChange={(e) => {
                                            this.state.RowData.sourceUrl = e.target.value;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box" style={{ position: 'absolute', right: '0', width: '480px' }}>
                                <span className="modal-box-title">标题图片</span>
                                <div className="modal-box-detail clearfix" style={{ width: '360px' }}>
                                    <Avatar sign={'news'} visible={this.state.visible}
                                        imageUrl={this.state.RowData.titleImg ? (globalConfig.avatarHost + "/upload" + this.state.RowData.imgurl) : null}
                                        urlData={(url) => { this.state.RowData.titleImg = url }} />
                                </div>
                            </div>
                        </div>
                        <div className="clearfix">
                            <div className="modal-box news-box">
                                <span className="modal-box-title">作者</span>
                                <div className="modal-box-detail">
                                    <Input value={this.state.RowData.author}
                                        onChange={(e) => {
                                            this.state.RowData.author = e.target.value;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box news-box">
                                <span className="modal-box-title">发布时间</span>
                                <div className="modal-box-detail">
                                    <DatePicker style={{ width: '120px' }}
                                        format="YYYY-MM-DD"
                                        placeholder="选择发布时间"
                                        value={this.state.RowData.createTimeFormattedDate ? moment(this.state.RowData.createTimeFormattedDate, "YYYY-MM-DD") : undefined}
                                        onChange={(t, str) => {
                                            this.state.RowData.createTimeFormattedDate = str;
                                            this.setState({ RowData: this.state.RowData });
                                        }} />
                                </div>
                            </div>
                            <div className="modal-box news-box">
                                <span className="modal-box-title">发布在首页</span>
                                <div className="modal-box-detail">
                                    <Radio.Group value={this.state.RowData.hot} onChange={(e) => {
                                        this.state.RowData.hot = e.target.value;
                                        this.setState({ RowData: this.state.RowData });
                                    }} >
                                        <Radio value={0}>否</Radio>
                                        <Radio value={1}>是</Radio>
                                    </Radio.Group>
                                </div>
                            </div>
                        </div>
                        <div className="modal-box">
                            <span className="modal-box-title">新闻内容</span>
                        </div>
                        <ReactQuill theme="snow"
                            value={this.state.RowData.content}
                            modules={modules}
                            formats={formats}
                            onChange={this.handleRichText} />
                        <input type="file"
                            name="fileToUpload"
                            id="fileToUpload"
                            style={{ "display": "none" }} />
                        <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 News;