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 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('hrmTitleSet')
@observer
export default class Title 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.titleSetting();
        }
    }

    componentDidMount() {
        this.init();
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    getMpShBaseValue() {
        const {
            hrmTitleSet
        } = this.props, {
            mpShForm,
            titleName
        } = hrmTitleSet;

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

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

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

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

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

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

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

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

        let arr = [];
        isFormInit && mpShCondition.map(c => {
            c.items.map((field, index) => {
                arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@wxpk0f@${index}`} span={10} offset={1}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@k7iwzk@${index}`}
                                      label={`${field.label}`}
                                      labelCol={{span: `${field.labelcol}`}}
                                      wrapperCol={{span: `${field.fieldcol}`}}>
                                          {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@64ts1t@${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@vl7wyk`} spinning={mpShLoading}></Spin>
                </div>
            )
        } else {
            return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@9wl6cf`}
                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 {
            hrmTitleSet
        } = this.props;

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

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

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

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

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

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

        return (
            <div>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@2dfwmv`} 
                    datas={this.getDropMenuDatas()} 
                    onClick={ key=>this.handleMenuClick(key)}
                    collectParams={{favname: mpTitle,favouritetype:5}}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@5i0cbp`} 
                        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@zbalg3`}
                            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={ ()=>hrmTitleSet.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@8ajhrm`} 
                            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@sdz397`} 
                    title={neTitle}
                    visible={neVisible}
                    condition={toJS(neCondition)}
                    form={neForm}
                    isFormInit={neForm.isFormInit}
                    loading={neLoading}
                    isEdit={isEdit}
                    save={() => this.save()}
                    onCancel={() => this.handleNeCancel()}
                />
            </div>
        )
    }
}