import { useRef, useState, useMemo } from "react";
import { Table, Button, Space, Popconfirm, Flex, message, Tooltip, Switch, Popover, Tag } from "antd";
import { EditOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import { useQuery, useMutation } from "@tanstack/react-query";
import { GetVqdPolling, DeleteVqdPolling, UpdateVqdPolling } from "../api/vqdpolling";
import type { VqdPollingItem, CreateVqdPollingReq } from "../types/vqdpolling";
import type { ColumnsType } from "antd/es/table";
import ChannelModel, { IChannelModelFunc } from "./polling/Channel";
import { useGlobal } from "../Context";
import Filter from "./Filter";
export default function VqdPollingPage() {
  const { ErrorHandle } = useGlobal();
  const channelRef = useRef<IChannelModelFunc>(null);
  const [pagination, setPagination] = useState({
    page: 1,
    size: 10,
    name: ""
  });

  // 获取任务列表
  const {
    data: storageResponse,
    isLoading,
    refetch,
  } = useQuery({
    queryKey: ["storage", pagination],
    queryFn: () =>
      GetVqdPolling({ ...pagination })
        .then((res) => res.data)
        .catch((err) => {
          ErrorHandle(err);
          throw err;
        }),
    // refetchInterval: 4000,
    retry: 2,
  });

  // 删除任务
  const [delLoadings, setDelLoadings] = useState<number[]>([]);
  const { mutate: deleteMutation } = useMutation({
    mutationFn: DeleteVqdPolling,
    onMutate: (id: number) => {
      setDelLoadings((prev) => [...prev, id]);
    },
    onSuccess: (_, ctx) => {
      setDelLoadings((prev) => prev.filter((item) => item !== ctx));
      message.success("删除成功");
      refetch();
    },
    onError: (error: Error, ctx) => {
      setDelLoadings((prev) => prev.filter((item) => item !== ctx));
      ErrorHandle(error);
    },
  });

  // 打开新增模态框
  const handleAdd = () => {
      channelRef.current?.openModal()
  };

  // 处理分页变化
  const handleTableChange = (page: number, pageSize?: number) => {
    setPagination((prev) => ({
      ...prev,
      page: page,
      size: pageSize || prev.size,
    }));
  };

  // 客户端分页数据
  const dataSource = useMemo(() => {
    const items = storageResponse?.items || [];
    const start = (pagination.page - 1) * pagination.size;
    const end = start + pagination.size;
    return items.slice(start, end);
  }, [storageResponse, pagination]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const rowSelection = {
    selectedRowKeys,
    onChange: (
      newSelectedRowKeys: React.Key[],
      selectedRows: VqdPollingItem[]
    ) => {
      setSelectedRowKeys([...newSelectedRowKeys]);
    },
  };
  const { mutate: updateMutate } = useMutation({
    mutationFn: UpdateVqdPolling,
    onSuccess: () => {
      message.success("更新成功");
      setTimeout(() => {
        refetch()
      }, 500);
    },
    onError: ErrorHandle,
  });

  // 表格列定义
  const columns: ColumnsType<VqdPollingItem> = [
    {
      title: "ID",
      dataIndex: "id",
      align: "center",
    },
    {
      title: "关联通道",
      dataIndex: "channel_name",
      align: "center",
      render: (text, record) => (
        <Space>
          {`${text}(${record.channel_id})`}
        </Space>
      ),
    },
    // {
    //   title: "诊断参数",
    //   dataIndex: "task_template_id",
    //   align: "center",
    //   render: (text, record) => (
    //     <Space>
    //       {text}
    //     </Space>
    //   ),
    // },

    {
      title: "状态",
      dataIndex: "status",
      align: "center",
      render: (text, record) => (
        <Space>
          {text == 0 && <Tag color="#ccc">等待中</Tag>}
          {text == 1 && <Tag color="#87d068">诊断中</Tag>}
        </Space>
      ),
    },
    {
      title: "操作",
      align: "center",
      width: 120,
      fixed: "right",
      render: (_, record) => (
        <Space>
          <Popconfirm
            title="确定要删除这个任务吗？"
            onConfirm={() => {
              if (record.id) {
                deleteMutation(record.id);
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button
              loading={delLoadings.includes(record.id)}
              danger
              icon={<DeleteOutlined />}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Flex justify="space-between" align="center" className="mb-4">
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加轮询任务
          </Button>
          {/* <Popconfirm
            title="确定要批量删除文件吗？"
            onConfirm={() => {
             
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button color="danger" variant="solid">
              批量删除
            </Button>
          </Popconfirm> */}

        </Space>

        <Filter
          searchLoading={isLoading}
          onSearchChange={(value: string) => {
            setPagination({ ...pagination, name: value });
          }}
        />
      </Flex>
      {/* 表格 */}
      <Table
        columns={columns}
        // rowSelection={rowSelection}
        dataSource={storageResponse?.items}
        rowKey="id"
        loading={isLoading}
        scroll={{ x: "max-content" }}
        pagination={{
          current: pagination.page,
          pageSize: pagination.size,
          total: storageResponse?.total || 0,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: handleTableChange,
          onShowSizeChange: handleTableChange,
        }}
      />

      {/* 模态框 */}
      <ChannelModel ref={channelRef} onCallback={() => {
        refetch()
      }} />
    </div>
  );
}
