import { useRef, useState, useMemo } from "react";
import { Table, Button, Space, Popconfirm, Flex, message, Tag, Tooltip } from "antd";
import { CloseOutlined, DeleteOutlined, ReloadOutlined } from "@ant-design/icons";
import { useQuery, useMutation } from "@tanstack/react-query";
import { GetAudioTask, DeleteAudioTask, GetAudioTaskCancel, DeleteAudioTaskAll } from "../api/task";
import type { AudioTaskItem } from "../types/audiotask";
import type { ColumnsType } from "antd/es/table";
import UploadAudio from './UploadAudio';
import { useGlobal } from "../Context";
import { FormatFileSizeToString } from "../utils/rate";
import { formatSecondsToHMS } from "../utils/time";
import Filter from "./Filter";

export default function AudioTaskPage() {
  const { ErrorHandle } = useGlobal();

  const [pagination, setPagination] = useState({
    page: 1,
    size: 10,
    name: ""
  });

  // 获取任务列表
  const {
    data: storageResponse,
    isLoading,
    refetch,
  } = useQuery({
    queryKey: ["storage", pagination],
    queryFn: () =>
      GetAudioTask({ ...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: DeleteAudioTask,
    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 { mutate: deleteMutationAll, isPending: delAllLoadings } = useMutation({
    mutationFn: DeleteAudioTaskAll,
    onSuccess: () => {
      message.success("批量删除成功");
      refetch()
      setSelectedRowKeys([])
    },
    onError: ErrorHandle,
    retry: 0,
  });



  // 取消任务
  const [cancelLoadings, setCancelLoadings] = useState<number[]>([]);
  const { mutate: cancelMutation } = useMutation({
    mutationFn: GetAudioTaskCancel,
    onMutate: (id: number) => {
      // setDelLoadings((prev) => [...prev, id]);
    },
    onSuccess: (_, ctx) => {
      message.success("取消成功");
      refetch();
    },
    onError: (error: Error, ctx) => {
      ErrorHandle(error);
    },
  });


  // 处理分页变化
  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: AudioTaskItem[]
    ) => {
      setSelectedRowKeys([...newSelectedRowKeys]);
    },
  };
  // 表格列定义
  const columns: ColumnsType<AudioTaskItem> = [
    {
      title: "任务编码",
      dataIndex: "id",
      align: "center",
    },
    {
      title: "音频名称",
      dataIndex: "audio_name",
      align: "center",
    },
    {
      title: "通道名称",
      dataIndex: "channel_name",
      align: "center",
    },
    {
      title: "通道编码",
      dataIndex: "channel_id",
      align: "center",
    },
    {
      title: "类型",
      dataIndex: "mode",
      align: "center",
      render: (text, record) => (
        <Space>
          {text}
        </Space>
      ),
    },
    {
      title: "大小",
      dataIndex: "size",
      align: "center",
      render: (text, record) => (
        <Space>
          {FormatFileSizeToString(text)}
        </Space>
      ),
    },
    {
      title: "时长",
      dataIndex: "duration",
      align: "center",
      render: (text, record) => (
        <Space>
          {formatSecondsToHMS(text)}
        </Space>
      ),
    },
    {
      title: "状态",
      dataIndex: "task_status",
      align: "center",
      render: (text, record) => (
        <Space>
          {text == 0 && <Tag className="mr-0" color="gold">等待中</Tag>}
          {text == 1 && <Tag className="mr-0" color="green">执行中</Tag>}
          {text == 2 && <Tag className="mr-0" color="#87d068">已完成</Tag>}
          {text == 3 && <Tag className="mr-0" color="#999">已取消</Tag>}
          {text == 4 && <>
            <Tooltip placement="top" title={record.error_msg} color="#fff">
              <Tag className="mr-0" color="red">任务失败</Tag>
            </Tooltip>

          </>}
          {text < 2 && <>
            <Tooltip placement="top" title="取消任务" color="#fff">
              <Button
                shape="circle"
                size="small"
                onClick={() => cancelMutation(record.id)}
                loading={cancelLoadings.includes(record.id)}
                icon={<CloseOutlined />}
              />
            </Tooltip>
          </>}
        </Space>
      ),
    },
    {
      title: "创建日期",
      dataIndex: "created_at",
      align: "center",
      render: (text: string) => (text ? new Date(text).toLocaleString() : "-"),
    },
    // {
    //   title: "开始日期",
    //   dataIndex: "start_time",
    //   align: "center",
    //   render: (text: string) => (text ? new Date(text).toLocaleString() : "-"),
    // },
    // {
    //   title: "结束日期",
    //   dataIndex: "end_time",
    //   align: "center",
    //   render: (text: string) => (text ? new Date(text).toLocaleString() : "-"),
    // },

    // {
    //   title: "日期",
    //   align: "center",
    //   render: (_, record) => (
    //     <>
    //       <div><span>创建: </span>{record.created_at ? new Date(record.created_at).toLocaleString() : "-"}</div>
    //       <div><span>更新: </span>{record.updated_at ? new Date(record.updated_at).toLocaleString() : "-"}</div>
    //     </>
    //   ),
    // },
    {
      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>
          <Popconfirm
            title="确定要批量删除文件吗？"

            onConfirm={() => {        
              deleteMutationAll({ids:selectedRowKeys as number[]})
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button color="danger" variant="solid" loading={delAllLoadings} disabled={selectedRowKeys.length == 0} >
              批量删除
            </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,
        }}
      />


    </div>
  );
}
