import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal, message } from 'antd'
import * as mobx from 'mobx';
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
// import Immutable from 'immutable'
// const is = Immutable.is;
import Simple from './simple'
import Full from './full'
import '../../style/add.less';
import { jumpToHrmCard } from '../../util/pulic-func'
import {
    WeaTab, WeaTop, WeaSearchGroup, WeaRightMenu, WeaPopoverHrm, WeaLeftRightLayout,
    WeaOrgTree, WeaSelect, WeaErrorPage, WeaTools, WeaFormItem, WeaSearchBrowserBox, WeaDialog, WeaLocaleProvider
} from 'ecCom'
import { WeaTableNew, WeaSwitch } from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import * as PublicFunc from '../../util/pulic-func';
import { i18n } from '../../public/i18n';
const getLabel = WeaLocaleProvider.getLabel;

@inject('hrmAdd')

@observer
class Add extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount () {
        const { hrmAdd } = this.props;
        hrmAdd.setSearchsValue('');
        hrmAdd.setDefDialog()
        hrmAdd.getData();
    }
    componentWillReceiveProps (nextProps) {
        const { hrmAdd } = this.props;
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        if (keyOld !== keyNew) {
            hrmAdd.setShowSearchAd(false);
            this.componentDidMount();
        }
    }
    componentWillUnmount () {
        const { hrmAdd } = this.props;
        hrmAdd.setShowSearchAd(false);
        hrmAdd.simpleVisible = false;
    }

    onSimpleCancelHandle = () => {
        const { hrmAdd } = this.props;
        hrmAdd.simpleVisible = false;
    }

    onFullCancelHandle = () => {
        const { hrmAdd } = this.props;
        hrmAdd.fullVisible = false;
    }

    render () {
        const { hrmAdd } = this.props;
        const { dataKey, title, searchParamsAd, showSearchAd, table, simpleVisible, fullVisible, jobtitleVisible, closeJobtitleDialog, formSimple, formFull, searchsValue } = hrmAdd;

        return <div className='wea-myhrm-Add'>
            <Simple ecId={`${this && this.props && this.props.ecId || ''}_Simple@iutso2`}
                visible={simpleVisible}
                openFullmode={this.openFullmode}
                update={this.update}
                onCancel={this.onSimpleCancelHandle}
            />

            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@sndxa9`} datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@hf8jhq`}
                    title={title()}
                    icon={<i className='icon-coms-hrm' />}
                    iconBgcolor='#217346'
                    buttons={this.getButtons()}
                    buttonSpace={10}
                    showDropIcon={true}
                    dropMenuDatas={this.getRightMenu()}
                    onDropMenuClick={this.onRightMenuClick}
                >
                    <div style={{ height: '100%' }}>
                        <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@yu4gg0`} isNew={true} leftCom={this.getTree()} >
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ata7dk`}
                                onlyShowRight={true}
                                buttonsAd={this.getTabButtonsAd()}
                                searchType={['base', 'advanced']}
                                searchsBaseValue={searchsValue}
                                setShowSearchAd={bool => { hrmAdd.setShowSearchAd(bool) }}
                                hideSearchAd={() => hrmAdd.setShowSearchAd(false)}
                                searchsAd={<div
                                    onKeyDown={(e) => {
                                        if (e.keyCode == 13 && e.target.tagName === "INPUT") {
                                            hrmAdd.doSearch();
                                            hrmAdd.setShowSearchAd(false);
                                        }
                                    }}
                                >{this.getSearchs(true)}</div>}
                                showSearchAd={showSearchAd}
                                onSearch={hrmAdd.doSearch}
                                onSearchChange={
                                    debounce(v => {
                                        hrmAdd.searchsValue = v;
                                    }, 200)
                                }
                            />
                            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@wqcyi9`} comsWeaTableStore={table}
                                hasOrder={true}
                                needScroll={true}
                                getColumns={this.reRenderColumns}
                                onOperatesClick={this.onOperatesClick}
                            />
                        </WeaLeftRightLayout>
                    </div>
                </WeaTop>
            </WeaRightMenu>
            {
                jobtitleVisible && (
                    <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@fw8u8f`}
                        onCancel={closeJobtitleDialog}
                        icon='icon-coms-hrm'
                        iconBgcolor='#217346'
                        title={i18n.label['531838']()}
                        callback={
                            datas => {
                                const {
                                    id,
                                    jobtitlemark
                                } = datas;

                                const form = simpleVisible ? formSimple : formFull;
                                form.updateFields({
                                    jobtitle: {
                                        value: id,
                                        valueSpan: jobtitlemark,
                                        valueObj: [{
                                            id,
                                            name: jobtitlemark
                                        }]
                                    }
                                });

                                closeJobtitleDialog();

                            }
                        }
                        url={'/spa/hrm/engine.html#/hrmengine/posts?type=0'}
                        visible={jobtitleVisible}
                        style={{ width: 600, height: 500 }}
                    />
                )
            }

            <Full ecId={`${this && this.props && this.props.ecId || ''}_Full@ndgvg5`}
                visible={fullVisible}
                update={this.update}
                onCancel={this.onFullCancelHandle}
            />
        </div>
    }
    reRenderColumns = (columns) => {
        columns.forEach(c => {
            if (c.dataIndex == 'lastname') {
                c.render = (text, record) => {
                    return <span style={{ cursor: 'pointer' }} className='wea-hrm-linkstyle' onClick={() => this.jumpToHrmCard(record.id)}>{record.lastname}</span>
                }
            // } else {
            //     c.render = function (text, record) {
            //         let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
            //         return <span dangerouslySetInnerHTML={{ __html: valueSpan }}></span>
            //     }
            }
        })
        return columns;
    }
    jumpToHrmCard = (hrmId) => {
        jumpToHrmCard(hrmId)
    }

    update = () => {
        const { hrmAdd } = this.props;
        hrmAdd.update();
    }
    onOperatesClick = (record, index, operate, flag, argumentString) => {
        const fn = operate.href ? operate.href.split(':')[1].split('(')[0] : '';
        const id = record.id ? record.id : '';
        PublicFunc[fn](id);
    }
    addhrm = () => {
        const { hrmAdd } = this.props;
        const { dialogDefShow } = hrmAdd;
        //此处控制应该显示那种模式的弹窗
        if (dialogDefShow == '0') {
            hrmAdd.simpleVisible = true;
        } if (dialogDefShow == '1') {
            hrmAdd.fullVisible = true;
        }

    }
    openFullmode = () => {
        const { hrmAdd } = this.props;
        hrmAdd.openFullmode();
    }
    getButtons = () => {
        const { hrmAdd } = this.props;
        const { title } = hrmAdd;
        let btns = [];
        btns.push(
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yhvh3y@1`} type="primary" onClick={() => this.addhrm()} >{title()}</Button>
        );
        return btns
    }
    getTabButtonsAd = () => {
        const { hrmAdd } = this.props;
        const { formSearch } = hrmAdd;
        return [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oaisww@2`} type="primary" onClick={() => { hrmAdd.doSearch(); hrmAdd.setShowSearchAd(false) }}>{i18n.button.search()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sfc6yi@3`} type="ghost" onClick={() => { formSearch.resetConditionValue(); hrmAdd.searchsValue = "" }}>{i18n.button.reset()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@84t6om@4`} type="ghost" onClick={() => { hrmAdd.setShowSearchAd(false) }}>{i18n.button.cancel()}</Button>)
        ]
    }

    getSearchs = (bool) => {
        const { hrmAdd } = this.props;
        const { condition, formSearch } = hrmAdd;
        const { isFormInit } = formSearch;
        let searchGroupArr = [];
        isFormInit && condition && condition.forEach((item, index) => {
            searchGroupArr.push(
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@j0jnb7@${index}`}
                    needTigger={true}
                    title={this.getTitle(index)}
                    showGroup={this.isShowFields(index)}
                    items={this.getFields(bool, index)}
                />
            )
        })
        return searchGroupArr;
    }
    getTitle = (index = 0) => {
        const { hrmAdd } = this.props;
        const { condition } = hrmAdd;
        return !isEmpty(condition) && condition[index].title
    }
    isShowFields = (index = 0) => {
        const { hrmAdd } = this.props;
        const { condition } = hrmAdd;
        return !isEmpty(condition) && condition[index].defaultshow
    }

    onChangeHandle = debounce((datas) => {
        const { hrmAdd } = this.props;
        const { setSearchsValue } = hrmAdd;
        if (datas.resourcename) {
            setSearchsValue(datas.resourcename.value);
        }
    }, 500)

    getFields = (bool = false, index = 0) => {
        const { hrmAdd } = this.props;
        const { formSearch, condition, setSearchsValue } = hrmAdd;
        const browserConditions = condition;
        const fieldsData = !isEmpty(browserConditions) && browserConditions[index].items;
        let items = new Array();
        fieldsData.forEach((field, i) => {
            field && items.push({
                com: <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@fps26g@${i}`}
                    label={`${field.label}`}
                    labelCol={{ span: `${field.labelcol}` }}
                    wrapperCol={{ span: `${field.fieldcol}` }}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@p3iurz@${i}`} fieldConfig={field} form={formSearch} onChange={
                        // debounce((datas) => {
                        //     if (datas.resourcename) {
                        //         setSearchsValue(datas.resourcename.value);
                        //     }
                        // },500)
                        this.onChangeHandle
                    } />
                </WeaFormItem>,
                colSpan: field.colSpan || 2
            });
        });
        return items;
    }
    getTree = () => {
        return <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@pn1awu`}
            loading
            needDropMenu={false}
            needSearch
            isLoadSubDepartment={true}
            inputLeftDom={`<b>${i18n.label.organization()}</b>`}
            topPrefix={'hrmAdd'}
            treeNodeClick={this.treeNodeClick}
            params={{ rightStr: 'HrmResourceAdd:Add' }}
        />
    }
    treeNodeClick = (nodeObj) => {
        const type = nodeObj.node.props.type || '0';
        const id = nodeObj.node.props.id || '';
        const name = nodeObj.node.props.name || '';
        const { hrmAdd } = this.props;
        const { formSearch } = hrmAdd;
        hrmAdd.setShowSearchAd(false);
        let params = {};
        if (type == '1') {
            params.subcompanyid1 = id;
        }
        if (type == '2') {
            params.departmentid = id;
        }
        hrmAdd.doSearch(params);
    }
    getRightMenu = () => {
        const keys = this.getSelectedRowKeys();
        const arr = [
            {
                icon: <i className='icon-coms-New-Flow' />,
                content: i18n.module.createResource()
            }, {
                icon: <i className='icon-coms-ws' />,
                content: i18n.button.search()
            }, {
                icon: <i className='icon-coms-task-list' />,
                content: i18n.button.columnVisibleSetting()
            }
            // ,{
            //         icon: <i className='icon-Right-menu-Batch-sharing'/>,
            //         content:'收藏',
            // },{
            //         icon: <i className='icon-Right-menu-Custom'/>,
            //         content:'帮助'
            // }
        ];
        return arr;
    }
    onRightMenuClick = (key) => {
        switch (key) {
            case '0':
                this.addhrm();
                break;
            case '1':
                this.doSearch();
                break;
            case '2':
                this.definedColumn();
                break;
        }
    }
    getSelectedRowKeys = () => {
        const { hrmAdd } = this.props;
        const { table } = hrmAdd;
        const selectedRowKeys = table.selectedRowKeys;
        return selectedRowKeys;
    }
    sendEmessage = () => {
        const keys = this.getSelectedRowKeys();
        const ids = keys ? keys.join(',') : '';
        PublicFunc.sendEmessage(ids);
    }
    exportExcel = () => {
        const { hrmAdd } = this.props;
        const { dataKey } = hrmAdd;
        dataKey && hrmAdd.exportExcel(dataKey);
    }
    doSearch = () => {
        const { hrmAdd } = this.props;
        hrmAdd.doSearch();
    }

    definedColumn = () => {
        const { hrmAdd } = this.props;
        const { table } = hrmAdd;
        table.setColSetVisible(true);
        table.tableColSet(true);
    }
}

export default Add