import { bannerApi } from "@/api";
import { DageTableActions } from "@dage/pc-components";
import { Button, Image, Table } from "antd";
import { useMemo, useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router-dom";

export default function BannerPage() {
  const navigate = useNavigate();
  const [list, setList] = useState<[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    getList();
  }, []);

  const getList = async () => {
    setLoading(true);
    try {
      const data = await bannerApi.getList();
      setList(data);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = useCallback(async (id: number) => {
    await bannerApi.delete(id);
    getList();
  }, []);

  const COLUMNS = useMemo(() => {
    return [
      {
        title: "海报",
        render: (item: any) => {
          return (
            <Image
              height={100}
              src={`${process.env.REACT_APP_API_URL}${process.env.REACT_APP_IMG_PUBLIC}${item.filePath}`}
            />
          );
        },
      },
      {
        title: "发布日期",
        dataIndex: "publishDate",
      },
      {
        title: "操作",
        render: (item: any) => {
          return (
            <DageTableActions
              onEdit={() => navigate(`/banner/edit/${item.id}`)}
              onDelete={handleDelete.bind(undefined, item.id)}
            />
          );
        },
      },
    ];
  }, [handleDelete, navigate]);

  return (
    <div>
      <div style={{ textAlign: "right" }}>
        <Button
          type="primary"
          disabled={list.length >= 10}
          onClick={() => navigate("/banner/create")}
        >
          新增
        </Button>
      </div>

      <Table
        loading={loading}
        className="page-table"
        dataSource={list}
        columns={COLUMNS}
        rowKey="id"
      />
    </div>
  );
}
