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,
    Tree
} from 'antd';

import Layout from '../../components/Layout/Layout';
import MainHeader from '../../components/MainHeader/MainHeader';
import HeaderOperation, {DetailOperations} from '../../components/HeaderOperation/HeaderOperation';
import FooterOperation from  '../../components/FooterOperation/FooterOperation';

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

import './EditItem.less';


@connect(state=>({
    loading: state.authority.loading || state.resource.loading,
    item: state.authority.item,
    isEdit: state.authority.isEdit,
    resources: state.resource.items,
    resourcesTotal: state.resource.total,
    removed: state.authority.removed
}))
@Form.create()
export default class EditItem extends Component {
    constructor() {
        super(...arguments);
        this.state = {
            resourcesCategoryMap: {},
            checkedKeys: []
        }
    }

    componentDidMount() {
        const {params:{id}} = this.props;
        if (id) {
            this.fetchItem(id);
            if (id !== 'ROLE_ADMIN') {
                this.fetchResourceList();
            }
        }
    };

    componentWillReceiveProps(nextProps) {
        const {params:{id}, history} = this.props;
        const {item, resources} = nextProps;
        if (!id && item && item.id) {
            history.replace('/admin/authorities/' + item.id);
            return;
        }
        if (item && item.permissions && resources) {
            this.analysisCheckedKeys(nextProps);
        }
    };

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

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

    handleSubmit(e) {
        e.preventDefault();
        let data = {};
        data = this.props.form.getFieldsValue();
        if (this.props.params.id) {
            data.id = this.props.params.id;
        }

        const permissions = {};
        this.state.checkedKeys.forEach(key=> {
            const [ka, cn, mask] = key.split('-');
            if (ka === 'a' && mask) {
                permissions[cn] = ( permissions[cn] || 0) + parseInt(mask, 10);
            }
        });
        data.permissions = JSON.stringify(permissions);
        if (isNaN(data.status)) {
            ENABLE_STATUS_LIST.forEach(item=> {
                if (item.text === data.status) {
                    data.status = item.value;
                    return false;
                }
            })
        }
        if(data.name){
            if(!/^ROLE_/g.test(data.name)){
                data.name = 'ROLE_' + data.name;
            }
            data.name = (data.name+'').toUpperCase();
        }
        console.log(data);
        this.props.dispatch({
            type: data.id ? 'UPDATE_AUTHORITY_ITEM' : 'CREATE_AUTHORITY_ITEM',
            item: data
        });
    }

    analysisCheckedKeys(props) {
        const {item:{permissions}, resources, isEdit} = props;
        //对权限资源分组
        const resourcesCategoryMap = {};
        const checkedKeys = [];
        resources && resources.forEach(res=> {
            if (res.actionMask && res.status == 9) {
                const category = res.category || '其他';
                const map = resourcesCategoryMap[category] || [];

                //角色拥有权限
                const permisMask = permissions && permissions[res.controllerName] || 0;
                const permisAction = permisMask && resourceActions(permisMask) || [];
                const permisActionMap = {};

                if (permisAction.length) {
                    permisAction.forEach(pac=> {
                        permisActionMap[pac.value] = pac;
                    });
                }

                if (isEdit) {
                    res.action = resourceActions(res.actionMask);
                    res.action.forEach(ac=> {
                        if (permisActionMap[ac.value]) {
                            ac.checked = true;
                            checkedKeys.push(['a', res.controllerName, ac.value].join('-'));
                        }
                    });
                } else {
                    res.action = permisAction;
                }

                if (isEdit || permisAction.length) {
                    map.push(res);
                    resourcesCategoryMap[category] = map;
                }
            }
        });

        this.setState({
            resourcesCategoryMap,
            checkedKeys
        });
    }


    render() {
        let {params, item, resources, loading, form:{getFieldProps}, location:{query}, dispatch, isEdit} = this.props;


        const isCreate = !params.id;

        if (!params.id) {
            item = {
                status: 1
            };
            isEdit = true;
        }


        const operation = (
            <HeaderOperation history={this.props.history}
                             buttons={DetailOperations('AUTHORITY', params.id, isEdit, dispatch)}/>
        );

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

        return (
            <Layout header={header}>
                <Spin spinning={loading}>
                    {
                        item &&
                        <Form className="main-form" horizontal onSubmit={this.handleSubmit.bind(this)}>
                            <Row style={{marginLeft: 20}}>
                                <Col span="12">
                                    <Form.Item label="角色ID" {...smallFormItemLayout}>
                                        {
                                            isCreate ?
                                                <Input {...getFieldProps('name', {initialValue: item.name})} />
                                                :
                                            item.name || NULL
                                        }
                                    </Form.Item>
                                    <Form.Item label="名称" {...smallFormItemLayout}>
                                        {
                                            isEdit ?
                                                <Input {...getFieldProps('description', {initialValue: item.description})} />
                                                :
                                            item.description || NULL
                                        }
                                    </Form.Item>
                                    <Form.Item label="状态" {...smallFormItemLayout}>
                                        {
                                            isEdit ?
                                                <Select
                                                    placeholder="请选择状态" {...getFieldProps('status', {initialValue: enableStatusToString(item.status)})} >
                                                    <Select.Option value="1">系统</Select.Option>
                                                    <Select.Option value="5">禁用</Select.Option>
                                                    <Select.Option value="9">启用</Select.Option>
                                                </Select>
                                                :
                                                (typeof item.status !== 'undefined' ? enableStatusToString(item.status) : NULL)
                                        }
                                    </Form.Item>
                                    {
                                        !isCreate &&
                                        <Form.Item label="创建时间" {...smallFormItemLayout}>
                                            {
                                                item.dateCreated ?
                                                    formatDateTime(item.dateCreated)
                                                    :
                                                    NULL
                                            }
                                        </Form.Item>
                                    }


                                    <FooterOperation {...this.props} isEdit={isEdit} command="AUTHORITY"
                                                     hasCancel={!isCreate}/>

                                </Col>
                                {
                                    params.id !== 'ROLE_ADMIN' &&
                                    <Col span="12">
                                        <Tree checkable={isEdit}
                                              defaultExpandAll={true}
                                              checkedKeys={this.state.checkedKeys}
                                              onCheck={(checkedKeys)=> {
                                                  this.setState({checkedKeys});
                                              }}>
                                            {
                                                Object.keys(this.state.resourcesCategoryMap).map((key, index)=>
                                                    <Tree.TreeNode className="resource-category" key={'c-' + key}
                                                                   title={key}>
                                                        {
                                                            this.state.resourcesCategoryMap[key].map(res=>
                                                                res.action &&
                                                                <Tree.TreeNode className="resource-item"
                                                                               key={
                                                                                   res.action.length === 1 ?
                                                                                       ('a-' + res.controllerName + '-' + res.action[0].value) :
                                                                                       ('r-' + res.id)
                                                                               }
                                                                               title={
                                                                                   res.description + (
                                                                                       res.action.length === 1 ? ' - ' + res.action[0].label : ''
                                                                                   )
                                                                               }>
                                                                    {
                                                                        res.action.length > 1 && res.action.map(action=>
                                                                            <Tree.TreeNode className="resource-action"
                                                                                           key={'a-' + res.controllerName + '-' + action.value}
                                                                                           title={action.label}/>
                                                                        )
                                                                    }
                                                                </Tree.TreeNode>
                                                            )
                                                        }
                                                    </Tree.TreeNode>
                                                )
                                            }
                                        </Tree>

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




