import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Button, List, Popconfirm, Input } from 'antd';
import classNames from 'classnames';
import { getPackageList, deletePackage } from '@/services/package';

export default (props) => {
  const { current, setCurrent } = props;
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [filter, setFilter] = useState({ pageNum: 1, pageSize: 10, total: 0 });
  const [list, setList] = useState([]);
  const listRef = useRef();
  listRef.current = list;

  const onLoadMore = () => {
    setFilter({
      ...filter,
      pageNum: filter.pageNum + 1,
    })
  }

  const loadMore = loading || !hasMore ? null : (
    <div
      style={{
        textAlign: 'center',
        marginTop: 12,
        height: 32,
        lineHeight: '32px',
      }}
    >
      <Button onClick={onLoadMore}>加载更多</Button>
    </div>
  );

  const onSearch = (val) => {
    setFilter({
      ...filter,
      name: val,
      pageNum: 1,
    })
  }

  const onDelete = (item) => {
    setLoading(true);
    deletePackage(item.id).then(res => {
      setLoading(false);

      const newList = listRef.current.filter(x => x.id !== item.id);
      setList(newList);
      if (item.id === current.id) {
        setCurrent(newList[0] || {});
      }
    }).catch(() => {
      setLoading(false);
    });
  };

  useEffect(() => {
    setLoading(true);
    getPackageList(filter).then(res => {
      setLoading(false);

      const { records = [], current, total, pages } = res

      if (current === 1) {
        setList(records)
        setCurrent((records || [])[0] || {})
      } else {
        setList(listRef.current.concat(records))
      }

      setHasMore(current < pages)
    }).catch(() => {
      setLoading(false);
    });
  }, [filter]);

  useEffect(() => {
    if (!current || !current.id) return;

    let found = false;
    let newList = listRef.current.map(x => {
      if (x.id === current.id) {
        found = true;
        return current;
      }

      return x;
    })

    if (!found) {
      newList = newList.concat(current);
    }

    setList(newList);
  }, [current])

  return (
    <List
      style={{ minHeight: '600px' }}
      bordered
      header={
        <Input.Group compact>
          <Input.Search allowClear placeholder="请输入筛选名称" onSearch={onSearch} style={{ width: 'calc(100% - 60px)' }} />
          <Button type='link' onClick={() => setCurrent({})} >新增</Button>
        </Input.Group>
      }
      dataSource={list}
      loading={loading}
      loadMore={loadMore}
      renderItem={item => (
        <List.Item
          className={classNames({ active: current.id === item.id })}
          onClick={() => setCurrent(item)}
          actions={[
            <Popconfirm
              key="delete"
              title="确认删除?"
              onConfirm={() => onDelete(item)}
              >
              <a href="#">删除</a>
            </Popconfirm>
          ]}
        >
          {item.name}
        </List.Item>
      )}
    />
  )
}
