import React from 'react'
import * as mobx from 'mobx'
import {
    inject,
    observer
} from 'mobx-react'
import {
    WeaTop,
    WeaTab,
    WeaFormItem,
    WeaRightMenu,
    WeaAlertPage,
    WeaBrowser
} 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 { renderNoright } from '../../util'; // 从util文件引入公共的方法



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


@inject('managerDetach')
@observer
export default class ManagerDetach extends React.Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
    }

    componentDidMount() {
          this.init();
    }

    componentWillUnmount() {
    }


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

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

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

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

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

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

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

        managerDetach.setNeDialogTitle(i18n.label.newManagerDetach());
        managerDetach.setIsNew(true);
        managerDetach.setVisible(true);
        managerDetach.getForm();
    }

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

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


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

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

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

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

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

        return btn;
    }

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

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

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

        managerDetach.setManagerName(val);
        !this.isEmptyObject(form2.getFormParams()) && managerDetach.updateFields(val);
    }

    reRenderColumns(columns) {
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'manager_type') {
                c.render = function (text, record) {
                    return record.manager_type == "0" ? '人员' : '角色'
                }
            };
        })
    }

    doDetachSwitch(checked) {
        const {
            managerDetach
        } = this.props;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: (checked == true) ? `${i18n.message.checkOnDetach()}` : `${i18n.message.checkOffDetach()}`,
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                managerDetach.setDetach(checked);
            },
            onCancel() {
                return false;
            },
        });
        
    }

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

    }

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

        managerDetach.setNeDialogTitle(i18n.label.editManagerDetach());
        managerDetach.setDetachId(id);
        managerDetach.setIsNew(false);
        managerDetach.setVisible(true);
        managerDetach.getForm();
    }

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


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

    


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

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

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

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

    }

    isEmptyObject(obj) {
        for (let key in obj) {
            return false;
        }
        return true;
    }


    render() {

        const {
            managerDetach
        } = this.props;
        const {
            isPanelShow, form2, managerName, conditionNum, tableStore, nEdialogTitle, visible, condition,
            form, dialogLoading, isEdit, date, hasRight,isDetach
        } = managerDetach;

        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)}
                >   
                    <div style={{"width":"100%","height":"50px","lineHeight":"50px"}}>
                        <span style={{"marginLeft":"20px","fontWeight":"bold"}}>{i18n.label.enableDetach()}:</span>
                        <Switch style={{"marginLeft":"20px"}} checked={isDetach == "true" ? true : false} onChange={checked => this.doDetachSwitch(checked)} />
                    </div>
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@bj98s7`}
                        title={i18n.label.mangerDetachName()}
                        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()) ? managerName : form2.getFormParams().ecManager}
                            setShowSearchAd={bool => managerDetach.setPanelStatus(bool)}
                            hideSearchAd={() => managerDetach.setPanelStatus(false)}
                            searchsAd={isPanelShow ? this.getPanelComponents() : <div></div>}
                            advanceHeight={Math.ceil(conditionNum / 2) * 52 + 20}
                            hasMask={false}
                            buttonsAd={this.getTabBtn()}
                            onSearch={() => managerDetach.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={220}
                    conditionLen={1}
                    save={() => this.handleSave()}
                    onCancel={() => managerDetach.setVisible(false)}
                    moduleName='managerDetach'
                    bindChangeEnvent={val => managerDetach.updateConditions(val)}
                />
            </div>
    )
    }
}