import React from 'react'
import { Modal, Transfer, Icon } from 'antd'

class DisplayColumnBox extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            targetColumns: props.defaultSelectedColumns || []
        }
    }
    swapItems = (arr, index1, index2) => {
        let arrClone = JSON.parse(JSON.stringify(arr));    //这里要使用一个深拷贝才能真正地改变state
        let temp = arrClone[index1];
        arrClone[index1] = arrClone[index2];
        arrClone[index2] = temp;
        this.setState({
            targetColumns: arrClone
        });
    }


    upSwap = (index) => {
        let arr = this.state.targetColumns
        if (index === 0) {
            return;
        }
        this.swapItems(arr, index, index - 1)
    }

    downSwap = (index) => {
        let arr = this.state.targetColumns
        if (index === arr.length - 1) {
            return;
        }
        this.swapItems(arr, index, index + 1);
    };

    renderRow = (item) => {
        let index = this.state.targetColumns.findIndex(c => c.name === item.name);
        return <span data-key={item.name}>
            {item.label}
            {index !== -1 && <span style={{ float: 'right' }}>
                <Icon type="arrow-up" onClick={() => {this.upSwap(index)}} /> 
                <Icon type="arrow-down" onClick={() => {this.downSwap(index)}} />
            </span>}
        </span>
    }

    handleChange = (targetKeys, direction, moveKeys) => {
        const { allColumns } = this.props;
        let targetColumns = allColumns.filter(c => targetKeys.indexOf(c.name) !== -1);
        this.setState({ targetColumns });
    }

    onOk= () => {
        const { hideBox, okHandler } = this.props;
        const { targetColumns } = this.state;
        okHandler(targetColumns);
        hideBox()
    }
    
    onCancel = () => {
        const { hideBox } = this.props
        hideBox();
    }

    render() {
        const { allColumns, visibleDisplayColumnBox } = this.props;
        const { targetColumns } = this.state;

        return (
            <Modal
                visible={visibleDisplayColumnBox}
                onCancel={this.onCancel}
                width={700}
                style={{textAlign:'center'}}
                onOk={this.onOk}
                maskClosable={false}
                destroyOnClose={true}
            >
                <Transfer
                    dataSource={allColumns.map(c => ({ ...c, key: c.name }))}
                    showSearch
                    listStyle={{
                        width: 250,
                        height: 300,
                        textAlign:'left'
                    }}
                    operations={['显示', '隐藏']}
                    targetKeys={targetColumns.map(c => c.name)}
                    onChange={this.handleChange}
                    render={this.renderRow}
                />
            </Modal>
        )
    };
}

export default DisplayColumnBox;