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/common.less'

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

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

@inject('hrmImportCommon')
@inject('hrmOfficeAddress')
@observer
export default class OfficeAddress 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.workingPlace();
        }
    }
    componentDidMount() {
        this.init();
    }
    componentWillReceiveProps(nextProps) {
        const {
            hrmOfficeAddress
        } = this.props;

        if (this.props.location.key !== nextProps.location.key) {
            this.init();
        }
    }
    init() {
        const {
            hrmOfficeAddress
        } = this.props;
        hrmOfficeAddress.mobxDatasReset();
        hrmOfficeAddress.getTableInfo();
        hrmOfficeAddress.getHasRight();
    }
    getTopMenuBtns() {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            topMenu,
            tableStore
        } = hrmOfficeAddress;

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

        });

        return btns;
    }
    handleClick(item) {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            isPanelShow
        } = hrmOfficeAddress;

        isPanelShow && hrmOfficeAddress.setPanelStatus(false);
        this[item.menuFun] && this[item.menuFun]();
    }
    new() {
        const {
            hrmOfficeAddress
        } = this.props;

        hrmOfficeAddress.setNeDialogTitle(i18n.label.newWorkPlace());
        hrmOfficeAddress.setIsNew(true);
        hrmOfficeAddress.setVisible(true);
        hrmOfficeAddress.getForm();
    }
    handleLinkage(id) {
        const {
            hrmOfficeAddress
        } = this.props;
        hrmOfficeAddress.setCityId(id);
        hrmOfficeAddress.getCountryDetail();
    }
    handleSave() {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            isNew
        } = hrmOfficeAddress;

        isNew && hrmOfficeAddress.save();
        !isNew && hrmOfficeAddress.edit();
    }
    onCancel() {
        const {
            hrmOfficeAddress
        } = this.props;
        hrmOfficeAddress.setVisible(false);
        hrmOfficeAddress.conditionReset();
    }
    import () {
        const {
            hrmImportCommon,
        } = this.props, {
            setTempletName,
            setImportDialogTitle,
            setImportType,
            setImportDialogVisible,
            setImportPage,
        } = hrmImportCommon;

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

        let keys = toJS(tableStore.selectedRowKeys).toString();
        hrmOfficeAddress.setIds(keys);
        this.showConfirm('batchDel');
    }
    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 {
            hrmOfficeAddress
        } = this.props;
        hrmOfficeAddress.delete();
    }
    getDropMenuDatas() {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            rightMenu
        } = hrmOfficeAddress;

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

    custom = () => {
        const {
            hrmOfficeAddress
        } = this.props, {
            tableStore,
        } = hrmOfficeAddress;

        tableStore.setColSetVisible(true);
        tableStore.tableColSet(true);
    }
    handleMenuClick(key) {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            isPanelShow
        } = hrmOfficeAddress;

        isPanelShow && hrmOfficeAddress.setPanelStatus(false);
        this[key] && this[key]();
    }
    getPanelComponents() {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            searchCondition,
            form2,
            searchConditionLoading
        } = hrmOfficeAddress;

        let arr = [];
        let formParams = form2.getFormParams();
        const {
            isFormInit
        } = form2;

        isFormInit && searchCondition.map(c => {
            c.items.map((field, index) => {
                arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4cc308@${index}`} span={(index%2 == 0) ? 10 : 11} offset={1}>
                              <div style={{marginTop: 20}}>
                                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@u6ex85@${index}`}
                                      label={`${field.label}`}
                                      labelCol={{span: `${field.labelcol}`}}
                                      wrapperCol={{span: `${field.fieldcol}`}}>
                                          {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@p7d3td@${index}`} fieldConfig={field} form={form2} formParams={formParams} />}
                                  </WeaFormItem>
                              </div>
                  	     </Col>)
            })
        })

        if (searchConditionLoading) {
            return (
                <div className='hrm-loading-center-small' style={{top:'25%'}}>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@lbktzb`} spinning={searchConditionLoading}></Spin>
                </div>
            )
        } else {
            return <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ppeb6z`} onKeyDown={(e) => {
                if ( e.keyCode == 13 && e.target.tagName === "INPUT") {
                    hrmOfficeAddress.getTableInfo(); 
                    hrmOfficeAddress.setPanelStatus(false)
                }
            }}>{arr}</Row>
        }

    }
    getTabBtn() {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            form2
        } = hrmOfficeAddress;

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bx87i8`} type="primary" onClick={() => {hrmOfficeAddress.getTableInfo(); hrmOfficeAddress.setPanelStatus(false)}}>{i18n.button.search()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@218ju6`} onClick={() => form2.reset()}>{i18n.button.reset()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5u9mfz`} onClick={() => hrmOfficeAddress.setPanelStatus(false)}>{i18n.button.cancel()}</Button>),
        ];

        return btn;
    }
    onSearchChange(val) {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            form2
        } = hrmOfficeAddress;

        hrmOfficeAddress.setLocationName(val);
        !this.isEmptyObject(form2.getFormParams()) && hrmOfficeAddress.updateFields(val);
    }
    isEmptyObject(obj) {
        for (let key in obj) {
            return false;
        }
        return true;
    }
    reRenderColumns(columns) {
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'locationname') {
                c.render = function(text, record) {
                    return <a onClick={() => _this.doEdit(record.randomFieldId)} >{record.locationname}</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 {
            hrmOfficeAddress
        } = this.props;

        hrmOfficeAddress.setNeDialogTitle(i18n.label.editWorkPlace());
        hrmOfficeAddress.setLocationId(id);
        hrmOfficeAddress.setIsNew(false);
        hrmOfficeAddress.setVisible(true);
        hrmOfficeAddress.getForm();
    }
    doDel(id) {
        const {
            hrmOfficeAddress
        } = this.props;
        hrmOfficeAddress.setIds(id);
        this.showConfirm('del');
    }
    deLog(id) {
        window.setLogViewProps({
            logSmallType: '3010',
            targetId: id,
        });
    }
    submit() {
        const {
            hrmOfficeAddress
        } = this.props;
        hrmOfficeAddress.importInfoSubmit();
    }
    importHistoryQuery() {
        const {
            hrmOfficeAddress
        } = this.props;
        hrmOfficeAddress.getImportHistory();
    }
    jumpToImportResult(id) {
        const {
            hrmOfficeAddress
        } = this.props;

        hrmOfficeAddress.setPid(id);
        hrmOfficeAddress.getImportResult();
    }
    queryImportLog() {
        const {
            hrmOfficeAddress
        } = this.props;

        hrmOfficeAddress.getImportLogDetail();
        hrmOfficeAddress.getImportLogSearchCondition();
    }
    importLogSearch() {
        const {
            hrmOfficeAddress
        } = this.props;
        hrmOfficeAddress.getImportLogDetail();
    }

    render() {
        const {
            hrmOfficeAddress
        } = this.props;
        const {
            nEdialogTitle,
            isPanelShow,
            condition,
            conditionNum,
            form,
            tableStore,
            visible,
            isNew,
            dialogLoading,
            form1,
            form2,
            date,
            locationName,
            isEdit
        } = hrmOfficeAddress;

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

        return (
            <div ref='page' style={{height: '100%'}}>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@k6oc4u`} 
                    datas={this.getDropMenuDatas()} 
                    onClick={ key => this.handleMenuClick(key)}
                    collectParams={{favname:i18n.label.workingPlace(),favouritetype:5}}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@bj98s7`} 
                        title={i18n.label.workingPlace()}
                        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@9c3zts`}
                            searchType={['base','advanced']}
                            showSearchAd={isPanelShow}
                            searchsBaseValue={this.isEmptyObject(form2.getFormParams()) ? locationName : form2.getFormParams().name}
                            setShowSearchAd={ bool => hrmOfficeAddress.setPanelStatus(bool) } 
                            hideSearchAd={ () => hrmOfficeAddress.setPanelStatus(false) }
                            searchsAd= {isPanelShow ? this.getPanelComponents() : <div></div>}
                            advanceHeight={ Math.ceil(conditionNum / 2) * 52 + 20}
                            hasMask={false}
                            buttonsAd={this.getTabBtn()}
                            onSearch={() => hrmOfficeAddress.getTableInfo()}
                            onSearchChange={ val => this.onSearchChange(val)}
                        />
                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@pgmg3x`} 
                            comsWeaTableStore={tableStore}
                            hasOrder={true}
                            needScroll={true}
                            getColumns={c => this.reRenderColumns(c)}
                            onOperatesClick={(record, index, operate) => this.onOperatesClick(record, index, operate)}
                        />
                    </WeaTop>
                </WeaRightMenu>
                <NewAndEditDialog ecId={`${this && this.props && this.props.ecId || ''}_NewAndEditDialog@q4rrwm`} 
                    title={nEdialogTitle}
                    visible={visible}
                    condition={toJS(condition)}
                    form={form}
                    isFormInit={form.isFormInit}
                    loading={dialogLoading}
                    isEdit={isEdit}
                    height={650}
                    conditionLen={3}
                    domkey={'locationcity'}
                    save={() => this.handleSave()}
                    handleLinkage={(id) => this.handleLinkage(id)}
                    onCancel={() => hrmOfficeAddress.setVisible(false)}
                />
                {importDialog.visible && <Import ecId={`${this && this.props && this.props.ecId || ''}_Import@pbs64f`} />}
            </div>
        )
    }
}