import React from 'react';
import { Icon, Button, Spin, message, Table, Cascader, Input } from 'antd';
import { techFieldList, getTechField } from '../../../DicTechFieldList';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';

const Star = React.createClass({
    loadData(pageNo) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/star/list',
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                number: this.state.searchNumber, //编号
                username: this.state.searchName, //名称
                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: thisdata.uid,
                            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.pagination.current = data.data.pageNo;
                    this.state.pagination.total = data.data.totalCount;
                };
                this.setState({
                    dataSource: theArr,
                    pagination: this.state.pagination
                });
            }.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/star/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: thisdata.uid,
                            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.setState({
                    hotTableData: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    loadStarData() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/star/starList',
            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: thisdata.uid,
                            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.setState({
                    starTableData: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            hotSelectedRowKeys: [],
            hotSelectedRows: [],
            starSelectedRowKeys: [],
            starSelectedRows: [],
            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: 'number',
                    key: 'number',
                }, {
                    title: '姓名',
                    dataIndex: 'username',
                    key: 'username',
                }, {
                    title: '从事领域',
                    dataIndex: 'engagedField',
                    key: 'engagedField',
                    render: text => { return getTechField(text[0], text[1], text[2]); }
                }, {
                    title: '职称名字',
                    dataIndex: 'professionalTitle',
                    key: 'professionalTitle',
                }, {
                    title: '工作单位',
                    dataIndex: 'workUnit',
                    key: 'workUnit',
                }, {
                    title: '成果数量',
                    dataIndex: 'achievementNums',
                    key: 'achievementNums',
                }, {
                    title: '操作',
                    dataIndex: 'action',
                    key: 'action',
                    render: (text, record, index) => {
                        return <div>
                            <Button onClick={() => { this.addIndex(record) }} type="primary" style={{ marginRight: '10px' }}>添加到大咖说</Button>
                            <Button onClick={() => { this.addStar(record) }} type="primary">添加到明星页</Button>
                        </div>
                    }
                }
            ],
            otherColumns: [
                {
                    title: '编号',
                    dataIndex: 'number',
                    key: 'number',
                }, {
                    title: '姓名',
                    dataIndex: 'username',
                    key: 'username',
                }, {
                    title: '从事领域',
                    dataIndex: 'engagedField',
                    key: 'engagedField',
                    render: text => { return getTechField(text[0], text[1], text[2]); }
                }, {
                    title: '职称名字',
                    dataIndex: 'professionalTitle',
                    key: 'professionalTitle',
                }, {
                    title: '工作单位',
                    dataIndex: 'workUnit',
                    key: 'workUnit',
                }, {
                    title: '成果数量',
                    dataIndex: 'achievementNums',
                    key: 'achievementNums',
                }
            ],
            dataSource: [],
            hotTableData: [],
            starTableData: []
        };
    },
    addIndex(record) {
        let theBool = true;
        if (this.state.hotTableData.length == 4) {
            message.warning('大咖列表最多只能显示4条记录！');
            theBool = false;
        };
        this.state.hotTableData.map((item, i) => {
            if (item.uid == record.uid) {
                message.warning('该条记录已经存在于大咖列表中！');
                theBool = false;
                return;
            };
        });
        if (theBool) {
            this.state.hotTableData.push(record);
            this.setState({ hotTableData: this.state.hotTableData });
        };
    },
    addStar(record) {
        let theBool = true;
        if (this.state.starTableData.length == 6) {
            message.warning('明星列表最多只能显示6条记录！');
            theBool = false;
        };
        this.state.starTableData.map((item, i) => {
            if (item.uid == record.uid) {
                message.warning('该条记录已经存在于明星列表中！');
                theBool = false;
                return;
            };
        });
        if (theBool) {
            this.state.starTableData.push(record);
            this.setState({ starTableData: this.state.starTableData });
        };
    },
    hotDelectRow() {
        let deletedArr = this.state.hotTableData.concat();
        for (let idx = 0; idx < this.state.hotSelectedRows.length; idx++) {
            let deleteIndex = this.state.hotSelectedRows[idx];
            if (deleteIndex.uid) {
                for (let n = 0; n < deletedArr.length; n++) {
                    if (deleteIndex.uid == deletedArr[n].uid) {
                        deletedArr.splice(n, 1);
                    };
                };
            };
        };
        this.setState({
            hotTableData: deletedArr,
            hotSelectedRowKeys: []
        });
    },
    starDelectRow() {
        let deletedArr = this.state.starTableData.concat();
        for (let idx = 0; idx < this.state.starSelectedRows.length; idx++) {
            let deleteIndex = this.state.starSelectedRows[idx];
            if (deleteIndex.uid) {
                for (let n = 0; n < deletedArr.length; n++) {
                    if (deleteIndex.uid == deletedArr[n].uid) {
                        deletedArr.splice(n, 1);
                    };
                };
            };
        };
        this.setState({
            starTableData: deletedArr,
            starSelectedRowKeys: []
        });
    },
    componentWillMount() {
        this.loadData();
        this.loadHotData();
        this.loadStarData();
    },
    submit() {
        let hotArr = [], starArr = [];
        for (let i = 0; i < this.state.hotTableData.length; i++) {
            let hotUid = this.state.hotTableData[i].uid;
            if (hotUid) {
                hotArr.push(hotUid);
            };
        };
        for (let n = 0; n < this.state.starTableData.length; n++) {
            let starUid = this.state.starTableData[n].uid;
            if (starUid) {
                starArr.push({
                    uid: starUid,
                    star: 1
                });
            };
        };
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/star/save',
            data: {
                data: JSON.stringify(starArr),
                hot: hotArr
            },
            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));
    },
    cleanCache() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/star/cleanCache',
            data: {
                'cacheKey': 'big_shot_star_cache_key'
            },
            success: function (data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success('清除缓存成功!');
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.searchPfs = undefined;
        this.state.searchUnit = undefined;
        this.state.searchNumber = undefined;
        this.state.searchName = undefined;
        this.state.searchField = [];
        this.loadData();
    },
    render() {
        const hotRowSelection = {
            selectedRowKeys: this.state.hotSelectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    hotSelectedRows: selectedRows,
                    hotSelectedRowKeys: selectedRowKeys
                });
            }
        };
        const starRowSelection = {
            selectedRowKeys: this.state.starSelectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    starSelectedRows: selectedRows,
                    starSelectedRowKeys: selectedRowKeys
                });
            }
        };
        const hotHasSelected = this.state.hotSelectedRowKeys.length > 0;
        const starHasSelected = this.state.starSelectedRowKeys.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>
                    </div>
                    <div className="admin-content-search">
                        <Input placeholder="编号" style={{ width: 100 }}
                            value={this.state.searchNumber}
                            onChange={(e) => { this.setState({ searchNumber: e.target.value }); }} />
                        <Input placeholder="用户名" style={{ width: 160 }}
                            value={this.state.searchName}
                            onChange={(e) => { this.setState({ searchName: 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.search}>搜索</Button>
                        <Button onClick={this.reset}>重置</Button>
                        <Button type="primary" onClick={() => { this.cleanCache(); }}>清除缓存</Button>
                    </div>
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination} />
                    </Spin>
                </div>
                <div className="clearfix">
                    <div className="admin-content-warp" style={{ width: '50%', float: 'left' }}>
                        <div className="admin-content-header">
                            <span>大咖显示列表</span>
                            <Button type='danger' disabled={!hotHasSelected} onClick={this.hotDelectRow}>
                                删除<Icon type="minus" />
                            </Button>
                        </div>
                        <Spin spinning={this.state.loading}>
                            <Table columns={this.state.otherColumns}
                                dataSource={this.state.hotTableData}
                                rowSelection={hotRowSelection}
                                pagination={false} />
                        </Spin>
                    </div>
                    <div className="admin-content-warp" style={{ width: '50%', float: 'left' }}>
                        <div className="admin-content-header">
                            <span>明星显示列表</span>
                            <Button type='danger' disabled={!starHasSelected} onClick={this.starDelectRow}>
                                删除<Icon type="minus" />
                            </Button>
                        </div>
                        <Spin spinning={this.state.loading}>
                            <Table columns={this.state.otherColumns}
                                dataSource={this.state.starTableData}
                                rowSelection={starRowSelection}
                                pagination={false} />
                        </Spin>
                    </div>
                </div>
                <Button onClick={this.submit} type="primary" style={{ marginTop: '20px' }}>保存</Button>
            </div >
        );
    }
});

export default Star;