import React, { Component } from 'react';
import { Icon, List, Avatar, Typography } from 'antd';
import './index.less';
import DragList from '@src/components/DragList';

export default class QuestionNoList extends Component {
  constructor(props) {
    super(props);
    this.state = { loading: 0 };
    // this.searchQuestion(this.props.ids, 'ids');
    this.setState({ questionNos: this.props.questionNos });
  }

  // componentWillReceiveProps(nextProps) {
  //   if (this.props.ids !== nextProps.ids) {
  //     this.searchQuestion(nextProps.ids, 'ids');
  //   } else if (this.props.nos !== nextProps.nos) {
  //     this.searchQuestion(nextProps.nos, 'nos');
  //   }
  // }

  componentWillReceiveProps(nextProps) {
    const { loading } = this.state;
    this.setState({ questionNos: nextProps.questionNos, loading: loading + 1 });
  }

  deleteQuestion(index) {
    const { questionNos, loading } = this.state;
    questionNos.splice(index, 1);
    this.setState({ questionNos, loading: loading + 1 });
    this.props.onChange(questionNos);
  }

  orderQuestion(oldIndex, newIndex) {
    const { questionNos, loading } = this.state;
    const tmp = questionNos[oldIndex];
    questionNos[oldIndex] = questionNos[newIndex];
    questionNos[newIndex] = tmp;
    this.setState({ questionNos, loading: loading + 1 });
    this.props.onChange(questionNos);
  }

  // searchQuestion(values, field = 'nos') {
  //   // console.log('search', values, field);
  //   if (!values || values.length === 0) {
  //     this.setState({ questionNos: [] });
  //     return;
  //   }
  //   // 查找练习题目
  //   Question.listNo({ [field]: values, module: this.props.module }).then(result => {
  //     const { loading } = this.state;
  //     const map = getMap(result, 'no');
  //     const questionNos = values.map(no => map[no]).filter(row => row);
  //     this.setState({ questionNos, loading: loading + 1 });
  //     this.props.onChange(questionNos);
  //   });
  // }

  render() {
    return <DragList
      key={this.state.loading}
      loading={!!this.props.loading}
      dataSource={this.state.questionNos || []}
      handle={'.icon'}
      onMove={(oldIndex, newIndex) => {
        this.orderQuestion(oldIndex, newIndex);
      }}
      type={this.props.type}
      renderItem={(item, index) => {
        if (this.props.render) {
          return this.props.render(item, 'icon', () => {
            this.deleteQuestion(index);
          });
        }
        return <List.Item actions={[<Icon type='delete' onClick={() => {
          this.deleteQuestion(index);
        }} />, <Icon type='bars' className='icon' />]}>
          <List.Item.Meta
            avatar={<Avatar alt={index + 1} size='small' >{index + 1}</Avatar>}
            title={item.title}
            description={<Typography.Text ellipsis disabled>{item.description}</Typography.Text>}
          />
        </List.Item>;
      }} />;
  }
}