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,
    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';



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


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

    componentWillMount() {
    }

    componentDidMount() {
        this.init();
    }

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

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

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

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

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

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

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

        sequence.setNeDialogTitle(i18n.label.newSequence());
        sequence.setIsNew(true);
        sequence.setVisible(true);
        sequence.getForm();
    }

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

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

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


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

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

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

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

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

        return btn;
    }

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

        sequence.setSequenceName(val);
        !this.isEmptyObject(form2.getFormParams()) && sequence.updateFields(val);
    }

    changeData(key) {
        const {
            sequence
        } = this.props;
        sequence.changeData(key);
    }

    reRenderColumns(columns) {
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'forbidden_tag') {
                c.render = function(text, record) {
                    return <Switch checked={record.forbidden_tag == "0" ? true : false} onChange={checked => _this.updateForbiddenTag(checked,record.id)} />
                }
            };
        })
    }

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

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

    updateForbiddenTag(checked,id) {
        const {
            sequence
        } = this.props;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: (checked == true) ? i18n.confirm.enableTag() : i18n.confirm.forbiddenTag(),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                sequence.updateForbiddenTag(checked, id);
            },
            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 {
            sequence
        } = this.props;
        
        sequence.setNeDialogTitle(i18n.label.editSequence());
        sequence.setSequenceId(id);
        sequence.setIsNew(false);
        sequence.setVisible(true);
        sequence.getForm();
    }

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


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

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

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

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

    }

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



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

    render() {

        const {
            sequence,importDialog
        } = this.props;
        const {
            isPanelShow, form2, levelName, conditionNum, tableStore,nEdialogTitle,visible,condition,
            form,dialogLoading,isEdit,selectedKey,topTab,topTabCount,date,hasRight
        } = sequence;
        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.sequenceName()}
                        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`}
                            datas={topTab}
                            counts={topTabCount}
                            keyParam="viewCondition" //主键
                            countParam="groupId" //数量
                            selectedKey={selectedKey}
                            onChange={this.changeData.bind(this)}
                            searchType={['base', 'advanced']}
                            showSearchAd={isPanelShow}
                            searchsBaseValue={this.isEmptyObject(form2.getFormParams()) ? levelName : form2.getFormParams().levelName}
                            setShowSearchAd={bool => sequence.setPanelStatus(bool)}
                            hideSearchAd={() => sequence.setPanelStatus(false)}
                            searchsAd= {isPanelShow ? this.getPanelComponents() : <div></div>}
                            advanceHeight={Math.ceil(conditionNum / 2) * 52 + 20}
                            hasMask={false}
                            buttonsAd={this.getTabBtn()}
                            onSearch={() => sequence.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={250}
                    conditionLen={1}
                    save={() => this.handleSave()}
                    onCancel={() => sequence.setVisible(false)}
                />
                {importVisible && <ImportDialog ecId={`${this && this.props && this.props.ecId || ''}_ImportDialog@633i8k`} />}
            </div>
        )
    }
}