import React, { useState, useEffect } from 'react';
import { List, Space, Button, Tooltip } from "antd";
import { EditOutlined, DiffOutlined, DeleteOutlined, ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';

import DatasourceItem from './DatasourceItem';

const DatasourceList = (props) => {

  const { loading, data, onEdit, onAddTask, onDelete, idBindTasksNeedRefresh, scope } = props;

  const [ expandedBindId, setExpandedBindId ] = useState({});

  useEffect(() => {
    setExpandedBindId({});

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [scope])

  const onExpanded = (item) => {
    if (expandedBindId.hasOwnProperty(item.id)) {
      expandedBindId[item.id] = !expandedBindId[item.id];
    } else {
      expandedBindId[item.id] = true;
    }

    setExpandedBindId({...expandedBindId});
  }

  return (
    <List
      loading={loading}
      itemLayout="vertical"
      dataSource={ data||[] }
      footer={null}
      renderItem={(item, index) => {

        let title = '', expanded = false;
        (item.targetParameters||[]).forEach(item => {
          if (item.name === 'name') {
            title = item.value||'';
          }
        })

        if (expandedBindId.hasOwnProperty(item.id)) {
          expanded = expandedBindId[item.id];
        }

        return (
          <List.Item key={index}>
            <List.Item.Meta
              title={
                <div className='d-flex' style={{ alignItems: 'center' }}>
                  <div className='textOverflow' style={{ flex: 1 }}>
                    <span title={title}>{title}</span>
                  </div>
                  <Space className='mx-3' style={{ marginLeft: 'auto' }} size='small'>
                    <Tooltip placement='bottom' title={'修改'}>
                      <Button icon={<EditOutlined />} size='small' onClick={() => { onEdit && onEdit(item); }} />
                    </Tooltip>
                    <Tooltip placement='bottom' title={'新增任务'}>
                      <Button icon={<DiffOutlined />} size='small' onClick={() => { onAddTask && onAddTask(item); }} />
                    </Tooltip>
                    <Tooltip placement='bottom' title={'删除'}>
                      <Button icon={<DeleteOutlined />} size='small' onClick={() => { onDelete && onDelete(item); }} />
                    </Tooltip>
                    <Tooltip placement='bottom' title={expanded?'隐藏任务列表':'显示任务列表'}>
                      <Button icon={expanded ? <ArrowUpOutlined /> : <ArrowDownOutlined />} size='small' onClick={() => { onExpanded(item); }} />
                    </Tooltip>
                  </Space>
                </div>
              }
              description={ <DatasourceItem data={item} scope={scope} expanded={expanded} refresh={idBindTasksNeedRefresh===item.id} /> }
            />
          </List.Item>
        );
      }}
    />
  );
}

export default DatasourceList;