import React from 'react'
import { Transfer, Button, Icon } from 'antd';


class Demo extends React.Component {
  state = {
    mockData: [
      {
          "key": "0",
          "title": "content1",
          "description": "description of content1",
          "chosen": false,
      },
      {
          "key": "1",
          "title": "content2",
          "description": "description of content2",
          "chosen": true
      },
      {
          "key": "2",
          "title": "content3",
          "description": "description of content3",
          "chosen": true
      },
      {
          "key": "3",
          "title": "content4",
          "description": "description of content4",
          "chosen": false
      },
      {
          "key": "4",
          "title": "content5",
          "description": "description of content5",
          "chosen": false
      }
  ],
    targetKeys: [],
  }
  swapItems = (arr, index1, index2) => {
    let arrClone = JSON.parse(JSON.stringify(arr))    //这里要使用一个深拷贝才能真正地改变state
    let temp = arrClone[index1]
    arrClone[index1] = arrClone[index2]
    arrClone[index2] = temp
    console.log("changedArrClone", arrClone)
    this.setState({
      targetKeys: arrClone
    }, () => {console.log(`${this.state.targetKeys}`)}
    );
  }
    

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

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

  renderRow = (item) => {
    let index = this.state.targetKeys.indexOf(item.key);
    if (index === -1) {
      return <span>{item.title}</span>
    }
    else {
      return (
      <span> {item.title} <Icon type="arrow-up" onClick={() => {
        this.upSwap(index)
      }}/> <Icon type="arrow-down" onClick={() => {
        this.downSwap(index)
      }}/></span>
      );
    }
  }

  handleChange = (targetKeys) => {
    this.setState({ targetKeys });
  }

  renderFooter = () => {
    return (
      <Button
        size="small"
        style={{ float: 'right', margin: 5 }}
        onClick={this.getMock}
      >
        reload
      </Button>
    );
  }

  render() {
    return (
      <Transfer
        dataSource={this.state.mockData}
        showSearch
        listStyle={{
          width: 250,
          height: 300,
        }}
        operations={['to right', 'to left']}
        targetKeys={this.state.targetKeys}
        onChange={this.handleChange}
        render={this.renderRow}
        footer={this.renderFooter}
      />
    );
  }
}

export default Demo