import { Form, ConfigProvider, Modal, Tag, message, Select, Button, InputNumber } 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 { ChannelPollingItem, VqdPollingConf, ChannelPollingReq } from "../../types/vqdpolling";
import Filter from "./Filter";
import { GetPollingChannels, CreateVqdPolling, DeleteVqdPollingAll, GetVqdPollingConf, UpdateVqdPollingConf } from "../../api/vqdpolling";
import { GetVqdTaskTemplate } from "../../api/vqdtasktemplate";
import { useGlobal } from "../../Context";

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

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

const ChannelModel: React.FC<IChannelModel> = forwardRef(({ onCallback }, ref) => {
  useImperativeHandle(ref, () => ({
    openModal: () => {
      setOpen(true);
    },
  }));
  const [open, setOpen] = useState(false);
  const pid = useRef<string>(undefined);
  const templateId = useRef<number>(1);
  const { ErrorHandle } = useGlobal();

  const columns: ColumnsType<ChannelPollingItem> = [
    {
      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 <Tag color={text ? "green" : "red"}>{text ? "在线" : "离线"}</Tag>
      },
    },
    {
      title: "接入方式",
      align: "center",
      dataIndex: "protocol",
      render: (text: string) => text || "-",
    },
  ];

  const [paginationTemplate, setTemplatePagination] = useState({
    page: 1,
    size: 999,
    name: ""
  });
  // 获取轮询列表
  const { refetch } = useQuery({
    queryKey: ["config"],
    queryFn: () =>
      GetVqdPollingConf()
        .then((res) => {
          const formValues = {
            polling_num: res.data.polling_num,
            polling_time: res.data.polling_time,
            polling_template: res.data.polling_template,
          };
          templateId.current = res.data.polling_template
          form.setFieldsValue(formValues);
        })
        .catch((err) => {
          ErrorHandle(err);
          throw err;
        }),
    retry: 2,
  });
  // 获取模板列表
  const {
    data: storageResponse,
  } = useQuery({
    queryKey: ["storage", paginationTemplate],
    queryFn: () =>
      GetVqdTaskTemplate({ ...pagination })
        .then((res) => res.data)
        .catch((err) => {
          ErrorHandle(err);
          throw err;
        }),
    // refetchInterval: 4000,
    retry: 1,
  });
  // 获取通道列表
  const [pagination, setPagination] = useState<ChannelPollingReq>({
    page: 1,
    size: 10, // 通道一般 < 10 个，客户端不做分页，一次性全查
    device_id: "",
    pid: "ROOT",
    status: "true",
    name: "",
    bid: "",
  });

  const { data, isLoading } = useQuery({
    queryKey: ["channels", pagination, pid.current],
    queryFn: () =>
      GetPollingChannels({ ...pagination })
        .then((res) => {
          let list: string[] = []
          res.data.items.forEach(element => {
            if (element.is_polling) {
              list.push(element.id)
            }
          });
          setSelectedRowKeys(list)
          return res.data
        })
        .catch((err) => {
          ErrorHandle(err);
        }),
    retry: 2,
    enabled: open,
  });
  const { mutate: updateConfMutate, isPending: updating } = useMutation({
    mutationFn: UpdateVqdPollingConf,
    onSuccess: () => {
      message.success("更新成功");
    },
    onError: ErrorHandle,
  });

  const { mutate: createMutate, } = useMutation({
    mutationFn: CreateVqdPolling,
    onSuccess: () => {
      message.success("添加任务成功");
      onCallback()
    },
    onError: ErrorHandle,
  });
  const { mutate: delMutate, } = useMutation({
    mutationFn: DeleteVqdPollingAll,
    onSuccess: () => {
      message.success("取消任务成功");
      onCallback()
    },
    onError: ErrorHandle,
  });
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<ChannelPollingItem[]>([]);
  const rowSelection = {
    selectedRowKeys,
    // getCheckboxProps: (record: ChannelPollingItem) => ({
    //   disabled: !!record.is_dir,
    // }),
    onChange: (
      newSelectedRowKeys: React.Key[],
      selectedRows: ChannelPollingItem[]
    ) => {
      setSelectedRowKeys(newSelectedRowKeys);
      setSelectedRows(selectedRows);
    },
    onSelect: (
      record: ChannelPollingItem,
      selected: boolean,
    ) => {
      if (selected) {
        createMutate({
          items: [{
            name: record.device_name,
            channel_id: record.id,
            channel_name: record.name,
            task_template_id: templateId.current,
          }]
        })
      } else {
        delMutate([record.id])
      }
    },
    onSelectAll: (
      selected: boolean,
      selectedRows: ChannelPollingItem[],
      changeRows: ChannelPollingItem[],
    ) => {

      if (selected) {
        let list = changeRows.map(item => {
          return {
            name: item.device_name,
            channel_id: item.id,
            channel_name: item.name,
            task_template_id: templateId.current,
          }
        })
        createMutate({ items: list })
      } else {
        let ids = changeRows.map(item => {
          return item.id
        })
        delMutate(ids)
      }
    }
  };

  const onCancel = () => {
    setOpen(false);
    setSelectedRows([]);
    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-between">
            <Form
              layout="inline"
              form={form}
              initialValues={{ layout: 'inline' }}
              style={{ maxWidth: 'none' }}
              onFinish={(values) => {
                if (updating) return
                const {
                  polling_num,
                  polling_time,
                  polling_template,
                } = values as {
                  polling_num: number;
                  polling_time: number;
                  polling_template: number;
                };
                const payload: VqdPollingConf = {
                  polling_num,
                  polling_time,
                  polling_template,
                };
                updateConfMutate({ ...payload });
              }}
            >
              <Form.Item name="polling_num" label="并发" >
                <InputNumber min={1} defaultValue={10} />
              </Form.Item>
              <Form.Item name="polling_time" label="时长" >
                <InputNumber min={30} defaultValue={60} />
              </Form.Item>
              <Form.Item name="polling_template" label="模板" >
                <Select
                  placeholder="请选择模板"
                  onChange={(res, item: any) => {
                    form.setFieldsValue({ polling_template: item?.id });
                  }}
                  options={storageResponse?.items
                    .map((item) => ({
                      label: item.name,
                      value: item.id,
                    }))
                    .filter((item) => item.value !== 0)}
                ></Select>
              </Form.Item>
              <Form.Item>
                <Button type="primary" onClick={()=>{
                  form.submit()
                }}>修改</Button>
              </Form.Item>
            </Form>

            <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;
