import { forwardRef, useImperativeHandle, useState, useRef } from "react";
import { Modal, Form, Input, Select, Button, message, Space, Switch } from "antd";
import { useMutation, useQuery } from "@tanstack/react-query";
import { CreateVqdTask, UpdateVqdTask } from "../api/vqdtask";
import { GetVqdTaskTemplate } from "../api/vqdtasktemplate";
import { GetVqdTimeTemplate } from "../api/vqdtimetemplate";
import type { CreateVqdTaskReq, VqdTaskItem } from "../types/vqdtask";
import { useGlobal } from "../Context";
import ChannelModel, { IChannelModelFunc } from "./channel/Channel";

interface AddVqdTaskProps {
  title: string;
  onSuccess: () => void;
}

export interface AddVqdTaskRef {
  open: (task?: VqdTaskItem) => void;
}

const AddVqdTask = forwardRef<AddVqdTaskRef, AddVqdTaskProps>(
  ({ title, onSuccess }, ref) => {
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<boolean>(false);
    const [channelId, setChannelId] = useState<string>("");
    const channelRef = useRef<IChannelModelFunc>(null);
    const [form] = Form.useForm();
    const { ErrorHandle } = useGlobal();
    useImperativeHandle(ref, () => ({
      open: (task?: VqdTaskItem) => {
        if (task) {
          setEditing(true);
          setChannelId(task.channel_id)
          const formValues = {
            name: task.name,
            id: task.id,
            channel_id: task.channel_id,
            channel_name: task.channel_name,
            task_template_id: task.task_template_id,
            task_template_name: task.task_template_name,
            enable: task.enable,
          };
          form.setFieldsValue(formValues);
        } else {
          setEditing(false);
          form.resetFields();
          form.setFieldsValue({
            enable: true,
          });
        }
        setOpen(true);
      },
    }));
    const [pagination, setPagination] = useState({
      page: 1,
      size: 999,
      name: ""
    });

    // 获取模板列表
    const {
      data: storageResponse,
    } = useQuery({
      queryKey: ["storage", pagination],
      queryFn: () =>
        GetVqdTaskTemplate({ ...pagination })
          .then((res) => res.data)
          .catch((err) => {
            ErrorHandle(err);
            throw err;
          }),
      // refetchInterval: 4000,
      retry: 1,
    });
    // 获取计划列表
    const {
      data: storageTimeResponse,
    } = useQuery({
      queryKey: ["storages", pagination],
      queryFn: () =>
        GetVqdTimeTemplate({ ...pagination })
          .then((res) => res.data)
          .catch((err) => {
            ErrorHandle(err);
            throw err;
          }),
      // refetchInterval: 4000,
      retry: 1,
    });
    const { mutate: createMutate, isPending: creating } = useMutation({
      mutationFn: CreateVqdTask,
      onSuccess: () => {
        message.success("创建任务成功");
        handleClose();
        onSuccess?.();
      },
      onError: ErrorHandle,
    });

    const { mutate: updateMutate, isPending: updating } = useMutation({
      mutationFn: UpdateVqdTask,
      onSuccess: () => {
        message.success("更新任务成功");
        handleClose();
        onSuccess?.();
      },
      onError: ErrorHandle,
    });

    const handleClose = () => {
      setOpen(false);
      setEditing(false);
      setChannelId("");
      form.resetFields();
    };

    return (
      <Modal
        // style={{ top: '-180px' }} // 距离顶部 80px（可改为 10% 等百分比）
        title={title}
        destroyOnHidden={true}
        open={open}
        onCancel={handleClose}
        centered
        onOk={() => form.submit()}
        confirmLoading={creating || updating}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={(values) => {
            if (creating || updating) return
            console.log(values);

            const {
              name,
              des,
              channel_id,
              channel_name,
              task_template_id,
              time_template_id,
              enable } = values as {
                name: string;
                des: string;
                id?: number;
                channel_id: string;
                channel_name: string;
                task_template_id: number;
                time_template_id: number;
                enable: boolean;
              };
            const payload: CreateVqdTaskReq = {
              name,
              des,
              channel_id,
              channel_name,
              task_template_id,
              time_template_id,
              enable,
            };

            if (editing) {
              const id = (values as any).id;
              updateMutate({ id: String(id), ...payload });
            } else {
              createMutate(payload);
            }
          }}
        >


          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: "请输入名称" }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item
            name="channel_id"
            label="关联通道"
            rules={[{ required: true, message: "请选择通道" }]}
          >
            <Space.Compact style={{ width: '100%' }}>
              <Input defaultValue="请输入通道" disabled value={channelId} />

              <Button type="primary" onClick={() => {
                channelRef.current?.openModal(channelId)
              }}>选择通道</Button>
            </Space.Compact>
          </Form.Item>
          <Form.Item name="task_template_id" label="关联模板" rules={[{ required: true, message: "请选择模板" }]}>
            <Select
              placeholder="请选择模板"
              onChange={(res, item: any) => {
                form.setFieldsValue({ task_template_name: item?.label });
              }}
              options={storageResponse?.items
                .map((item) => ({
                  label: item.name,
                  value: item.id,
                }))
                .filter((item) => item.value !== 0)}
            ></Select>

          </Form.Item>
          <Form.Item name="time_template_id" label="关联计划" rules={[{ required: true, message: "请选择计划" }]}>
            <Select
              placeholder="请选择计划"
              onChange={(res, item: any) => {
                form.setFieldsValue({ task_template_name: item?.label });
              }}
              options={storageTimeResponse?.items
                .map((item) => ({
                  label: item.name,
                  value: item.id,
                }))
                .filter((item) => item.value !== 0)}
            ></Select>

          </Form.Item>

          <Form.Item
            name="des"
            label="描述"
          >
            <Input placeholder="请输入描述" />
          </Form.Item>
          <Form.Item
            style={{ width: '20%' }}
            name="enable"
            label="启用"
          >
            <Switch />
          </Form.Item>
          {editing && (
            <Form.Item name="id" hidden>
              <Input />
            </Form.Item>
          )}
          <Form.Item name="channel_name" hidden>
            <Input />
          </Form.Item>
        </Form>
        <ChannelModel ref={channelRef} onCallback={(id: any, name: any) => {
          form.setFieldsValue({ channel_id: id, channel_name: name });
          setChannelId(id)
        }} />
      </Modal>
    );
  }
);

export default AddVqdTask;
