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.setState({ questionNos: this.props.questionNos });
  }

  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.splice(oldIndex, 1);
    if (newIndex === questionNos.length) {
      questionNos.push(tmp[0]);
    } else {
      questionNos.splice(newIndex, 0, tmp[0]);
    }
    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={[<a href={`/subject/question/${item.question.id}`} target='_blank'><Icon type='small-dash' /></a>, <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.Paragraph ellipsis={{ rows: 2, expandable: true }} disabled >{item.question ? item.question.description : ''}</Typography.Paragraph>}
          />
        </List.Item>;
      }} />;
  }
}