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

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

import {
    WeaTop,
    WeaTab,
    WeaFormItem,
    WeaRightMenu,
    WeaSearchGroup,
} 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;

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

@inject('hrmWorkNatureSet')
@observer
export default class WorkNature 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.workNature();
        }
    }

    componentDidMount() {
        this.init();
    }

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

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

        hrmWorkNatureSet.mobxDatasReset();
        hrmWorkNatureSet.setOperation('getTableInfo');
        hrmWorkNatureSet.getTableInfo();
    }

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

        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 {
            hrmWorkNatureSet
        } = this.props, {
            isMpPanelShow
        } = hrmWorkNatureSet;

        isMpPanelShow && hrmWorkNatureSet.setMpPanelStatus(false);
        this[key] && this[key]();
    }

    //WeaTop
    getTopMenuBtns() {
        const {
            hrmWorkNatureSet
        } = this.props, {
            topMenu,
            mpTableStore,
            type
        } = hrmWorkNatureSet;

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

    handleClick(item) {
        const {
            hrmWorkNatureSet
        } = this.props, {
            isMpPanelShow
        } = hrmWorkNatureSet;

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

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

        hrmWorkNatureSet.setNeTitle(i18n.label.newWorkNature());
        hrmWorkNatureSet.setNeVisible(true);
        hrmWorkNatureSet.newSet('new', 'addForm');
        hrmWorkNatureSet.getNeForm();
    }

    import () {
        const {
            hrmWorkNatureSet
        } = this.props;

        hrmWorkNatureSet.setItVisible(true);
        hrmWorkNatureSet.setOperation('import');
        hrmWorkNatureSet.getImportForm();
    }

    batchDelete() {
        const {
            hrmWorkNatureSet
        } = this.props, {
            mpTableStore
        } = hrmWorkNatureSet;

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

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

        if (id) {
            hrmWorkNatureSet.deleteSet(id, 'delete');
        } else {
            hrmWorkNatureSet.setOperation('batchDelete');
        }
        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 {
            hrmWorkNatureSet
        } = this.props;
        hrmWorkNatureSet.delete();
    }

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

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

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

    save() {
        const {
            hrmWorkNatureSet
        } = this.props, {
            formType
        } = hrmWorkNatureSet;

        if (formType == 'new') {
            hrmWorkNatureSet.setOperation('save_new');
            hrmWorkNatureSet.add();
        } else if (formType == 'edit') {
            hrmWorkNatureSet.setOperation('save_edit');
            hrmWorkNatureSet.edit();
        }
    }
    //WeaTab
    getTabBtn() {
        const {
            hrmWorkNatureSet
        } = this.props, {
            mpShForm
        } = hrmWorkNatureSet;

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gylahj`} type="primary" onClick={() => this.handleMpSearch()}>搜索</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@de8409`} onClick={() => mpShForm.reset()}>重置</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h4i3ms}`} onClick={() => hrmWorkNatureSet.setMpPanelStatus(false)}>取消</Button>),
        ];
        return btn;
    }

    getMpShBaseValue() {
        const {
            hrmWorkNatureSet
        } = this.props, {
            mpShForm,
            wnName
        } = hrmWorkNatureSet;

        let val;
        if (mpShForm.isFormInit) {
            val = mpShForm.getFormParams().name;
        } else {
            val = wnName;
        }
        return val;
    }

    handleMpShChange(val) {
        const {
            hrmWorkNatureSet
        } = this.props, {
            mpShForm
        } = hrmWorkNatureSet;

        if (mpShForm.isFormInit) {
            hrmWorkNatureSet.updateFields(val);
        }
        hrmWorkNatureSet.setSearchName(val);
    }

    handleMpPanelStatus(bool) {
        const {
            hrmWorkNatureSet
        } = this.props, {
            mpShCondition
        } = hrmWorkNatureSet;

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

    handleMpSearch() {
        const {
            hrmWorkNatureSet
        } = this.props, {
            isMpPanelShow
        } = hrmWorkNatureSet;

        hrmWorkNatureSet.setOperation('getTableInfo');
        hrmWorkNatureSet.getTableInfo(); //获取表格信息
        isMpPanelShow && hrmWorkNatureSet.setMpPanelStatus(false); //关闭面板
    }

    getPanelComponents() {
        const {
            hrmWorkNatureSet
        } = this.props, {
            mpShCondition,
            mpShForm,
            mpShLoading
        } = hrmWorkNatureSet, {
            isFormInit
        } = mpShForm;

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

        if (mpShLoading) {
            return (
                <div className='hrm-loading-center-small' style={{top:'25%'}}>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@aj24al`} spinning={mpShLoading}></Spin>
                </div>
            )
        } else {
            return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@yc4su6`} 
                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 == 'name') {
                c.render = function(text, record) {
                    return <a onClick={() => _this.doEdit(record.randomFieldId)} >{record.name}</a>
                }
            };
        })
    }

    onOperatesClick(record, index, operate) {
        let i = operate.index;

        i == '0' && this.doEdit(record.randomFieldId);
        i == '1' && this.doDel(record.randomFieldId);
        i == '2' && this.deLog(record.randomFieldId);
    }

    doEdit(id) {
        const {
            hrmWorkNatureSet
        } = this.props;

        hrmWorkNatureSet.setNeTitle(i18n.label.editWorkNature());
        hrmWorkNatureSet.setNeVisible(true);
        hrmWorkNatureSet.editSet(id, 'edit', 'editFrom');
        hrmWorkNatureSet.getNeForm();
    }

    doDel(id) {
        this.deleteRows(id);
    }

    deLog(id) {
        window.setLogViewProps({
            logSmallType: '3018',
            targetId: id,
        });
    }

    //NewAndEditDialog
    handleNeCancel() {
        const {
            hrmWorkNatureSet
        } = this.props;

        hrmWorkNatureSet.setNeVisible(false);
        hrmWorkNatureSet.neReset();
    }

    render() {
        const {
            hrmWorkNatureSet
        } = this.props, {
            wtpLoading,
            isEdit,
            date
        } = hrmWorkNatureSet, {
            mpTitle
        } = hrmWorkNatureSet, {
            isMpPanelShow,
            conditionNum
        } = hrmWorkNatureSet, {
            mpTableStore
        } = hrmWorkNatureSet, {
            neTitle,
            neVisible,
            neCondition,
            neForm,
            neLoading
        } = hrmWorkNatureSet;

        return (
            <div>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ln4ew9`} 
                    datas={this.getDropMenuDatas()} 
                    onClick={ key=>this.handleMenuClick(key)}
                    collectParams={{favname: mpTitle,favouritetype:5}}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@qulh2e`} 
                        title={mpTitle}
                        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@dw0tr2`}
                            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={ ()=>hrmWorkNatureSet.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@umxyt3`} 
                            comsWeaTableStore={mpTableStore}
                            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@8eba78`} 
                        title={neTitle}
                        visible={neVisible}
                        condition={toJS(neCondition)}
                        form={neForm}
                        isFormInit={neForm.isFormInit}
                        loading={neLoading}
                        isEdit={isEdit}
                        save={() => this.save()}
                        onCancel={() => this.handleNeCancel()}
                />
            </div>
        )
    }
}