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

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

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


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


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

    componentWillMount() {
    }

    componentDidMount() {
        this.init();
    }

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

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

    init() {
        const {
            resourceBasicInfo
        } = this.props;
        resourceBasicInfo.getHasRight();
        resourceBasicInfo.initData();
    }


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

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

        return btns;
    }

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

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

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

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

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

        resourceBasicInfo.setNeDialogTitle(i18n.label.newResourceBasicInfo());
        resourceBasicInfo.setIsNew(true);
        resourceBasicInfo.setOperateType("1");
        resourceBasicInfo.setVisible(true);
        resourceBasicInfo.getForm();
    }

    addItemClass() {
        const {
            resourceBasicInfo
        } = this.props;
        resourceBasicInfo.setNeDialogTitle(i18n.label.newResourceBasicType());
        resourceBasicInfo.setIsNew(true);
        resourceBasicInfo.setVisible(true);
        resourceBasicInfo.setOperateType("2")
        resourceBasicInfo.getTypeForm();
    }

    editItemClass() {
        const {
            resourceBasicInfo
        } = this.props;
        resourceBasicInfo.setNeDialogTitle(i18n.label.editResourceBasicType());
        resourceBasicInfo.setIsNew(false);
        resourceBasicInfo.setVisible(true);
        resourceBasicInfo.setOperateType("4")
        resourceBasicInfo.getTypeForm();
    }

    delItemClass() {
        const {
            resourceBasicInfo
        } = this.props;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: "确认删除该类型吗！",
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                resourceBasicInfo.deleteType();
            },
            onCancel() {
                return false;
            },
        });
    }



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

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


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

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

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

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

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

        return btn;
    }

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

        resourceBasicInfo.setFName(val);
        !this.isEmptyObject(form2.getFormParams()) && resourceBasicInfo.updateFields(val);
    }


    reRenderColumns(columns) {
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'fdelete') {
                c.render = function (text, record) {
                    return record.fdelete == '0' ? <Tag color="green" >正常</Tag> : <Tag color="red">停用</Tag>
                }
            };
        })
    }

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


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

        resourceBasicInfo.setNeDialogTitle(i18n.label.editResourceBasicInfo());
        resourceBasicInfo.setFId(id);
        resourceBasicInfo.setIsNew(false);
        resourceBasicInfo.setOperateType("3")
        resourceBasicInfo.setVisible(true);
        resourceBasicInfo.getForm();
    }

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

    doRecover(id) {
        const {
            resourceBasicInfo
        } = this.props;
        this.showRecoverConfirm(id);
    }

    showRecoverConfirm(id) {
        const {
            resourceBasicInfo
        } = this.props;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: i18n.confirm.recoverConfirm(),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                resourceBasicInfo.recover(id);
            },
            onCancel() {
                return false;
            },
        });
    }




    handleSave() {
        const {
            resourceBasicInfo
        } = this.props;
        const {
            isNew,
            operateType
        } = resourceBasicInfo;

        switch(operateType){
            case "1":
                resourceBasicInfo.save();
            break;
            case "2":
                resourceBasicInfo.saveType();
            break;
            case "3":
                resourceBasicInfo.edit();
            break;
            case "4":
                resourceBasicInfo.editType();
            break;
        }
    }

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

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

    }

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


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


    render() {

        const {
            resourceBasicInfo
        } = this.props;
        const {
            isPanelShow, form2, fname, conditionNum, tableStore, nEdialogTitle, visible, condition,
            form, dialogLoading, isEdit, date, hasRight, treeConfig, treeLoading,operateType
        } = resourceBasicInfo;

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

        const {
            data,
            onSelectedTreeNode,
            selectedKeys,
            onExpand,
            treeExpandKeys
        } = toJS(treeConfig);
        const treeCom = (
            <WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@ifgbi1`}
                datas={data}
                searchLabel={"类型"}
                onSelect={onSelectedTreeNode}
                selectedKeys={selectedKeys}
                onExpand={onExpand}
                loading={treeLoading}
                expandedKeys={treeExpandKeys} />
        )

        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.resourceBasicInfo()}
                        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@q6b87k`} leftCom={treeCom}>
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@9c3zts`}
                                searchType={['base', 'advanced']}
                                showSearchAd={isPanelShow}
                                searchsBaseValue={this.isEmptyObject(form2.getFormParams()) ? fname : form2.getFormParams().fname}
                                setShowSearchAd={bool => resourceBasicInfo.setPanelStatus(bool)}
                                hideSearchAd={() => resourceBasicInfo.setPanelStatus(false)}
                                searchsAd={isPanelShow ? this.getPanelComponents() : <div></div>}
                                advanceHeight={Math.ceil(conditionNum / 2) * 52 + 20}
                                hasMask={false}
                                buttonsAd={this.getTabBtn()}
                                onSearch={() => resourceBasicInfo.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)}
                            />
                        </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={operateType == 2 ? 180 : 230}
                    conditionLen={1}
                    save={() => this.handleSave()}
                    onCancel={() => resourceBasicInfo.setVisible(false)}
                />
            </div>
        )
    }
}