import React from 'react';
import {observer} from 'mobx-react';
import {toJS} from 'mobx';

import {Button} from 'antd';
import {getSearchBtns, getAdvancedItem} from '../../../util/IntegrationUtil';
import {WeaRightMenu, WeaTab, WeaTop} from 'ecCom';
import { WeaTableNew, WeaLogView} from 'comsMobx';

const {WeaTable} = WeaTableNew;
const WeaLogViewComp = WeaLogView.Component;

@observer
export default class List extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}

        const {listStore} = this.props;

        listStore.setState({
            apiUrl: this.props.apiUrl,
            colums: this.props.colums,
            logShow: this.props.log && this.props.log.show,
            logId: this.props.log && this.props.log.targetId
        });
    }

    componentDidMount() {
        const {listStore} = this.props;

        listStore.doInit();
    }

    componentWillReceiveProps(nextProps) {
        const {listStore} = this.props;
        
        listStore.setState({
            apiUrl: nextProps.apiUrl,
            colums: nextProps.colums,
            logShow:nextProps.log && nextProps.log.show,
            logId:  nextProps.log && nextProps.log.targetId
        });

        if (this.props.key !== nextProps.key) {
            listStore.getDatas(true);
        }

        if("synclog" == nextProps.synclog){
            listStore.doInit();
        }
    }

    /**
     * 获取按钮
     * @returns {*[]}
     */
    getBtns() {
        const {listStore} = this.props;
        const {buttoninfo, rowSelectIds} = toJS(listStore.status);

        let btnArr = [];
        buttoninfo && buttoninfo.map(b => {
            btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j81to1@integrationldapListComponentButton${b.type}`} type={b.btnType} disabled={ (b.type==='BTN_BatchDelete' || b.type==='BTN_DESIGN_DEPARTMENT') && rowSelectIds.length === 0} onClick={() => this.onRightMenuClick(b.type)}>
                    {b.btnName}
                </Button>
            );
        });
        return btnArr;
    }

    /**
     * 获取右键菜单
     * @returns {*[]}
     */

    getRightMenu() {

        const {listStore} = this.props;

        const {menuinfo, rowSelectIds } = toJS(listStore.status);
        let btnArr = [];
        menuinfo && menuinfo.map(m => {
			let disable = false;
			if (m.type === "BTN_BatchDelete") {
				disable = rowSelectIds.length === 0;
            }
            if(m.type === 'BTN_DESIGN_DEPARTMENT') {
              disable = rowSelectIds.length === 0;  
            }
            btnArr.push({
                key: m.type,
                icon: <i className={m.menuIcon}/>,
                content: m.menuName,
				disabled: disable,
                onClick: () => this.onRightMenuClick(m.type)
            });
        });
        return btnArr;
    }

    /**
     * 获取查询条件
     * @returns {Array}
     */
    getSearchs = () => {
        const {listStore} = this.props;
        const {status, searchForm} = listStore;
        const {conditioninfo} = toJS(status);
        return getAdvancedItem(searchForm, conditioninfo, this.handleSearchFun, false, this && this.props && this.props.ecId || '', "integrationLdapListComponent",)
    }

    handleSearchFun = () => {
        const {listStore} = this.props;
        listStore.getDatas(true);
        listStore.setShowSearchAd(false);  
    }

    /**
     * 高级搜索按钮
     * @returns {*[]}
     */
    getTabButtonsAd() {
        const {listStore} = this.props;
        return getSearchBtns(
            this.handleSearchFun,
            () => listStore.searchForm.reset(),
            () => listStore.setShowSearchAd(false), 
            this && this.props && this.props.ecId || '', 
            "integrationLdapListComponent",
        )
    }

    /**
     * 右键菜单操作作
     * @param type
     */
    onRightMenuClick = (type) => {
        const {listStore} = this.props;

        if (type == 'BTN_COLUMN') {//显示列定制
            listStore.tableStore.setColSetVisible(true);
            listStore.tableStore.tableColSet(true);
        } else {
            this.props.onMenuClick && typeof(this.props.onMenuClick) == "function" &&  this.props.onMenuClick(type);
        }
    }

    /**
     * 行操作区
     * @param record
     * @param index
     * @param operate
     * @param flag
     */
    onOperatesClick = (record, index, operate, flag) => {
        this.props.onRowClick && typeof(this.props.onRowClick) == "function" && this.props.onRowClick(record, index, operate, flag);
    }

    /**
     * 列操作
     * @param record
     * @param type
     */
    onColumClick = (record, type) => {
        this.props.onColumClick && typeof(this.props.onColumClick) == "function" && this.props.onColumClick(record, type);
    }

    getColumns = (columns) => {
        const {listStore} = this.props;
        let newColumns = '';
        newColumns = columns.map(column => {
            let newColumn = column;
            newColumn.render = (text, record, index) => { //前端元素转义

                let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];

                let column = listStore.status.colums.find((c) => c.key && c.key == newColumn.dataIndex);

                return (
                    column && column.type ?
                        <a onClick={() => this.onColumClick(record, column.type)}
                           dangerouslySetInnerHTML={{__html: valueSpan}}/>
                        :
                        <div dangerouslySetInnerHTML={{__html: valueSpan}}/>
                )
            };
            return newColumn;
        });
        return newColumns;
    }

    getRowSelection = () => {
        return {
            onChange: selectedRowKeys => {
                this.props.listStore.setState({
                    rowSelectIds: selectedRowKeys
                })
            }      
        }
    }

    onLogDialogClose = () => {
        this.props.listStore.setState({
            logShow: false,
            logId: ''
        });
        this.props.onLogClose && typeof(this.props.onLogClose) == "function" && this.props.onLogClose();
    }

    render() {
        const {listStore} = this.props;
        const {tableStore, status, searchForm} = listStore;
        const {showSearchAd, collectinfo, topinfo, logType, logSmallType,logShow,logId, apiUrl, rightLoading} = toJS(status);

        return (<div>
          {!rightLoading && <div>
            <WeaRightMenu
                ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@integrationldapListComponent`}
                datas={this.getRightMenu()}
                collectParams={collectinfo}
            >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@integrationldapListComponent`}
                    title={topinfo.title}
                    icon={<i className={topinfo.icon}/>}
                    iconBgcolor={topinfo.iconColor}
                    buttons={this.getBtns()}
                    buttonSpace={10}
                    showDropIcon={true}
                    dropMenuDatas={this.getRightMenu()}
                    dropMenuProps={{collectParams: collectinfo}}
                >
                    <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@integrationldapListComponent`}
                        {...topinfo.tab}
                        showSearchAd={showSearchAd}
                        searchsAd={this.getSearchs()}
                        buttonsAd={this.getTabButtonsAd()}
                        searchsBaseValue={
                            apiUrl.indexOf('custominterface')>0 ? searchForm.getFormParams().formartname
                            :
                            apiUrl.indexOf('useraccount')>0 ? searchForm.getFormParams().lastname
                            :
                            searchForm.getFormParams().ldapname
                        }
                        setShowSearchAd={() => {
                            listStore.setShowSearchAd(!showSearchAd);
                        }}
                        hideSearchAd={() => {
                            listStore.setShowSearchAd(false);
                        }}
                        onSearchChange={value => {
                            // searchForm.resetForm();
                            if(apiUrl.indexOf('custominterface')>0){
                                searchForm.updateFields({formartname: value});
                            }else if(apiUrl.indexOf('useraccount')>0){
                                searchForm.updateFields({lastname: value});
                            }else{
                                searchForm.updateFields({ldapname: value});
                            }
                        }}
                        onSearch={() => {
                            listStore.getDatas(true);
                        }}
						onChange={tabKey => {
                                var that = this;
                                setTimeout(function(){
                                    topinfo.tab.selectedKey = tabKey;
                                    searchForm.resetForm();
                                    listStore.setState({
                                      topinfo: topinfo,
                                      rowSelectIds: []
                                    });
                                    that.props.onTabListChange && typeof(that.props.onTabListChange) == "function"
                                    && that.props.onTabListChange(tabKey);
                                    listStore.doInit()
                                    
                                }, 300)
								
                        }}
                    />
                    <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@integrationldapListComponent`}
                        comsWeaTableStore={tableStore}
                        hasOrder={true}
                        needScroll={true}
                        loading={true}
						rowSelection={this.getRowSelection()}
                        onOperatesClick={this.onOperatesClick}
                        getColumns={this.getColumns}
                    />
                </WeaTop>


                <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@integrationldapListComponent`}
                    visible={logShow}
                    onCancel={this.onLogDialogClose}
                    logStore={listStore.logStore}
                    logType={logType}
                    logSmallType={logSmallType}
                    targetId={logId}
                />
            </WeaRightMenu>
          </div>}
        </div>);
    }
}
