import { useRef, useState, useMemo } from "react";
import { Table, Button, Space, Popconfirm, Flex, message, Tag, Tooltip, notification } from "antd";
import { PlayCircleOutlined, EditOutlined, NotificationOutlined, DeleteOutlined, ReloadOutlined } from "@ant-design/icons";
import { useQuery, useMutation } from "@tanstack/react-query";
import { GetAudioEncode, DeleteAudioEncode, GetAudioEncodeCode } from "../api/audio";
import { CreateAudioTask } from "../api/task";
import type { AudioEncodeItem } from "../types/audioencode";
import type { AddTaskItem } from "../types/audiotask";
import type { ColumnsType } from "antd/es/table";
import AddAudioEncode, { AddAudioEncodeRef } from "./AddAudioEncode";
import PlayerModal, { PlayerModalRef } from "./PlayerModal";
import ChannelModel, { IChannelModelFunc } from "./channel/Channel";
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 AudioEncodePage() {
  const { ErrorHandle } = useGlobal();
  const dialogRef = useRef<AddAudioEncodeRef>(null);
  const playerModalRef = useRef<PlayerModalRef>(null);
  const channelRef = useRef<IChannelModelFunc>(null);
  const [pagination, setPagination] = useState({
    page: 1,
    size: 10,
    name: ""
  });

  // 获取任务列表
  const {
    data: storageResponse,
    isLoading,
    refetch,
  } = useQuery({
    queryKey: ["storage", pagination],
    queryFn: () =>
      GetAudioEncode({ ...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: DeleteAudioEncode,
    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 [codeLoadings, setCodeLoadings] = useState<number[]>([]);
  const { mutate: codeMutation } = useMutation({
    mutationFn: GetAudioEncodeCode,
    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: createTaskMutate, isPending: creating } = useMutation({
    mutationFn: CreateAudioTask,
    onSuccess: (v, ctx) => {
      if (v.data.data == 'ok') {
        message.success("下发任务成功");
      } else {
        notification.error({
          message: '下发任务失败,可以重新下发!',
          description:
            JSON.stringify(v.data.data),
        });
      }

    },
    onError: ErrorHandle,
    retry: 0,
  });

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

  // 打开编辑模态框
  const handleEdit = (disk: AudioEncodeItem) => {
    dialogRef.current?.open(disk);
  };
  const handleNotification = (disk: AudioEncodeItem) => {
    channelRef.current?.openModal(disk.id, disk.name)
  }
  const handlePlay = (disk: AudioEncodeItem) => {
    playerModalRef.current?.open(disk);
  };

  // 处理分页变化
  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: AudioEncodeItem[]
    ) => {
      setSelectedRowKeys([...newSelectedRowKeys]);
    },
  };
  // 表格列定义
  const columns: ColumnsType<AudioEncodeItem> = [
    {
      title: "名称",
      dataIndex: "name",
      align: "center",
    },
    {
      title: "文件名称",
      dataIndex: "file_name",
      align: "center",
      render: (text, record) => (
        <Space>
          {text}
        </Space>
      ),
    },
    {
      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: "encode_status",
      align: "center",
      render: (text, record) => (
        <Space>
          {text == 0 && <Tag color="#999">未转码</Tag>}
          {text == 1 && <Tag color="#87d068">转码成功</Tag>}
          {text == 2 && <Tag color="#87d068">转码中</Tag>}
          {text == 3 && <>
            <Tag color="#f50">转码失败</Tag>
            <Tooltip placement="top" title="重新转码" color="#fff">
              <Button
                onClick={() => codeMutation(record.id)}
                loading={codeLoadings.includes(record.id)}
                icon={<ReloadOutlined />}
              />
            </Tooltip>
          </>}
        </Space>
      ),
    },
    {
      title: "描述",
      dataIndex: "des",
      align: "center",
    },
    {
      title: "创建日期",
      dataIndex: "created_at",
      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>
          <Tooltip placement="top" title="广播" color="#fff">
            <Button icon={<NotificationOutlined />} onClick={() => handleNotification(record)} />
          </Tooltip>
          <Tooltip placement="top" title="预览" color="#fff">
            <Button icon={<PlayCircleOutlined />} onClick={() => handlePlay(record)} />
          </Tooltip>
          <Tooltip placement="top" title="编辑" color="#fff">
            <Button icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
          <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>
          <UploadAudio onOk={() => refetch()} />
          {/* <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,
        }}
      />

      {/* 编辑模态框 */}
      <AddAudioEncode
        ref={dialogRef}
        title="编辑"
        onSuccess={() => refetch()}
      />
      {/* 播放模态框 */}
      <PlayerModal
        ref={playerModalRef}
        title="预览"
        onSuccess={() => refetch()}
      />
      {/* 广播模态框 */}
      <ChannelModel ref={channelRef} onCallback={(item: AddTaskItem[]) => {
        createTaskMutate({ items: item })
      }} />
    </div>
  );
}
