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

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

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

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

import {
    WeaSwitch,
    WeaTableNew,
} from 'comsMobx'

import {
    i18n
} from '../../public/i18n';
import '../../style/area.css'

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

import Import from '../importRelatedComponet/index';
import {
    HrmImportCommon
} from '../../stores/importCommon';
const hrmImportCommon = new HrmImportCommon();

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

@inject('hrmImportCommon')
@inject('hrmMajorSet')
@observer
export default class Major extends React.Component {
    constructor(props) {
        super(props);
    }

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

    componentDidMount() {
        this.init();
    }

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

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

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

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

        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: '3016',
        });
    }

    handleMenuClick(key) {
        const {
            hrmMajorSet
        } = this.props, {
            isMpPanelShow
        } = hrmMajorSet;

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

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

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

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

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

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

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

    import () {
        const {
            hrmImportCommon,
        } = this.props, {
            setTempletName,
            setImportDialogTitle,
            setImportType,
            setImportDialogVisible,
            setImportPage,
        } = hrmImportCommon;

        setTempletName(i18n.label.importTemplate());
        setImportDialogTitle(i18n.button.majorImport());
        setImportType('special');
        setImportDialogVisible(true);
        //设置标识，标识当前是那个页面在导入
        setImportPage(this.props.location.pathname.split('/').pop());
    }

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

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

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

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

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

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

        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 {
            hrmMajorSet
        } = this.props;
        hrmMajorSet.delete();
    }

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

        if (formType == 'new') {
            hrmMajorSet.setOperation('save_new');
            hrmMajorSet.add();
        } else if (formType == 'edit') {
            hrmMajorSet.setOperation('save_edit');
            hrmMajorSet.edit();
        }
    }

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

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h2qlim`} type="primary" onClick={() => this.handleMpSearch()}>{i18n.button.search()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ttflb4`} onClick={() => mpShForm.reset()}>{i18n.button.reset()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lo3wjs`} onClick={() => hrmMajorSet.setMpPanelStatus(false)}>{i18n.button.cancel()}</Button>),
        ];
        return btn;
    }

    getMpShBaseValue() {
        const {
            hrmMajorSet
        } = this.props, {
            mpShForm,
            majorName
        } = hrmMajorSet;

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

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

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

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

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

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

        let arr = [];
        isFormInit && mpShCondition.map(c => {
            c.items.map((field, index) => {
                arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@gf63dh@${index}`} span={10} offset={1}>
                              <div style={{marginTop: 20}}>
                                    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@73tyj2@${index}`}
                                        label={`${field.label}`}
                                        labelCol={{span: `${field.labelcol}`}}
                                        wrapperCol={{span: `${field.fieldcol}`}}>
                                            {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@g4jemq@${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@7xyzpg`} spinning={mpShLoading}></Spin>
                </div>
            )
        } else {
            return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@mdgkbw`}
                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, rowIndex, operate) {
        const {
            index
        } = operate;

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

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

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

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

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

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

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

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

        const {
            hrmImportCommon
        } = this.props, {
            importDialog
        } = hrmImportCommon;

        return (
            <div>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@a5u9qv`} 
                    datas={this.getDropMenuDatas()} 
                    onClick={ key=>this.handleMenuClick(key)}
                    collectParams={{favname:mpTitle,favouritetype:5}}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@5qgne3`} 
                        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@x4tah7`}
                            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={ ()=>hrmMajorSet.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@la2w9m`} 
                            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@6z035o`} 
                    title={neTitle}
                    visible={neVisible}
                    condition={toJS(neCondition)}
                    form={neForm}
                    isFormInit={neForm.isFormInit}
                    loading={neLoading}
                    isEdit={isEdit}
                    save={() => this.save()}
                    onCancel={() => this.handleNeCancel()}
                />
                 {importDialog.visible && <Import ecId={`${this && this.props && this.props.ecId || ''}_Import@de0x6o`} />}
            </div>
        )
    }
}