import { Alert, ConfigProvider, Modal, Tag, message } from "antd";
import Table, { ColumnsType } from "antd/es/table";
import React, {
  forwardRef,
  useImperativeHandle,
  useRef,
  useState,
  useEffect,
} from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { ChannelItem, ChannelReq } from "../../types/device";
import Filter from "./Filter";
import { GetChannels } from "../../api/devices";
import { useGlobal } from "../../Context";

export interface IChannelModelFunc {
  openModal: (id: string) => void;
}

interface IChannelModel {
  ref: any;
  onCallback: (id: any, name:any) => void;
}

const ChannelModel: React.FC<IChannelModel> = forwardRef(({onCallback},ref) => {
  useImperativeHandle(ref, () => ({
    openModal: (id: string) => {
      setOpen(true);
      if (id != "") {
        setSelectedRowKeys([id])
      }
      pid.current = id;
    },
  }));
  const [open, setOpen] = useState(false);
  const pid = useRef<string>(undefined);
  const { ErrorHandle } = useGlobal();

  const columns: ColumnsType<ChannelItem> = [
    {
      title: "ID",
      align: "center",
      dataIndex: "id",
    },
    {
      title: "设备名称",
      align: "center",
      dataIndex: "device_name",
      ellipsis: true,
      render: (text: string) => text || "-",
    },
    {
      title: "通道名称",
      align: "center",
      dataIndex: "name",
      ellipsis: true,
      render: (text: string) => text || "-",
    },
    {
      title: "状态",
      dataIndex: "status",
      align: "center",
      render: (text: any, record) => {
        return record.is_dir ? (
          "-"
        ) : (
          <Tag color={text ? "green" : "red"}>{text ? "在线" : "离线"}</Tag>
        );
      },
    },
    {
      title: "接入方式",
      align: "center",
      dataIndex: "protocol",
      render: (text: string) => text || "-",
    },
  ];

  // 获取通道列表
  const [pagination, setPagination] = useState<ChannelReq>({
    page: 1,
    size: 10, // 通道一般 < 10 个，客户端不做分页，一次性全查
    device_id: "",
    pid: "ROOT",
    status: "",
    name: "",
    bid: "",
  });

  const { data, isLoading } = useQuery({
    queryKey: ["channels", pagination, pid.current],
    queryFn: () =>
      GetChannels({ ...pagination })
        .then((res) => res.data)
        .catch((err) => {
          ErrorHandle(err);
        }),
    retry: 2,
    enabled: open,
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<ChannelItem[]>([]);
  const rowSelection = {
    selectedRowKeys,
    getCheckboxProps: (record: ChannelItem) => ({
      disabled: !!record.is_dir,
    }),
    onChange: (
      newSelectedRowKeys: React.Key[],
      selectedRows: ChannelItem[]
    ) => {
      if (newSelectedRowKeys.length > 0) {
        setSelectedRowKeys([newSelectedRowKeys[newSelectedRowKeys.length - 1]]);
        setSelectedRows([selectedRows[selectedRows.length - 1]]);
      }
    },
  };

  const onCancel = () => {
    setOpen(false);
    if (selectedRowKeys.length>0) {
      onCallback(selectedRows[0].id, selectedRows[0].name||selectedRows[0].id)
    }
    setSelectedRowKeys([])
  };

  const modalStyles = {
    content: {
      padding: "20px 24px 12px 24px",
    },
  };

  return (
    <ConfigProvider
      theme={{
        components: {
          Table: {
            cellPaddingBlock: 14,
            cellPaddingBlockMD: 4,
            cellPaddingBlockSM: 2,
          },
        },
      }}
      modal={{ styles: modalStyles }}
    >
      <Modal
        open={open}
        title="绑定通道"
        style={{ top: "5%" }}
        width={"1000px"}
        onCancel={onCancel}
        onOk={onCancel}
      >
        <div>
          <div className="mb-2  flex justify-end">
            <Filter
              searchLoading={isLoading}
              stateValue={pagination.status}
              onSearchChange={(value: string) => {
                setPagination({ ...pagination, name: value, bid: value });
              }}
              onSelectChange={(value: string) => {
                setPagination({ ...pagination, status: value });
              }}
            />
          </div>
          <Table
            loading={isLoading}
            rowKey={"id"}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={data?.items}
            className="min-h-32 overflow-y-auto hidden-transverse-scroll"
            scroll={{ x: "max-content" }}
            pagination={{
              total: data?.total,
              current: pagination.page,
              pageSize: pagination.size,
              onChange: (page, size) =>
                setPagination({ ...pagination, page, size }),
              showTotal: (total) => `共 ${total} 条`,
              showSizeChanger: true,
              pageSizeOptions: [5, 10, 20, 30],
            }}
          />
        </div>
      </Modal>
    </ConfigProvider>
  );
});

export default ChannelModel;
