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 {
    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
}))
@Form.create()
export default class EditItem extends Component {
    constructor() {
        super(...arguments);
        this.state = {
            resourcesCategoryMap:{},
            checkedKeys: []
        }
    }


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

    componentWillReceiveProps(nextProps) {
        if (nextProps.item && nextProps.item.permissions && nextProps.resources) {
            this.analysisCheckedKeys(nextProps);
            console.log('analysisCheckedKeys');
        }
    };

    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();
        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
                }
            })
        }
        console.log(data);
        this.props.dispatch({
            type: 'UPDATE_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.mask] = pac;
                    });
                }

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

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

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


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

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

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

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

                            <Row>
                                <Col span="12">
                                    <Form.Item label="角色ID" {...smallFormItemLayout}>
                                        {
                                            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>

                                    <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_AUTHORITY'
                                            });
                                        }}>
                                                    <Icon type="edit"/>编辑
                                                </Button>

                                        }
                                        <Button onClick={e=>{
                                            e.preventDefault();
                                            isEdit ?
                                                this.props.dispatch({
                                                    type: 'CANCEL_UPDATE_AUTHORITY'
                                                }) :
                                                this.props.history.goBack();
                                        }}
                                                style={{marginLeft:'1em'}}>
                                            <Icon type="rollback"/>
                                            {isEdit ? '取消' : '返回'}
                                        </Button>
                                    </Form.Item>
                                </Col>
                                <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=>
                                                            <Tree.TreeNode className="resource-item"
                                                                           key={
                                                                                res.action.length===1 ?
                                                                                    ('a-'+res.controllerName+'-'+res.action[0].mask) :
                                                                                    ('r-' + res.id)
                                                                           }
                                                                           title={
                                                                                res.description + (
                                                                                    res.action.length===1 ? ' - '+res.action[0].title :''
                                                                                )
                                                                           }>
                                                                {
                                                                    res.action.length > 1 && res.action.map(action=>
                                                                        <Tree.TreeNode className="resource-action"
                                                                                       key={'a-' + res.controllerName + '-' + action.mask}
                                                                                       title={action.title}/>
                                                                    )
                                                                }
                                                            </Tree.TreeNode>
                                                        )
                                                    }
                                                </Tree.TreeNode>
                                            )
                                        }
                                    </Tree>

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




