import React from 'react'
import * as mobx from 'mobx'
import {
    inject,
    observer
} from 'mobx-react'
import {
    WeaTop,
    WeaTab,
    WeaFormItem,
    WeaRightMenu,
    WeaLeftRightLayout,
    WeaOrgTree,
    WeaLocaleProvider
} from 'ecCom'
import {
    Row,
    Col,
    Spin,
    Modal,
    Button,
    message,
    Switch
} from 'antd'
import {
    WeaSwitch,
    WeaTableNew
} from 'comsMobx'
import {
    i18n
} from '../../public/i18n';

import '../../style/common.less';

import NewAndEditDialog from '../NewAndEditDialog';
import ImportDialog from '../ImportDialog';
import { renderNoright } from '../../util';
import SelectTag from '../SelectTag'

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

@inject('staff')
@inject('importDialog')
@observer
export default class Staff extends React.Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
    }

    componentDidMount() {
        this.init();
    }

    componentWillReceiveProps(nextProps) {
        const {
            staff
        } = this.props;

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

    init() {
        const {
            staff
        } = this.props;
        staff.getTableInfo();
        staff.getHasRight();
    }

    getTopMenuBtns() {
        const {
            staff
        } = this.props;
        const {
            topMenu,
            tableStore
        } = staff;

        let btns = [];
        topMenu.map((item, i) => {
            if (item.menuFun !== 'batchDelete') {
                btns.push(<Button type='primary' onClick={() => this.handleClick(item)}>{item.menuName}</Button>);
            } else {
                btns.push(<Button type='primary' onClick={() => this.handleClick(item)} disabled={tableStore.selectedRowKeys.length > 0 ? false : true} >{item.menuName}</Button>);
            }

        });

        return btns;
    }

    handleClick(item) {
        const {
            staff
        } = this.props;
        const {
            isPanelShow
        } = staff;

        isPanelShow && staff.setPanelStatus(false);
        this[item.menuFun] && this[item.menuFun]();
    }

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

        staff.setNeDialogTitle(i18n.label.newStaff());
        staff.setIsNew(true);
        staff.setVisible(true);
        staff.getForm();
    }

    import() {
        const {
            importDialog
        } = this.props;
        importDialog.importVisible=true;
        importDialog.importModule='staff';
        importDialog.current = 0;
        importDialog.getImportForm();
    }


    exportStaff() {
        const {
            staff
        } = this.props;
        staff.exportData();
    }


    log = () => {
        window.setLogViewProp({
            logMoudleType: 13,
            keys: new Date().getTime(),
        });
    }

    batchDelete() {
        const {
            staff
        } = this.props;
        const {
            tableStore
        } = staff;

        let keys = toJS(tableStore.selectedRowKeysAllPages).toString();
        staff.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 {
            staff
        } = this.props;
        staff.delete();
    }


    getDropMenuDatas() {
        const {
            staff
        } = this.props;
        const {
            rightMenu
        } = staff;

        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 {
            staff
        } = this.props;
        const {
            isPanelShow
        } = staff;

        isPanelShow && staff.setPanelStatus(false);
        this[key] && this[key]();
    }

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

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bx87i8`} type="primary" onClick={() => {
                staff.getTableInfo(); staff.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={() => staff.setPanelStatus(false)}>{i18n.button.cancel()}</Button>),
        ];

        return btn;
    }

    onSearchChange(val) {
        const {
            staff
        } = this.props;
        const {
            form2
        } = staff;
        staff.setStaffName(val);
    }

    reRenderColumns(columns) {
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'lack_status') {
                c.render = function (text, record) {
                    let value = text == "1" ? "#ff9000" : (text == 2 ? "#66cc66" : "#ff0033")
                    return <SelectTag bagColor={value} text={record.lack_statusspan} />
                }
            };
            if (c.dataIndex == 'staff_desc') {
                c.render = function (text, record) {
                    return <span>{`${getLabel(547345,'编制数')}: ${record.staff_num} / ${getLabel(547346,'在编数')}:  ${record.permanent_num} / ${getLabel(547347,'冻结数')}: ${record.freeze_num}/ ${getLabel(547240,'状态')} :${record.lack_statusspan}`}</span>
                }
            };
        })
    }

    getTree = () => {
        const {
            staff
        } = this.props;
        const {
            companysId,
        } = staff

        let tree = (
            <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@dhi1ro`}
                ref='WeaOrgTree'
                dataUrl={"/api/bs/hrmorganization/job/getSearchTree"}
                loading
                needSearch
                noCache={true}
                needDropMenu={false}
                //onSelect={this.selectVirtual}  //组织维度回调函数
                isLoadSubDepartment={true}
                topPrefix={'hrmSearch'}
                companysId={companysId}
                inputLeftDom={`<b>${i18n.label.organization()}</b>`}
                treeNodeClick={this.treeNodeClick}
                expandAllChildrenOnSearch={true}
                renderNode={item => this.renderNode(item)}
            />
        )
        return tree;
    }

    renderNode(item) {
        return <div className='text-elli' title={item.name}>
            <i className={item.icon} style={{ marginRight: '5px' }}></i>
            {item.name}
            {item.canceled && <span style={{ color: 'red' }}>({i18n.label.forbidden()})</span>}
        </div>
    }

    treeNodeClick = (event, ids, nodeids, nodes) => {
        const {
            staff
        } = this.props;
        const {
            form2,
            companysId
        } = staff;
        const type = event.node.props.type || '0';
        const id = event.node.props.id || '';
        let params = {};
        form2.resetConditionValue();
        if (type == '0') {
            params['virtualtype'] = companysId;
        }
        if (type == '1') {
            params['compId'] = id;
        }
        if (type == '2') {
            params['deptId'] = id;
        }
        staff.doSearch(params);
    }

    replaceLeft() {
        const {
            staff
        } = this.props;
        const {
            leftCondition,
            form1,
        } = staff;
        let formParams = form1.getFormParams();
        const {
            isFormInit
        } = form1;
        let arr = [];
        isFormInit && leftCondition.map(c => {
            c.items.map((field, index) => {
                arr.push(
                    <div style={{ marginLeft: 20,marginTop:7 }}>
                        <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={form1} formParams={formParams} onChange={this.onChange} />}
                        </WeaFormItem>
                    </div>
                )
            })
        })
        return arr;
    }

    onChange = data => {
       const {
        staff
    } = this.props;
        staff.setPlanId(data.planId.value)
    };


    onOperatesClick(record, rowIndex, operate) {
        const {
            index
        } = operate;
        (index == '0') && this.doEdit(record.randomFieldId);
        (index == '1') && this.doDel(record.randomFieldId);
        (index == '2') && this.doChange(record.randomFieldId);
    }

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

        staff.setNeDialogTitle(i18n.label.editStaff());
        staff.setStaffId(id);
        staff.setOperateType("1");
        staff.setIsNew(false);
        staff.setVisible(true);
        staff.getForm();
    }

    doChange(id) {
        const {
            staff
        } = this.props;

        staff.setNeDialogTitle(i18n.label.changeStaff());
        staff.setStaffId(id);
        staff.setOperateType("2");
        staff.setIsNew(false);
        staff.setVisible(true);
        staff.getForm();
    }


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

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


    doDel(id) {
        const {
            staff
        } = this.props;
        staff.setIds(id);
        this.showConfirm('del');
    }


    handleSave() {
        const {
            staff
        } = this.props;
        const {
            isNew
        } = staff;

        isNew && staff.save();
        !isNew && staff.edit();
    }

    getPanelComponents() {
        const {
            staff
        } = this.props;
        const {
            searchCondition,
            form2,
            searchConditionLoading
        } = staff;

        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") {
                    staff.getTableInfo();
                    staff.setPanelStatus(false)
                }
            }}>{arr}</Row>
        }

    }

    //非空判断
    isEmptyObject(obj) {
        for (let key in obj) {
            return false;
        }
        return true;
    }




    render() {

        const {
            staff,importDialog
        } = this.props;
        const {
            isPanelShow, form2, staffName, conditionNum, tableStore, nEdialogTitle, visible, condition,
            form, dialogLoading, isEdit, date, hasRight,exSpinning
        } = staff;
        const {importVisible} = importDialog;

        if (hasRight === false) {
            return renderNoright();
        }

        return (
            hasRight && <div ref='page' style={{ height: '100%' }}>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@k6oc4u`}
                    datas={this.getDropMenuDatas()}
                    onClick={key => this.handleMenuClick(key)}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@bj98s7`}
                        title={i18n.label.staffName()}
                        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@7muhhb`} isNew={true} showLeft={true} leftCom={this.getTree()}>

                            <WeaTab  ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@9c3zts`}
                                searchType={['base', 'advanced']}
                                showSearchAd={isPanelShow}
                                searchsBaseValue={this.isEmptyObject(form2.getFormParams()) ? staffName : form2.getFormParams().staffName}
                                setShowSearchAd={bool => staff.setPanelStatus(bool)}
                                hideSearchAd={() => staff.setPanelStatus(false)}
                                searchsAd={isPanelShow ? this.getPanelComponents() : <div></div>}
                                advanceHeight={Math.ceil(conditionNum / 2) * 52 + 20}
                                hasMask={false}
                                buttonsAd={this.getTabBtn()}
                                onSearch={() => staff.getTableInfo()}
                                onSearchChange={val => this.onSearchChange(val)}
                                replaceLeft={this.replaceLeft()}
                            />
                             <Spin size="large" spinning={exSpinning} tip={getLabel(547647,'正在导出请稍候....')} className="hrm-loading-center-small"/>
                            <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)}
                            />
                        </WeaLeftRightLayout>
                    </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={350}
                    conditionLen={2}
                    save={() => this.handleSave()}
                    onCancel={() => staff.setVisible(false)}
                    moduleName={"staff"}
                    bindChangeEnvent={val => staff.updateConditions(val)}
                />
                {importVisible && <ImportDialog ecId={`${this && this.props && this.props.ecId || ''}_ImportDialog@633i8k`} />}
            </div>
        )
    }
}