import React from 'react';
import { Table, Button, Input, Spin, Message, Select, Modal, Tag, Icon } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';

const Role = React.createClass({
    getInitialState() {
        return {
            visible: false,
            disabled: false,
            name: '',
            selectOption: [],
            data: [],
            selectedRowKeys: [],
            selectedRows: [],
            loading: false,
            permissions: {

            },
            modelRecord: {
                id: '',
                name: '',
                permissions: []
            }
        }
    },

    componentWillMount() {
        this.loadData();
    },

    loadData() {
        let _me = this;
        this.setState({
            loading: true
        });
        $.when($.ajax({
            url: globalConfig.context + '/api/roles',
            method: 'get',
            cache: false
        }), $.ajax({
            url: globalConfig.context + '/api/permissions',
            method: 'get',
            cache: false
        })).done((roles, permissions) => {
            if (!roles[0].error.length && roles[0].data) {
                this.state.data = [];
                for (let i = 0; i < roles[0].data.length; i++) {
                    let thisdata = roles[0].data[i];
                    this.state.data.push({
                        key: i,
                        id: thisdata.id,
                        roleName: thisdata.roleName,
                        permissions: thisdata.permissions.map((p) => { return String(p.id) }) || []
                    });
                };
            }
            if (!permissions[0].error.length && permissions[0].data) {
                _me.state.selectOption = [];
                permissions[0].data.map(function (item) {
                    _me.state.selectOption.push(
                        <Select.Option key={item.id}>{item.name}</Select.Option>
                    )
                    _me.state.permissions[String(item.id)] = item.name;
                });
            }
        }).always(() => {
            this.setState({
                loading: false
            });
        });
    },

    save() {
        this.setState({
            loading: true
        });
        $.ajax({
            url: globalConfig.context + '/api/role',
            method: 'post',
            data: { data: JSON.stringify(this.state.modelRecord) },
        }).done((res) => {
            if (!res.error.length) {
                Message.success("保存成功");
                this.loadData();
            } else {
                Message.error(res.error[0].message);
            }
        }).always(() => {
            this.setState({
                loading: false,
                visible: false,
                disabled: false
            });
        })
    },

    remove() {
        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({
            loading: deletedIds.length > 0
        });
        if (deletedIds.length) {
            $.ajax({
                url: globalConfig.context + '/api/role/delete',
                method: 'post',
                data: {
                    data: JSON.stringify(deletedIds)
                }
            }).done((res) => {
                if (!res.error.length) {
                    Message.success("删除成功");
                    this.state.selectedRowKeys.sort((a, b) => { return b - a });
                    for (let idx = 0; idx < this.state.selectedRowKeys.length; idx++) {
                        let dataIndex = this.state.selectedRowKeys[idx];
                        this.state.data.splice(dataIndex, 1);
                    };
                    this.setState({
                        data: this.state.data,
                        selectedRowKeys: []
                    });
                } else {
                    Message.error(res.error[0].message);
                }
            }).always(() => {
                this.setState({
                    loading: false
                });
            })
        }
    },

    addNew() {
        this.setState({
            visible: true,
            modelRecord: {
                id: null,
                roleName: '',
                permissions: []
            }
        })
    },

    edit(e) {
        this.setState({
            modelRecord: {
                id: e.id,
                roleName: e.roleName,
                permissions: e.permissions
            },
            visible: true,
            disabled: false
        })
    },

    handleCancel() {
        this.setState({
            visible: false,
            disabled: false
        })
    },

    render() {
        const columns = [{
            title: '名字',
            dataIndex: 'roleName',
            key: 'roleName'
        }, {
            title: '绑定权限',
            dataIndex: 'permissions',
            key: 'permissions',
            render: (text, record, index) => {
                let _me = this;
                if (record.permissions) {
                    return <div>
                        {record.permissions.map((tag) => {
                            return <Tag key={tag} closable={false}>
                                {_me.state.permissions[tag]}
                            </Tag>
                        }
                        )}
                    </div>
                } else {
                    return <div></div>;
                }
            },
        }];
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <Spin spinning={this.state.loading}>
                <Modal title="用户编辑"
                    closable={false}
                    visible={this.state.visible}
                    onOk={this.save}
                    onCancel={this.handleCancel}>
                    <ul className="modal-content">
                        <li>
                            <span className='modal-text'>名字</span>
                            <Input value={this.state.modelRecord.roleName} onChange={(e) => {
                                this.state.modelRecord.roleName = e.target.value;
                                this.setState({
                                    modelRecord: this.state.modelRecord
                                })
                            }} />
                        </li>
                        <li>
                            <span className='modal-text'>权限</span>
                            <Select
                                multiple
                                style={{ width: '76%' }}
                                placeholder="选择绑定权限"
                                disabled={!this.state.modelRecord.id}
                                value={this.state.modelRecord.permissions}
                                onChange={(pids) => {
                                    this.state.modelRecord.permissions = pids;
                                    this.setState({
                                        modelRecord: this.state.modelRecord
                                    })
                                }}
                            >
                                {this.state.selectOption}
                            </Select>
                        </li>
                    </ul>
                </Modal>
                <div className="set-content">
                    <div className="set-title">
                        <span>角色控制</span>
                        <Button style={{ background: "#ea0862", border: "none", color: "#fff" }}
                            onClick={this.addNew}>添加<Icon type="plus" /></Button>
                        <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
                            disabled={!hasSelected}
                            onClick={this.remove}>删除<Icon type="minus" /></Button>
                    </div>
                    <Table className='member-table'
                        columns={columns}
                        dataSource={this.state.data}
                        onRowClick={this.edit}
                        pagination={false}
                        rowSelection={rowSelection} />
                </div>
            </Spin>
        );
    }
});

export default Role;