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 = {
            isEdit: false,
            permissions: {},
            expandedKeys:[],
            autoExpandParent: true,
            checkedKeys:[]
        }
    }


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

    componentWillReceiveProps(nextProps) {
        const state = {isEdit: nextProps.isEdit};
        if (nextProps.item && nextProps.item.permissions && nextProps.resources) {
            state.permissions = nextProps.item.permissions;
            console.log('state.permissions', state.permissions);
        }
        this.setState(state);
    };

    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;
        data.permissions = JSON.stringify(this.state.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
        });
    }

    handleExpand(expandedKeys){
        console.log('onExpand', arguments);
        this.setState({
            expandedKeys,
            autoExpandParent: false
        });
    }

    handleCheck(checkedKeys){
        this.setState({
            checkedKeys
        });
    }





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

        const {isEdit} = this.state;

        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}
            />
        );


        //对权限资源分组
        const resourcesCategoryMap = {};
        //角色权限
        const {permissions} = this.state;

        const checkedKeys = [];


        resources.forEach(res=> {
            if (res.actionMask && res.status == 9) {
                const category = res.category || '其他';
                const map = resourcesCategoryMap[category] || [];

                //角色拥有权限
                const permisMask = permissions[res.controllerName];
                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;
                }
            }
        });

        console.log(permissions, '选中的:', checkedKeys);


        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}
                                          onClick={
                                               (cks)=>{
                                                    const cs = {};
                                                    cks.forEach(key=>{
                                                        const [ac, cn, mask] = key.split('-');
                                                        if(ac === 'a' && typeof mask !== 'undefined'){
                                                            let _mask = parseInt(mask, 10);
                                                            cs[cn] = (cs[cn] || 0) + _mask;

                                                        }
                                                    });
                                                    console.log(cs);
                                                    this.setState({
                                                        checkedKeys: cks,
                                                        permissions: cs,
                                                    })
                                                }
                                          }
                                    >
                                        {
                                            Object.keys(resourcesCategoryMap).map((key, index)=>
                                                <Tree.TreeNode className="resource-category" key={'c-'+key}
                                                               title={key}>
                                                    {
                                                        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>
        );
    }
}




