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,
    isAdmin: /^\/admin\//.test(location.pathname)
}))
@Form.create()
export default class EditItem extends Component {
    constructor() {
        super(...arguments);
        this.state = {
            authoritiesCheckedValues: [],
        }
    }

    componentDidMount() {
        this.fetchItem(this.props.params.id);
        // if (this.props.isAdmin) {
        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 {form, params, dispatch, isAdmin} = this.props;
        const data = form.getFieldsValue();
        data.id = params.id;

        if (isAdmin) {
            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);
        dispatch({
            type: 'UPDATE_USER_ITEM',
            item: data
        });
    }

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

        let {authorities} = this.props;

        const breadcrumb = isAdmin ? ['用户管理', '用户详情'] : ['我的', '个人信息'];

        const title = isAdmin ? '用户详情' : '个人信息';

        const header = (
            <MainHeader breadcrumb={breadcrumb}
                        title={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.status === 5 ? '[已禁用]' : '');
                authority.value = authority.name;
                authority.disabled = authority.status !== 9;
                authoritiesMap[authority.name] = authority;
            });
            if (item.authorities) {
                const uas = item.authorities.split(',');
                uas.forEach(name=> {
                    userAuthorities.push(authoritiesMap[name]);
                });
            }
        }

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

                            <Form.Item label="用户名" {...smallFormItemLayout}>
                                { item.username }
                            </Form.Item>


                            <Form.Item label="状态" {...smallFormItemLayout}>
                                {
                                    isAdmin && 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}>
                                {  isAdmin && isEdit ?
                                    <div className="authorities-checkbox-group">
                                        <Checkbox.Group options={authorities}
                                                        value={this.state.authoritiesCheckedValues}
                                                        onChange={(checkedValues)=> {
                                                            this.setState({
                                                                authoritiesCheckedValues: checkedValues
                                                            })
                                                        }}/>
                                        <p style={{opacity: .5}}>注意: 只能分配角色列表中已经启用的角色!</p>
                                    </div>
                                    :
                                    (
                                        userAuthorities.length ?
                                            userAuthorities.map((userAuthorty)=>(
                                                userAuthorty &&
                                                <div style={userAuthorty.status === 5 ? {opacity: .7} : {}}
                                                     key={userAuthorty.name}>{userAuthorty.label}</div>
                                            ))
                                            :
                                            NULL
                                    )
                                }
                            </Form.Item>


                            <Form.Item label="昵称" {...smallFormItemLayout}>
                                {
                                    !isAdmin && isEdit ?
                                        <Input {...getFieldProps('nick', {initialValue: item.nick})} />
                                        :
                                    item.nick || NULL
                                }
                            </Form.Item>
                            <Form.Item label="E-mail" {...smallFormItemLayout}>
                                {
                                    !isAdmin && isEdit ?
                                        <Input {...getFieldProps('email', {initialValue: item.email})} />
                                        :
                                    item.email || NULL
                                }
                            </Form.Item>
                            <Form.Item label="手机号" {...smallFormItemLayout}>
                                {
                                    !isAdmin && 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>
        );
    }
}
