import React from 'react'
import * as mobx from 'mobx'
import {
    inject,
    observer,
} from 'mobx-react'

import {
    WeaTop,
    WeaDropdown,
    WeaRightMenu,
    WeaLeftRightLayout,
} from 'ecCom'

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

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

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

const WrappedJobGroupEditor = HocFactory(NewAndEditDialog, 'jobGroup');
const WrappedJobEditor = HocFactory(NewAndEditDialog, 'job');
const WrappedPostEditor = HocFactory(NewAndEditDialog, 'post');

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

const {
    ButtonSelect
} = WeaDropdown;

import LeftTree from './LeftTree'
import AreaTable from './AreaTable'
import TabInfo from './TabInfo'
import BriefInfo from './BriefInfo'

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

@inject('hrmImportCommon')
@inject('hrmPostSet')
@observer
export default class Post 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.postSetting();
        }
    }

    componentDidMount() {
        this.init();
    }

    componentWillReceiveProps(nextProps) {
        const {
            hrmPostSet
        } = this.props;
        if (this.props.location.key !== nextProps.location.key) {
            hrmPostSet.orgTreeReload();
            this.handleTreeNodeClick('all', 'n'); //第二个参数没有实际意义，只是为了不让左侧树刷新
        }
    }

    componentWillUnmount() {
        const {
            hrmPostSet
        } = this.props;
        hrmPostSet.orgTreeReload();
        this.handleTreeNodeClick('all', 'n');
    }

    init() {
        const {
            hrmPostSet
        } = this.props;
        const {
            mpTableStore
        } = hrmPostSet;
        hrmPostSet.initSet('getTableInfo', 'getJobGroupList');
        hrmPostSet.getTableInfo();
    }

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

        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 {
            hrmPostSet
        } = this.props;
        const {
            isMpPanelShow
        } = hrmPostSet;
        isMpPanelShow && hrmPostSet.setMpPanelStatus(false);
        this[key] && this[key]();
    }
    //WeaTop
    getBreadcrumb() {
        const {
            hrmPostSet
        } = this.props;
        const {
            type,
            curJobType,
            curJob,
            curPost
        } = hrmPostSet;
        let breadcrumb;
        if (type == 'all') breadcrumb = [{
            name: i18n.label.postSetting()
        }];
        if (type == 'JobGroup') {
            breadcrumb = [{
                name: i18n.label.postSetting(),
                onClick: () => this.handleTreeNodeClick('all')
            }, {
                name: curJobType
            }];
        }
        if (type == 'JobActivity') {
            breadcrumb = [{
                name: curJobType,
                onClick: () => this.handleTreeNodeClick('JobGroup')
            }, {
                name: curJob
            }];
        }
        if (type == 'JobTitle') {
            breadcrumb = [{
                name: curJob,
                onClick: () => this.handleTreeNodeClick('JobActivity')
            }, {
                name: curPost
            }];
        }
        return breadcrumb;
    }
    getTopMenuBtns() {
        const {
            hrmPostSet
        } = this.props;
        const {
            topMenu,
            mpTableStore,
            selectedKey,
            type
        } = hrmPostSet;
        let btns = [];
        toJS(topMenu).map((item, index) => {
            if (item.menuFun !== 'batchDelete') {
                btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ml9bk6@${index}`} type='primary' onClick={() => this.handleClick(item)}>{item.menuName}</Button>);
            } else {
                btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@viy4zr@${index}`} type='primary' onClick={() => this.handleClick(item)} disabled={mpTableStore.selectedRowKeys.length>0?false:true} >{item.menuName}</Button>);
            }
        });
        return btns;
    }
    handleClick(item) {
        const {
            hrmPostSet
        } = this.props;
        const {
            isMpPanelShow
        } = hrmPostSet;
        isMpPanelShow && hrmPostSet.setMpPanelStatus(false);
        this[item.menuFun] && this[item.menuFun]()
    }

    log = () => {
        const {
            hrmPostSet
        } = this.props, {
            type
        } = hrmPostSet;

        window.setLogViewProps({
            logSmallType: (type == 'all') ? '3012' : (type == 'JobGroup') ? '3013' : '3014',
        });
    }

    newJobGroup() {
        const {
            hrmPostSet
        } = this.props;

        hrmPostSet.setJgTitle(i18n.label.newJobType());
        hrmPostSet.setJgVisible(true);
        hrmPostSet.newSet('new', 'jobGroup', 'getNewForm', 'getJobGroupForm');
        hrmPostSet.getNeForm();
    }
    newJob() {
        const {
            hrmPostSet
        } = this.props;

        hrmPostSet.setJbTitle(i18n.label.newJob());
        hrmPostSet.setJbVisible(true);
        hrmPostSet.newSet('new', 'job', 'getNewForm', 'getJobForm');
        hrmPostSet.getNeForm();
    }
    newPost() {
        const {
            hrmPostSet
        } = this.props;

        hrmPostSet.setPtTitle(i18n.label.newPost());
        hrmPostSet.setPtVisible(true);
        hrmPostSet.newSet('new', 'post', 'getNewForm', 'getPostForm');
        hrmPostSet.getNeForm();
    }
    save() {
        const {
            hrmPostSet
        } = this.props;
        const {
            formType,
            neJgForm,
            neJbForm,
            nePtForm
        } = hrmPostSet;
        if (neJgForm.isFormInit) {
            if (formType == 'new') {
                hrmPostSet.saveSet('jobGroup', 'save_new', 'addJobGroup');
                hrmPostSet.add();
                if (neJbForm.isFormInit) {
                    return;
                }
            } else {
                hrmPostSet.saveSet('', 'save_edit', 'editJobGroup');
                hrmPostSet.edit();
            }
        } else {
            if (neJbForm.isFormInit) {
                if (formType == 'new') {
                    hrmPostSet.saveSet('job', 'save_new', 'addJob');
                    hrmPostSet.add();
                    if (nePtForm.isFormInit) {
                        return;
                    }
                } else {
                    hrmPostSet.saveSet('', 'save_edit', 'editJob');
                    hrmPostSet.edit();
                }
            } else {
                if (nePtForm.isFormInit) {
                    if (formType == 'new') {
                        hrmPostSet.saveSet('post', 'save_new', 'addPost');
                        hrmPostSet.add();
                    } else {
                        hrmPostSet.saveSet('', 'save_edit', 'editPost');
                        hrmPostSet.edit();
                    }
                }

            }
        }
    }

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

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

    batchDelete() {
        const {
            hrmPostSet
        } = this.props;
        const {
            mpTableStore,
            type
        } = hrmPostSet;
        let keys = toJS(mpTableStore.selectedRowKeys).toString();
        hrmPostSet.setSelectedRowsKeys(keys);
        this.delete();
    }
    edit(id) {
        const {
            hrmPostSet
        } = this.props;
        const {
            type,
            selectedKey
        } = hrmPostSet;
        if (id) {
            type == 'all' && hrmPostSet.setJobGroupId(id);
            type == 'JobGroup' && hrmPostSet.setJobActivityId(id);
            type == 'JobActivity' && hrmPostSet.setJobTitleId(id);
        }
        if (type == 'all' || (type == 'JobGroup' && selectedKey == '0')) {
            hrmPostSet.setJgTitle(i18n.label.editJobType());
            hrmPostSet.setJgVisible(true);
            hrmPostSet.editSet('edit', 'getEditForm', 'getJobGroupForm');
            hrmPostSet.getNeForm();
        } else if ((type == 'JobGroup' && selectedKey == '1') || (type == 'JobActivity' && selectedKey == '0')) {
            hrmPostSet.setJbTitle(i18n.label.editJob());
            hrmPostSet.setJbVisible(true);
            hrmPostSet.editSet('edit', 'getEditForm', 'getJobForm');
            hrmPostSet.getNeForm();
        } else {
            hrmPostSet.setPtTitle(i18n.label.editPost());
            hrmPostSet.setPtVisible(true);
            hrmPostSet.editSet('edit', 'getEditForm', 'getPostForm');
            hrmPostSet.getNeForm();
        }
    }
    delete(id) {
        const {
            hrmPostSet
        } = this.props;
        const {
            type,
            selectedKey
        } = hrmPostSet;
        if (id) { //删除表格中单条数据
            type == 'all' && hrmPostSet.setJobGroupId(id);
            type == 'JobGroup' && hrmPostSet.setJobActivityId(id);
            type == 'JobActivity' && hrmPostSet.setJobTitleId(id);
            hrmPostSet.deleteSet('delete');
        } else {
            if (selectedKey == '0') {
                if (type !== 'all') {
                    hrmPostSet.deleteSet('delete'); //删除基本信息
                } else {
                    hrmPostSet.deleteSet('batch_delete'); //批量删除
                }
            } else {
                hrmPostSet.deleteSet('batch_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 {
            hrmPostSet
        } = this.props;
        const {
            type,
            selectedKey
        } = hrmPostSet;
        if (type == 'all') {
            hrmPostSet.setFuncName('deleteJobGroup');
            hrmPostSet.delete();
        } else if (type == 'JobGroup') {
            if (selectedKey == '0') {
                hrmPostSet.setFuncName('deleteJobGroup');
                hrmPostSet.delete();
                this.handleTreeNodeClick('all');
            } else {
                hrmPostSet.setFuncName('deleteJob');
                hrmPostSet.delete();
            }
        } else if (type == 'JobActivity') {
            if (selectedKey == '0') {
                hrmPostSet.setFuncName('deleteJob');
                hrmPostSet.delete();
                this.handleTreeNodeClick('JobGroup');
            } else {
                hrmPostSet.setFuncName('deletePost');
                hrmPostSet.delete();
            }
        } else if (type == 'JobTitle') {
            hrmPostSet.setFuncName('deletePost');
            hrmPostSet.delete();
            this.handleTreeNodeClick('JobActivity');
        }
    }
    jobSystemImport() {
        const {
            hrmImportCommon,
        } = this.props, {
            setTempletName,
            setImportDialogTitle,
            setImportType,
            setImportDialogVisible,
            setImportPage,
        } = hrmImportCommon;

        setTempletName(i18n.label.importTemplate());
        setImportDialogTitle(i18n.button.postSystemImport());
        setImportType('jobtitle');
        setImportDialogVisible(true);
        //设置标识，标识当前是那个页面在导入
        setImportPage(this.props.location.pathname.split('/').pop());
    }
    //WeaLeftRightLayout-LeftTree
    getLeftCom() {
        const {
            hrmPostSet
        } = this.props;
        const {
            treeRefresh,
            otReload
        } = hrmPostSet;
        return (
            <LeftTree ecId={`${this && this.props && this.props.ecId || ''}_LeftTree@oa0org`}
                treeRefresh={treeRefresh}
                reload={otReload}
                treeNodeClick={(type,id,pid) => this.handleTreeNodeClick(type,id,pid)}
            />
        )
    }
    handleTreeNodeClick(type, id, pid) {
        const {
            hrmPostSet
        } = this.props;
        const {
            isMpPanelShow
        } = hrmPostSet;

        hrmPostSet.setType(type); //设置节点类型
        hrmPostSet.selectedKeyReset(); //重置页签的key值
        isMpPanelShow && hrmPostSet.setMpPanelStatus(false); //关闭面板
        hrmPostSet.mpSearchReset(); //重置搜索条件
        type == 'all' && this.init(); //点击第一层级节点
        type == 'JobGroup' && id && hrmPostSet.setJobGroupId(id); //点击第二层级节点（点击节点时才会接收到id）
        if (type == 'JobActivity' && id) {
            pid && hrmPostSet.setJobGroupId(pid);
            hrmPostSet.setJobActivityId(id); //点击第三层级节点
        }
        if (type == 'JobTitle' && id) {
            pid && hrmPostSet.setJobActivityId(pid);
            hrmPostSet.setJobTitleId(id); //点击第四层级节点
        }

        if (type !== 'all') {
            hrmPostSet.setOperation('getBriefInfo');
            hrmPostSet.getBriefInfo(); //获取基本信息
        }!id && hrmPostSet.setTreeRefresh(); //点击面包屑时刷新组织树
    }
    //TabInfo
    getTabName() {
        const {
            hrmPostSet
        } = this.props;
        const {
            type
        } = hrmPostSet;
        let tabName;
        if (type == 'JobGroup') {
            tabName = [{
                key: '0',
                title: i18n.label.typeInfo()
            }, {
                key: '1',
                title: i18n.label.subordinatePosition()
            }, ]
        } else if (type == 'JobActivity') {
            tabName = [{
                key: '0',
                title: i18n.label.jobInfo()
            }, {
                key: '1',
                title: i18n.label.lowerPost()
            }, ]
        }
        return tabName;
    }
    getSearchType() {
        const {
            hrmPostSet
        } = this.props;
        const {
            type,
            selectedKey
        } = hrmPostSet;
        if (type == 'all' || ((type == 'JobGroup' || type == 'JobActivity') && selectedKey == '1')) {
            return ['base', 'advanced'];
        }
    }
    getMpShBaseValue() {
        const {
            hrmPostSet
        } = this.props;
        const {
            type,
            mpShForm,
            jobGroupName,
            jobName,
            postName
        } = hrmPostSet;
        let val;
        if (mpShForm.isFormInit) {
            if (type == 'all') {
                val = mpShForm.getFormParams().jobgroupmark;
            } else if (type == 'JobGroup') {
                val = mpShForm.getFormParams().jobactivitymark;
            } else if (type == 'JobActivity') {
                val = mpShForm.getFormParams().jobtitlemark;
            }
        } else {
            if (type == 'all') val = jobGroupName;
            if (type == 'JobGroup') val = jobName;
            if (type == 'JobActivity') val = postName;
        }
        return val;
    }
    handleMpShChange(val) {
        const {
            hrmPostSet
        } = this.props;
        const {
            type,
            mpShForm
        } = hrmPostSet;
        if (mpShForm.isFormInit) {
            hrmPostSet.updateFields(val);
        }
        type == 'all' && hrmPostSet.setJobGroupName(val);
        type == 'JobGroup' && hrmPostSet.setJobName(val);
        type == 'JobActivity' && hrmPostSet.setPostName(val);

    }
    handleMpPanelStatus(bool) {
        const {
            hrmPostSet
        } = this.props;
        const {
            mpShCondition
        } = hrmPostSet;
        if (bool) { //打开面板
            hrmPostSet.setMpPanelStatus(true);
            if (mpShCondition.length == 0) { //第一次打开面板时加载高级搜索数据
                hrmPostSet.setOperation('mpSearch');
                hrmPostSet.getMpSearchCondition();
            }
        } else { //关闭面板
            hrmPostSet.setMpPanelStatus(false);
            // hrmPostSet.mpSearchReset();
        }
    }
    handleTabClick(key) {
        const {
            hrmPostSet
        } = this.props;
        const {
            isMpPanelShow,
            selectedKey,
            type
        } = hrmPostSet;
        hrmPostSet.setSelectedKey(key); //设置页签key值
        isMpPanelShow && hrmPostSet.setMpPanelStatus(false); //关闭面板
        hrmPostSet.mpSearchReset();
        if (key == '0') { //切换到第一个页签
            hrmPostSet.tabSet('getBriefInfo');
            hrmPostSet.getBriefInfo();
        } else if (key == '1') { //切换到第二个页签
            type == 'JobGroup' && hrmPostSet.tabSet('getTableInfo', 'getJobActivityList');
            type == 'JobActivity' && hrmPostSet.tabSet('getTableInfo', 'getJobTitleList');
            hrmPostSet.getTableInfo();
        }
    }
    handleMpSearch() {
        const {
            hrmPostSet
        } = this.props;
        const {
            type,
            isMpPanelShow
        } = hrmPostSet;
        type == 'all' && hrmPostSet.tabSet('getTableInfo', 'getJobGroupList');
        type == 'JobGroup' && hrmPostSet.tabSet('getTableInfo', 'getJobActivityList');
        type == 'JobActivity' && hrmPostSet.tabSet('getTableInfo', 'getJobTitleList');
        hrmPostSet.getTableInfo(); //获取表格信息
        isMpPanelShow && hrmPostSet.setMpPanelStatus(false); //关闭面板
    }
    //AreaTable
    tdClick(params) {
        const {
            hrmPostSet
        } = this.props;
        let type = params.indexTo;
        let id = params.id;
        let isTabSwitch = params.isTabSwitch;
        this.handleTreeNodeClick(type, id);
        isTabSwitch && this.handleTabClick('1');
    }
    //WrappedJobGroupEditor
    handleJgCancel() {
        const {
            hrmPostSet
        } = this.props;
        hrmPostSet.setJgVisible(false);
        hrmPostSet.jgReset();
    }
    handleJbCancel() {
        const {
            hrmPostSet
        } = this.props;
        hrmPostSet.setJbVisible(false);
        hrmPostSet.jbReset();
    }
    handlePtCancel() {
        const {
            hrmPostSet
        } = this.props;
        hrmPostSet.setPtVisible(false);
        hrmPostSet.ptReset();
    }
    addOnClick(type) {
        if (type == 'jobGroup') this.newJobGroup();
        if (type == 'job') this.newJob();
    }

    render() {
        const {
            hrmPostSet
        } = this.props;
        const {
            type,
            wtpLoading,
            date
        } = hrmPostSet; //common
        const {
            mpLoading
        } = hrmPostSet; //Weatop
        const {
            mpShCondition,
            mpShForm,
            isMpPanelShow,
            mpShLoading,
            selectedKey
        } = hrmPostSet; //TabInfo
        const {
            briefInfo,
            bfLoading
        } = hrmPostSet; //BriefInfo
        const {
            mpTableStore
        } = hrmPostSet; //AreaTable
        const {
            jgTitle,
            jgVisible,
            jgCondition,
            neJgForm,
            jgLoading
        } = hrmPostSet; //WrappedJobGroupEditor
        const {
            jbTitle,
            jbVisible,
            jbCondition,
            neJbForm,
            jbLoading
        } = hrmPostSet; //WrappedJobEditor
        const {
            ptTitle,
            ptVisible,
            ptCondition,
            nePtForm,
            ptLoading
        } = hrmPostSet; //WrappedPostEditor

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

        return (
            <div ref='page'>
    	        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@uexutl`} 
                    datas={this.getDropMenuDatas()} 
                    onClick={(e) => this.handleMenuClick(e)}
                    collectParams={{favname:i18n.label.postSetting(),favouritetype:5}}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@40ordj`} 
                        breadcrumb={this.getBreadcrumb()}
                        icon={<i className='icon-coms-hrm' />}
                        iconBgcolor='#217346'
                        loading={true}
                        buttons={this.getTopMenuBtns()}
                        showDropIcon={true}
                        dropMenuDatas={this.getDropMenuDatas()}
                        onDropMenuClick={(e) => this.handleMenuClick(e)}
                    >
                    <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@m9zfjx`} 
                        isNew={true}
                        leftCom={this.getLeftCom()}
                    >
                        {  type !== 'JobTitle' ?    <TabInfo ecId={`${this && this.props && this.props.ecId || ''}_TabInfo@krchfj`}
                                                        condition={toJS(mpShCondition)}
                                                        form={mpShForm}
                                                        isFormInit={mpShForm.isFormInit}
                                                        isPanelShow={isMpPanelShow}
                                                        loading={mpShLoading}
                                                        selectedKey={selectedKey}
                                                        tabName={this.getTabName()}
                                                        searchType={this.getSearchType()}
                                                        searchsBaseValue={this.getMpShBaseValue()}
                                                        search={() => this.handleMpSearch()}
                                                        onSearchChange={val => this.handleMpShChange(val)}
                                                        setPanelStatus={ b => this.handleMpPanelStatus(b)}
                                                        setSelectedKey={key => this.handleTabClick(key)}
                                                    /> : <div></div>}
                        { type !== 'all' && selectedKey == '0'? <BriefInfo ecId={`${this && this.props && this.props.ecId || ''}_BriefInfo@5v95mh`} datas={toJS(briefInfo)}/>    :   <AreaTable ecId={`${this && this.props && this.props.ecId || ''}_AreaTable@uxwybk`} 
                                                                                                                                    tableStore={mpTableStore}
                                                                                                                                    type={type}
                                                                                                                                    getEditForm={ id => this.edit(id)}
                                                                                                                                    deleteRows={ id => this.delete(id)}
                                                                                                                                    tdClick={ params => this.tdClick(params)}
                                                                                                                                />}                                                                             
                    </WeaLeftRightLayout>
                </WeaTop>
                </WeaRightMenu>
                <WrappedPostEditor ecId={`${this && this.props && this.props.ecId || ''}_WrappedPostEditor@icd25x`} 
                    title={ptTitle}
                    visible={ptVisible}
                    condition={toJS(ptCondition)}
                    form={nePtForm}
                    isFormInit={nePtForm.isFormInit}
                    loading={ptLoading}
                    addOnClick={(type)=>this.addOnClick(type)}
                    save={() => this.save()}
                    onCancel={() => this.handlePtCancel()}
                />
                <WrappedJobEditor ecId={`${this && this.props && this.props.ecId || ''}_WrappedJobEditor@6m1atz`}
                    title={jbTitle}
                    visible={jbVisible}
                    condition={toJS(jbCondition)}
                    form={neJbForm}
                    isFormInit={neJbForm.isFormInit}
                    loading={jbLoading}
                    addOnClick={(type)=>this.addOnClick(type)}
                    save={() => this.save()}
                    onCancel={() => this.handleJbCancel()}
                />
                <WrappedJobGroupEditor ecId={`${this && this.props && this.props.ecId || ''}_WrappedJobGroupEditor@4cb9ml`} 
                    title={jgTitle}
                    visible={jgVisible}
                    condition={toJS(jgCondition)}
                    form={neJgForm}
                    isFormInit={neJgForm.isFormInit}
                    loading={jgLoading}
                    save={() => this.save()}
                    onCancel={() => this.handleJgCancel()}
                />
                {importDialog.visible && <Import ecId={`${this && this.props && this.props.ecId || ''}_Import@81y4mr`} />}
    	    </div>
        )
    }
}