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 HeaderOperation, {DetailOperations} from '../../components/HeaderOperation/HeaderOperation';

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);
        this.state = {
            authoritiesCheckedValues: []
        }
    }

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

    componentWillReceiveProps(nextProps) {
        if ((nextProps.isEdit != this.props.isEdit) && nextProps.item && nextProps.item.authorities) {
            this.setState({
                authoritiesCheckedValues: nextProps.item.authorities.split(',')
            });
        }

    }

    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;
                }
            })
        }
        data.authorities = this.state.authoritiesCheckedValues.join();
        console.log(data);
        this.props.dispatch({
            type: 'UPDATE_USER_ITEM',
            item: data
        });
    }

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

        const header = (
            <MainHeader breadcrumb={['用户管理', '用户详情']}
                        title={'用户详情' + (isEdit ? ' - 编辑' : '')}
                        operation={<HeaderOperation history={history}
                                                    buttons={item && DetailOperations('USER', item.id, isEdit, dispatch)}/>}
            />
        );

        const authoritiesMap = {};
        const userAuthorities = [];
        if (item && authorities) {
            authorities.forEach(authority=> {
                authority.label = authority.description + '（' + authority.name + '）';
                authority.value = authority.name;
                authoritiesMap[authority.name] = authority.label;
            });
            if (item.authorities) {
                const uas = item.authorities.split(',');
                uas.forEach(name=> {
                    userAuthorities.push(authoritiesMap[name]);
                });
            }
        }

        return (
            <Layout header={header}>
                <Spin spinning={loading}>
                    {
                        item &&
                        <Form className="main-form" horizontal>

                            <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}>
                                {  isEdit ?
                                    <Checkbox.Group options={authorities}
                                                    value={this.state.authoritiesCheckedValues}
                                                    onChange={(checkedValues)=> {
                                                        this.setState({
                                                            authoritiesCheckedValues: checkedValues
                                                        })
                                                    }}/>
                                    :
                                    (userAuthorities.length ? userAuthorities.join('，') : NULL)
                                }
                            </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>

                        </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>
