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 SecuritySet from './SecuritySet'
import {
    HocFactory
} from './HocFactory'

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

import '../../style/area.css'

@inject('hrmDecentralizationAdminSet')
@observer
export default class DecentralizationAdminSet 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.decentAdminSetting();
        }
    }

    componentDidMount() {
        this.init();
    }

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

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

        mobxDatasReset();
        getRight();
    }

    getDropMenuDatas = () => {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            menu
        } = hrmDecentralizationAdminSet, {
            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 == 'collection' || item.menuFun == 'help' || item.menuFun == 'pageAddress') {
                obj.disabled = true;
            }
            menus.push(obj);
        })

        return menus;
    }

    log = () => {
        window.setLogViewProps({
            logSmallType: '3022',
        });
    }

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

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

    handleMenuClick = (key) => {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            isPanelShow,
            setPanelStatus
        } = hrmDecentralizationAdminSet;

        isPanelShow && setPanelStatus(false);
        this[key] && this[key]();
    }

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

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


    handleClick = (item) => {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            isPanelShow,
            setPanelStatus
        } = hrmDecentralizationAdminSet;

        isPanelShow && setPanelStatus(false);
        this[item.menuFun] && this[item.menuFun]()
    }

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

        setEditorDialogVisible(true, 'new');
    }


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

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

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

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

    showConfirm(v) {
        let _this = this;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: (v == 'del') ? i18n.confirm.delete() : i18n.confirm.batchDeleteConfirm(),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                _this.onOk()
            },
            onCancel() {
                return false
            },
        });
    }

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

        deleteTableRows();
    }

    editorSave() {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            editor,
            addAdminInfo,
            editAdminInfo
        } = hrmDecentralizationAdminSet, {
            formType
        } = editor;

        formType == 'new' && addAdminInfo();
        formType == 'edit' && editAdminInfo()
    }

    getDropPanelButtons() {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            searchPanel,
            setPanelStatus
        } = hrmDecentralizationAdminSet, {
            form
        } = searchPanel;

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rivurx`} type="primary" onClick={() => this.handleSearch()}>{i18n.button.search()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0z4xpx`} onClick={() => form.reset()}>{i18n.button.reset()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zhl7bz`} onClick={() => setPanelStatus(false)}>{i18n.button.cancel()}</Button>),
        ];
        return btn;
    }

    getBaseValueOfSearch() {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            searchPanel
        } = hrmDecentralizationAdminSet, {
            form,
            value
        } = searchPanel;

        let val;
        if (form.isFormInit) {
            val = form.getFormParams().lastname;
        } else {
            val = value;
        }
        return val;
    }

    handleSearchChange(val) {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            searchPanel,
            updateFields,
            setBaseValueOfSearch
        } = hrmDecentralizationAdminSet, {
            form
        } = searchPanel

        if (form.isFormInit) {
            updateFields(val);
        }
        setBaseValueOfSearch(val);
    }

    handlePanelStatus(bool) {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            searchPanel,
            setPanelStatus,
            getSearchCondition
        } = hrmDecentralizationAdminSet, {
            condition
        } = searchPanel;

        if (bool) {
            setPanelStatus(true);
            condition.length == 0 && getSearchCondition(); //第一次打开面板时加载数据
        } else {
            setPanelStatus(false);
        }
    }

    handleSearch() {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            isPanelShow,
            setPanelStatus,
            getTableInfo
        } = hrmDecentralizationAdminSet;

        getTableInfo();
        isPanelShow && setPanelStatus(false);
    }

    getPanelComponents() {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            searchPanel
        } = hrmDecentralizationAdminSet, {
            condition,
            form,
            loading
        } = searchPanel, {
            isFormInit
        } = form;

        let arr = [];
        isFormInit && condition.map(c => {
            c.items.map((field, index) => {
                arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@gc2anu@${index}`} span={10} offset={(index%2 ==0)? 1 : 2}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ugv6lg@${index}`}
                                      label={`${field.label}`}
                                      labelCol={{span: `${field.labelcol}`}}
                                      wrapperCol={{span: `${field.fieldcol}`}}>
                                          {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@wzsevo@${index}`} fieldConfig={field} form={form} formParams={form.getFormParams()} />}
                                  </WeaFormItem>
                              </div>
                  	     </Col>)
            })
        })

        if (loading) {
            return (
                <div className='hrm-loading-center-small' style={{top:'30%'}}>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@87e1zj`} spinning={loading}></Spin>
                </div>
            )
        } else {
            return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@x4d2yh`} onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleSearch()}>{arr}</Row>
        }
    }

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

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

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

        switch (i) {
            case '0': //安全设置
                setSelectedRowsKeys(id);
                setSecuritySetDialogVisible(true);
                break;
            case '1': //编辑
                this.doEdit(id)
                break;
            case '2': //删除
                this.deleteRows(id)
                break;
            case '3':
                window.setLogViewProps({
                    logSmallType: '3022',
                    targetId: id
                });
                break;
        }
    }

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

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

    securitySetSave = () => {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            securitySave,
        } = hrmDecentralizationAdminSet;

        securitySave();
    }


    render() {
        const {
            hrmDecentralizationAdminSet
        } = this.props, {
            loading,
            title,
            isPanelShow,
            authorized,
            setPanelStatus,
            tableStore,
            searchPanel,
            editor,
            securitySet,
            setVerifyTypeSelectedValue,
            setUseTypeSelectedValue,
            setCheckboxValue,
            setEditorDialogVisible,
            setSecuritySetDialogVisible,
            setLoginId,
            date,

            isSecondaryVerifySetted,
            isSecondaryVerifyUsed,
            saveSecondaryPasswordSetting,

            hasValidateType,
            handleCondition,
        } = hrmDecentralizationAdminSet, {
            conditionCount
        } = searchPanel;

        if (!authorized) {
            return (
                <div style={{height: '100%'}}>
                    {loading ?  <div className='hrm-loading-center'>
                                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@0em0q1`} spinning={loading} size='large'></Spin>
                                </div>
                             :  <div className="hrm-wea-alert-page">
                                    <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@vexkk3`}>
                                        <div style={{ color: '#000' }}>
                                            {i18n.message.authFailed()}
                                        </div>
                                    </WeaAlertPage>
                                </div>
                    }   
                </div>
            )
        } else {
            return (
                <div>
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@qatkoc`} 
                        datas={this.getDropMenuDatas()} 
                        onClick={ key => this.handleMenuClick(key)}
                        collectParams={{favname:title,favouritetype:5}}
                    >
                            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@xsi8bf`} 
                                title={title}
                                icon={<i className='icon-coms-hrm'/>}
                                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@2be5kh`}
                                searchType={['base','advanced']}
                                showSearchAd={isPanelShow}
                                hasMask={false}
                                advanceHeight={Math.ceil(conditionCount / 2)*52+20}
                                buttonsAd={this.getDropPanelButtons()}
                                searchsBaseValue={this.getBaseValueOfSearch()}
                                setShowSearchAd={  b => this.handlePanelStatus(b)}
                                hideSearchAd={ () => setPanelStatus(false)}
                                searchsAd= {isPanelShow ? this.getPanelComponents():<div></div>}
                                onSearch={() => this.handleSearch()}
                                onSearchChange={val => this.handleSearchChange(val)}
                            />
                            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@tuyije`} 
                                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@65yq1e`} 
                        {...editor}
                        isFormInit={editor.form.isFormInit}
                        save={() => this.editorSave()}
                        loading={editor.loading}
                        onCancel={() => setEditorDialogVisible(false)}
                    />
                     <SecuritySet ecId={`${this && this.props && this.props.ecId || ''}_SecuritySet@ikqz0y`} 
                        {...securitySet} 
                        hrmId={this.props.params.hrmId}
                        isFormInit={securitySet.form.isFormInit}
                        save={() => this.securitySetSave()}
                        onCancel={() => setSecuritySetDialogVisible(false)}
                        setVerifyTypeSelectedValue={(key, val) => setVerifyTypeSelectedValue(key, val, 'change')}
                        setUseTypeSelectedValue={(val, key) => setUseTypeSelectedValue(val, key, 'change')}
                        setCheckboxValue={(val, key) => setCheckboxValue(val, key, 'change')}
                        setLoginId={id => setLoginId(id)}
                        isSecondaryVerifySetted={isSecondaryVerifySetted}
                        isSecondaryVerifyUsed={isSecondaryVerifyUsed}
                        hasValidateType={hasValidateType}
                        handleCondition={handleCondition}
                        saveSecondaryPasswordSetting={cb => saveSecondaryPasswordSetting(cb)}
                    />
                </div>
            )
        }

    }
}