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

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

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

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

import {
    WeaSwitch
} from 'comsMobx'
import {
    WeaTableNew
} from 'comsMobx'
import {
    i18n
} from '../../public/i18n';
import NewEngineGroup from './NewEngineGroup'
import GroupSetting from './GroupSetting'
import OrganizationTree from '../../coms/OrganizationTree';


const toJS = mobx.toJS;
const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;

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

@inject('hrmEngineGroup')

@observer
export default class EngineGroup 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.groupSet();
        }
    }

    componentDidMount() {
        this.init();
    }

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

    init() {
        const {
            hrmEngineGroup
        } = this.props;

        hrmEngineGroup.mobxDatasReset();
        hrmEngineGroup.setOperation('getRight');
        hrmEngineGroup.getRight();
        hrmEngineGroup.setOperation('getTableInfo');
        hrmEngineGroup.getTableInfo();
    }

    //WeaRightMenu 
    getDropMenuDatas() {
        const {
            hrmEngineGroup
        } = this.props, {
            rightMenu
        } = hrmEngineGroup;

        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;
    }
    handleMenuClick(key) {
        const {
            hrmEngineGroup
        } = this.props, {
            isMpPanelShow
        } = hrmEngineGroup;

        isMpPanelShow && hrmEngineGroup.setMpPanelStatus(false);
        this[key] && this[key]();
    }
    //WeaTop
    getTopMenuBtns() {
        const {
            hrmEngineGroup
        } = this.props, {
            topMenu,
            mpTableStore,
            type
        } = hrmEngineGroup;

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

        isMpPanelShow && hrmEngineGroup.setMpPanelStatus(false);
        this[item.menuFun] && this[item.menuFun]()
    }

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

    new() {
        const {
            hrmEngineGroup
        } = this.props;

        hrmEngineGroup.setNewDialogVisible(true);
    }
    batchDelete() {
        const {
            hrmEngineGroup
        } = this.props, {
            mpTableStore
        } = hrmEngineGroup;

        let keys = toJS(mpTableStore.selectedRowKeys).toString();
        hrmEngineGroup.setSelectedRowKey(keys);
        this.deleteRows();
    }

    custom = () => {
        const {
            hrmEngineGroup
        } = this.props, {
            mpTableStore,
        } = hrmEngineGroup;

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

    deleteRows(id) {
        const {
            hrmEngineGroup
        } = this.props;

        if (id) {
            hrmEngineGroup.deleteSet(id, 'delete');
        } else {
            hrmEngineGroup.setOperation('delete');
        }

        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 {
            hrmEngineGroup
        } = this.props;

        hrmEngineGroup.delete();
    }
    //WeaTab
    getTabBtn() {
        const {
            hrmEngineGroup
        } = this.props, {
            mpShForm
        } = hrmEngineGroup;

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@20x7l0`} type="primary" onClick={() => this.handleMpSearch()}>{i18n.button.search()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s769id`} onClick={() => mpShForm.reset()}>{i18n.button.reset()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@62en1b`} onClick={() => hrmEngineGroup.setMpPanelStatus(false)}>{i18n.button.cancel()}</Button>),
        ];
        return btn;
    }
    getMpShBaseValue() {
        const {
            hrmEngineGroup
        } = this.props, {
            mpShForm,
            groupName
        } = hrmEngineGroup;

        let val;
        if (mpShForm.isFormInit) {
            val = mpShForm.getFormParams().orgGroupName;
        } else {
            val = groupName;
        }
        return val;
    }
    handleMpShChange(val) {
        const {
            hrmEngineGroup
        } = this.props, {
            mpShForm
        } = hrmEngineGroup;
        if (mpShForm.isFormInit) {
            hrmEngineGroup.updateFields(val);
        }
        hrmEngineGroup.setSearchName(val);
    }
    handleMpPanelStatus(bool) {
        const {
            hrmEngineGroup
        } = this.props, {
            mpShCondition
        } = hrmEngineGroup;

        if (bool) { //打开面板
            hrmEngineGroup.setMpPanelStatus(true);
            if (mpShCondition.length == 0) { //第一次打开面板时加载高级搜索数据
                hrmEngineGroup.setOperation('mpSearch');
                hrmEngineGroup.getMpSearchCondition();
            }
        } else { //关闭面板
            hrmEngineGroup.setMpPanelStatus(false);
            hrmEngineGroup.mpSearchReset();
        }
    }
    handleMpSearch() {
        const {
            hrmEngineGroup
        } = this.props, {
            isMpPanelShow
        } = hrmEngineGroup;

        hrmEngineGroup.setOperation('getTableInfo');
        hrmEngineGroup.getTableInfo(); //获取表格信息
        isMpPanelShow && hrmEngineGroup.setMpPanelStatus(false); //关闭面板
    }
    getPanelComponents() {
        const {
            hrmEngineGroup
        } = this.props, {
            mpShCondition,
            mpShForm,
            mpShLoading
        } = hrmEngineGroup;

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

        if (mpShLoading) {
            return (
                <div className='hrm-loading-center-small' style={{top:'25%'}}>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@fe0972`} spinning={mpShLoading}></Spin>
                </div>
            )
        } else {
            return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@dq3lxz`} onKeyDown={(e) =>( e.keyCode == 13 && e.target.tagName === "INPUT")  && this.handleMpSearch()}>{arr}</Row>
        }
    }
    //WeaTable
    reRenderColumns(columns) {
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'orgGroupName') {
                c.render = function(text, record) {
                    return <a onClick={() => _this.doEdit(record.randomFieldId)} >{record.orgGroupName}</a>
                }
            };
        })
    }
    onOperatesClick(record, index, operate) {
        let i = operate.index;
        const {
            randomFieldId
        } = record;

        i == '0' && this.doEdit(randomFieldId);
        i == '1' && this.doOpenMem(randomFieldId);
        i == '2' && this.doDel(randomFieldId);
        i == '3' && window.setLogViewProps({
            logSmallType: '3052',
            targetId: randomFieldId
        });
    }
    doEdit(id) {
        const {
            hrmEngineGroup
        } = this.props;

        hrmEngineGroup.setGroupId(id);
        hrmEngineGroup.setSelectedKey('0');
        hrmEngineGroup.setSettingDialogVisible(true);
    }
    doDel(id) {
        const {
            hrmEngineGroup
        } = this.props;

        this.deleteRows(id);
    }
    doOpenMem(id) {
        const {
            hrmEngineGroup
        } = this.props;

        hrmEngineGroup.setGroupId(id);
        hrmEngineGroup.setSelectedKey('1');
        hrmEngineGroup.setSettingDialogVisible(true);
    }

    render() {
        const {
            hrmEngineGroup
        } = this.props, {
            wtpLoading,
            isEdit,
            date,
            authorized,
			detachable,
			orgTreeProps
        } = hrmEngineGroup, {
            mpTitle
        } = hrmEngineGroup, {
            isMpPanelShow,
            conditionNum
        } = hrmEngineGroup, {
            mpTableStore
        } = hrmEngineGroup, {
            newDialogVisible
        } = hrmEngineGroup, {
            settingDialogVisible
        } = hrmEngineGroup;

        if (!authorized) {
            return (
                <div style={{height: '100%'}}>
                    {wtpLoading ?   <div className='hrm-loading-center'>
                                        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@spo4w9`} spinning={wtpLoading} size='large'></Spin>
                                    </div>
                                :   <div className="hrm-wea-alert-page">
                                        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@pdihq8`}>
                                            <div style={{ color: '#000' }}>
                                                {i18n.message.authFailed()}
                                            </div>
                                        </WeaAlertPage>
                                    </div>
                    }   
                </div>
            )
        } else {
            const coms = [
				<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@nfufna`}
                    searchType={['base','advanced']}
                    showSearchAd={isMpPanelShow}
                    hasMask={false}
                    advanceHeight={Math.ceil(conditionNum/2)*52+20}
                    buttonsAd={this.getTabBtn()}
                    searchsBaseValue={this.getMpShBaseValue()}
                    setShowSearchAd={  b => this.handleMpPanelStatus(b)}
                    hideSearchAd={ ()=>hrmEngineGroup.setMpPanelStatus(false)}
                    searchsAd= {isMpPanelShow?this.getPanelComponents():<div></div>}
                    onSearch={()=>this.handleMpSearch()}
                    onSearchChange={val=>this.handleMpShChange(val)}
                />,
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@nx1vro`} 
                    comsWeaTableStore={mpTableStore}
                    hasOrder={true}
                    needScroll={true}
                    getColumns={c => this.reRenderColumns(c)}
                    onOperatesClick={(record, index, operate) => this.onOperatesClick(record, index, operate)}
                />
			];
			let children;
			if(detachable){
				children = (
					<WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@aptotk`} leftCom={<OrganizationTree ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTree@m5n619`} {...orgTreeProps} ref='orgTree'/>}>
						{coms}
					</WeaLeftRightLayout>
				)
			}else{
				children = coms;
            }
            
            return (
                <div>
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@p212ee`} 
                        datas={this.getDropMenuDatas()} 
                        onClick={ key=>this.handleMenuClick(key)}
                        collectParams={{favname:mpTitle,favouritetype:5}}
                    >
                            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@pjuba2`} 
                                title={i18n.module.groupSet()}
                                icon={<i className='icon-coms-hrm'/>}
                                iconBgcolor='#217346'
                                loading={true}
                                buttons={this.getTopMenuBtns()}
                                showDropIcon={true}
                                dropMenuDatas={this.getDropMenuDatas()}
                                onDropMenuClick={(e) => this.handleMenuClick(e)}
                            >
                            {children}
                        </WeaTop>
                    </WeaRightMenu>
                    {newDialogVisible && <NewEngineGroup ecId={`${this && this.props && this.props.ecId || ''}_NewEngineGroup@u0n4kj`} />}
                    {settingDialogVisible && <GroupSetting ecId={`${this && this.props && this.props.ecId || ''}_GroupSetting@bqi7mn`} />}
                </div>
            )
        }

    }
}