import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {
    Row,
    Col,
    Form,
    Input,
    Button,
    Checkbox,
    Select,
    message,
    Tabs,
    Cascader,
    Radio,
    Upload,
    Icon,
    Modal,
    DatePicker,
    Table,
    Spin
} from 'antd';

import Layout from '../../components/Layout/Layout';
import MainHeader from '../../components/MainHeader/MainHeader';

import {
    formItemLayout,
    smallFormItemLayout,
    footerFormSubmitLayout,
    userStatusToString,
    formatDateTime,
    NULL,
    USER_STATUS
} from '../../utils';

@connect(state=>({
    loading: state.user.loading || state.authority.loading,
    item: state.user.item,
    isEdit: state.user.isEdit,
    authorities: state.authority.items,
}))
@Form.create()
export default class EditItem extends Component {
    constructor() {
        super(...arguments);
    }

    componentDidMount() {
        this.fetchItem(this.props.params.id);
        this.fetchAuthorityList();
    };

    // componentWillReceiveProps(nextProps) {
    //     if (nextProps.item && nextProps.authorities) {
    //         this.analysisCheckedKeys(nextProps);
    //     }
    // };
    //
    // analysisCheckedKeys(props) {
    //     const {item, authorities, isEdit} = props;
    //     //对权限资源分组
    //     const authoritiesMap = {};
    //     const checkedKeys = [];
    //     authorities && authorities.forEach(authority=> {
    //         authoritiesMap[authority.name] = authority;
    //
    //     });
    //
    //     this.setState({
    //         authoritiesMap,
    //         checkedKeys
    //     });
    // }

    fetchItem(id) {
        this.props.dispatch({
            type: 'FETCH_USER_ITEM',
            id
        });
    };

    fetchAuthorityList() {
        this.props.dispatch({
            type: 'FETCH_AUTHORITY_LIST',
            query: {s: 100}
        });
    };

    handleSubmit(e) {
        e.preventDefault();
        const data = this.props.form.getFieldsValue();
        data.id = this.props.params.id;
        if (isNaN(data.status)) {
            Object.keys(USER_STATUS).forEach(key=> {
                if (USER_STATUS[key] === data.status) {
                    data.status = key;
                    return false;
                }
            })
        }
        console.log(data);
        this.props.dispatch({
            type: 'UPDATE_USER_ITEM',
            data
        });
    }

    render() {
        const {item, loading, form:{getFieldProps}, location:{query}, isEdit, authorities} = this.props;

        const operation = (
            <div style={{textAlign:'right'}}>
                <Button.Group>
                    <Button type="ghost"
                            onClick={
                            e=>{
                                e.preventDefault();
                                this.props.dispatch({
                                    type: isEdit ? 'CANCEL_UPDATE_USER' : 'UPDATE_USER'
                                });
                            }
                    }>
                        <Icon type="edit"/>
                    </Button>
                    <Button type="ghost" onClick={e=>{
                        e.preventDefault();
                        isEdit ?
                            this.props.dispatch({
                                type: 'CANCEL_UPDATE_USER'
                            }) :
                            this.props.history.goBack();
                    }}>
                        <Icon type="rollback"/>
                    </Button>
                </Button.Group>
            </div>
        );

        const header = (
            <MainHeader breadcrumb={['用户管理', '用户详情']}
                        title={'用户详情' + (isEdit ? ' - 编辑' : '')}
                        operation={operation}
            />
        );

        const authoritiesMap = authorities ? authorities.reduce((map, authority)=> {
            map[authority.name] = authority;
            return map;
        }, {}) : {};

        if (item) {
            item.authorities = item.authorities.split(',');

            item.authoritiesDescList = [];

            // item.authoritiesMap = item.authorities.reduce((map, name)=> {
            //     const authority = authoritiesMap[name];
            //     map[name] = authority;
            //     item.authoritiesDescList.push(authority.description);
            // }, {});
        }

        return (
            <Layout header={header}>
                <Spin spinning={loading}>
                    {
                        item &&
                        <Form className="main-form" horizontal>
                            <Row>
                                <Col span="12">
                                    <Form.Item label="用户名" {...smallFormItemLayout}>
                                        { item.username }
                                    </Form.Item>
                                    <Form.Item label="状态" {...smallFormItemLayout}>
                                        {
                                            isEdit ?
                                                <Select
                                                    placeholder="请选择状态" {...getFieldProps('status', {initialValue: userStatusToString(item.status)})} >
                                                    <Select.Option value="0">未激活</Select.Option>
                                                    <Select.Option value="1">已激活</Select.Option>
                                                </Select>
                                                :
                                                (typeof item.status !== 'undefined' ? userStatusToString(item.status) : NULL)
                                        }
                                    </Form.Item>
                                    <Form.Item label="角色" {...smallFormItemLayout}>
                                        {item.authoritiesDescList.join()}
                                    </Form.Item>
                                    <Form.Item label="昵称" {...smallFormItemLayout}>
                                        {
                                            isEdit ?
                                                <Input {...getFieldProps('nick', {initialValue: item.nick})} />
                                                :
                                            item.nick || NULL
                                        }
                                    </Form.Item>
                                    <Form.Item label="E-mail" {...smallFormItemLayout}>
                                        {
                                            isEdit ?
                                                <Input {...getFieldProps('email', {initialValue: item.email})} />
                                                :
                                            item.email || NULL
                                        }
                                    </Form.Item>
                                    <Form.Item label="手机号" {...smallFormItemLayout}>
                                        {
                                            isEdit ?
                                                <Input {...getFieldProps('mobile', {initialValue: item.mobile})} />
                                                :
                                            item.mobile || NULL
                                        }
                                    </Form.Item>
                                    <Form.Item label="注册时间" {...smallFormItemLayout}>
                                        {item.dateCreated && formatDateTime(item.dateCreated)}
                                    </Form.Item>
                                    <Form.Item {...footerFormSubmitLayout} style={{marginTop:30}}>
                                        {
                                            isEdit ?
                                                <Button type="primary" onClick={this.handleSubmit.bind(this)}
                                                        loading={loading}>
                                                    <Icon type="save"/>保存
                                                </Button>
                                                :
                                                <Button type="primary" onClick={e=>{
                                            e.preventDefault();
                                            this.props.dispatch({
                                                type:'UPDATE_USER'
                                            });
                                        }}>
                                                    <Icon type="edit"/>编辑
                                                </Button>

                                        }
                                        <Button onClick={e=>{
                                            e.preventDefault();
                                            isEdit ?
                                                this.props.dispatch({
                                                    type: 'CANCEL_UPDATE_USER'
                                                }) :
                                                this.props.history.goBack();
                                        }}
                                                style={{marginLeft:'1em'}}>
                                            <Icon type="rollback"/>
                                            {isEdit ? '取消' : '返回'}
                                        </Button>
                                    </Form.Item>
                                </Col>
                                <Col span="12">

                                </Col>
                            </Row>
                        </Form>
                    }
                </Spin>
            </Layout>
        );
    }
}

// <Button type="ghost" onClick={e=>{e.preventDefault(); this.setState({isEdit: !this.state.isEdit})}}>
//     <Icon type="edit"/>
// </Button>

// <Form.Item {...footerFormSubmitLayout} style={{marginTop:30}}>
//     {
//         isEdit ?
//             <Button type="primary" onClick={this.handleSubmit.bind(this, -1)}
//                     loading={loading}>
//                 <Icon type="save"/>修改
//             </Button>
//             :
//             item.status ?
//                 <Button type="primary" onClick={this.handleSubmit.bind(this, 0)}
//                         loading={loading}>
//                     <Icon type="save"/>禁用
//                 </Button>
//                 :
//                 <Button type="primary" onClick={this.handleSubmit.bind(this, 1)}
//                         loading={loading}>
//                     <Icon type="save"/>激活
//                 </Button>
//     }
//     <Button onClick={e=>{e.preventDefault(); this.props.history.goBack();}}
//             style={{marginLeft:'1em'}}>
//         <Icon type="rollback"/>返回
//     </Button>
// </Form.Item>
