import React from 'react'
import * as mobx from 'mobx'

import {
    inject,
    observer,
} from 'mobx-react'

import {
    WeaTop,
    WeaTab,
    WeaFormItem,
    WeaRightMenu,
    WeaAlertPage,
} from 'ecCom'

import {
    Row,
    Col,
    Spin,
    Modal,
    Button,
    message,
} from 'antd'

import {
    WeaSwitch,
    WeaTableNew,
} from 'comsMobx'

import {
    i18n
} from '../../public/i18n';

import Editor from '../../coms/Editor'
import {
    HocFactory
} from './HocFactory'

const WrappedEditor = HocFactory(Editor);
const toJS = mobx.toJS;
const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;


@inject('hrmUnitSet')
@observer
export default class UnitSet extends React.Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
        let bool = window.location.href.indexOf('/spa/hrm/engine.html') > -1;
        if (bool) {
            document.title = i18n.module.unitSetting();
        }
    }

    componentDidMount() {
        this.init();
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.location.key !== nextProps.location.key) {
            this.init();
        }
    }

    init() {
        const {
            hrmUnitSet
        } = this.props, {
            getRight,
            mobxDatasReset
        } = hrmUnitSet;

        mobxDatasReset();
        getRight();
    }

    getDropMenuDatas = () => {
        const {
            hrmUnitSet
        } = this.props, {
            menu
        } = hrmUnitSet, {
            rightMenu
        } = menu;

        let menus = [];
        toJS(rightMenu).map((item, index) => {
            let obj = {
                key: item.menuFun,
                icon: <i className={`${item.menuIcon}`}/>,
                content: item.menuName,
            }
            if (item.menuFun == 'log' || item.menuFun == 'collection' || item.menuFun == 'help' || item.menuFun == 'pageAddress') {
                obj.disabled = true;
            }
            menus.push(obj);
        })

        return menus;
    }

    handleMenuClick = (key) => {
        this[key] && this[key]();
    }

    getTopMenuBtns = () => {
        const {
            hrmUnitSet
        } = this.props, {
            menu,
            tableStore
        } = hrmUnitSet, {
            topMenu
        } = menu;

        let btns = [];
        toJS(topMenu).map((item, index) => {
            if (item.menuFun !== 'batchDelete') {
                btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@paujhi@${index}`} type='primary' onClick={() => this.handleClick(item)}>{item.menuName}</Button>);
            } else {
                btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gquaov@${index}`} type='primary' onClick={() => this.handleClick(item)} disabled={tableStore.selectedRowKeys.length > 0 ? false : true} >{item.menuName}</Button>);
            }
        });
        return btns;
    }

    handleClick = (item) => {
        this[item.menuFun] && this[item.menuFun]()
    }


    new() {
        const {
            hrmUnitSet
        } = this.props, {
            setEditorDialogVisible
        } = hrmUnitSet

        setEditorDialogVisible(true, 'new');
    }

    batchDelete() {
        const {
            hrmUnitSet
        } = this.props, {
            tableStore,
            setSelectedRowsKeys
        } = hrmUnitSet;

        let keys = toJS(tableStore.selectedRowKeys).toString();
        setSelectedRowsKeys(keys);
        this.deleteRows();
    }

    custom = () => {
        const {
            hrmUnitSet
        } = this.props, {
            tableStore,
        } = hrmUnitSet;

        tableStore.setColSetVisible(true);
        tableStore.tableColSet(true);
    }

    deleteRows(id) {
        const {
            hrmUnitSet
        } = this.props, {
            setSelectedRowsKeys
        } = hrmUnitSet;

        id && setSelectedRowsKeys(id);

        let v = id ? 'del' : 'batchDel';
        this.showConfirm(v);
    }

    showConfirm(v) {
        let _this = this;
        confirm({
            title: '信息确认',
            content: (v == 'del') ? i18n.confirm.delete() : i18n.confirm.batchDeleteConfirm(),
            okText: '确认',
            cancelText: '取消',
            onOk() {
                _this.onOk()
            },
            onCancel() {
                return false
            },
        });
    }

    onOk() {
        const {
            hrmUnitSet
        } = this.props, {
            deleteTableRows
        } = hrmUnitSet;

        deleteTableRows();
    }

    editorSave() {
        const {
            hrmUnitSet
        } = this.props, {
            editorDialog,
            addEditorInfo,
            editEditorInfo
        } = hrmUnitSet, {
            formType
        } = editorDialog;

        formType == 'new' && addEditorInfo();
        formType == 'edit' && editEditorInfo()
    }

    reRenderColumns(columns) {
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'unitname') {
                c.render = function(text, record) {
                    return <a onClick={() => _this.doEdit(record.randomFieldId)} >{record.unitname}</a>
                }
            };
        })
    }

    onOperatesClick(record, index, operate) {
        const {
            hrmUnitSet
        } = this.props, {
            setEditorDialogVisible,
            setSelectedRowsKeys
        } = hrmUnitSet;

        let i = operate.index,
            id = record.randomFieldId;

        switch (i) {
            case '0': //编辑
                this.doEdit(id)
                break;
            case '1': //删除
                this.deleteRows(id)
                break;
            case '2': //日志
                message.info('暂未实现！');
                break;
        }
    }

    doEdit = (id) => {
        const {
            hrmUnitSet
        } = this.props, {
            setSelectedRowsKeys,
            setEditorDialogVisible,
        } = hrmUnitSet;

        setSelectedRowsKeys(id);
        setEditorDialogVisible(true, 'edit');
    }

    render() {
        const {
            hrmUnitSet
        } = this.props, {
            loading,
            title,
            authorized,
            tableStore,
            editorDialog,
            setEditorDialogVisible,
            getTableInfo,
            onSearchChange,
            date,
        } = hrmUnitSet, {
            visible,
            form
        } = editorDialog

        if (!authorized) {
            return (
                <div style={{height: '100%'}}>
                    {loading ?  <div className='hrm-loading-center'>
                                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@vvpvvs`} spinning={loading} size='large'></Spin>
                                </div>
                             :  <div className="hrm-wea-alert-page">
                                    <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@5k6nye`}>
                                        <div style={{ color: '#000' }}>
                                            {i18n.message.authFailed()}
                                        </div>
                                    </WeaAlertPage>
                                </div>
                    }   
                </div>
            )
        } else {
            return (
                <div>
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@g8mn40`} 
                        datas={this.getDropMenuDatas()} 
                        onClick={ key => this.handleMenuClick(key)}
                        collectParams={{favname: title,favouritetype:5}}
                    >
                            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@nm1kbm`} 
                                title={title}
                                icon={<i className='icon-coms-currency'/>}
                                iconBgcolor='#217346'
                                loading={true}
                                buttons={this.getTopMenuBtns()}
                                showDropIcon={true}
                                dropMenuDatas={this.getDropMenuDatas()}
                                onDropMenuClick={(e) => this.handleMenuClick(e)}
                            >
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@rnpg2d`}
                                searchType={['base']}
                                onSearch={() => getTableInfo()}
                                onSearchChange={val => onSearchChange(val)}
                            />
                            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@iwhyhe`} 
                                comsWeaTableStore={tableStore}
                                hasOrder={true}
                                needScroll={true}
                                getColumns={c => this.reRenderColumns(c)}
                                onOperatesClick={(record, index, operate) => this.onOperatesClick(record, index, operate)}
                            />
                        </WeaTop>
                    </WeaRightMenu> 
                    <WrappedEditor ecId={`${this && this.props && this.props.ecId || ''}_WrappedEditor@t5aw3t`} 
                        {...editorDialog}
                        isFormInit={form.isFormInit}
                        save={() => this.editorSave()}
                        onCancel={() => setEditorDialogVisible(false)}
                    />
                </div>
            )
        }

    }
}