import React from "react";
import { Select, Input, Button, Form, message } from "antd";
import { useConfigStore } from "..";
import { EditAutoHandle, GetAllWorkflowVariable } from "@/api/node";
import SelectModal from "@/components/SelectModal";
import { SysVars, TypeMap } from "@/constants";
import { useModel } from "umi";

export default function AutoHandle() {
  const options = [
    { value: 2, label: "Sql" },
    { value: 1, label: "Dll" },
    { value: 3, label: "Intergration" },
  ];

  const nodeData = useConfigStore((state) => state.nodeData);
  const updateState = useConfigStore((state) => state.updateState);
  const { mode } = useModel("flowModel");

  const [form] = Form.useForm();

  const handleEditAutoHandle = async () => {
    const values = form.getFieldsValue();
    await EditAutoHandle({
      ...nodeData,
      ...values,
    });
    message.success("保存成功");
    updateState({
      nodeData: {
        ...nodeData,
        ...values,
      },
    });
  };

  const addVariable = (val: string) => {
    const text = form.getFieldValue("autoCallValue");
    form.setFieldValue("autoCallValue", `${text || ''}${val}`);
    handleEditAutoHandle();
  };

  return (
    <Form
      form={form}
      initialValues={{
        autoCallType: nodeData?.autoCallType,
        autoCallValue: nodeData?.autoCallValue,
      }}
      disabled={mode === "ops"}
    >
      <Form.Item label="处理方式" name="autoCallType">
        <Select
          placeholder="请选择"
          options={options}
          onChange={handleEditAutoHandle}
        />
      </Form.Item>
      <SelectModal
        key={1}
        labelKey="name"
        valueKey="value"
        api={GetAllWorkflowVariable}
        onChange={addVariable}
        onSuccess={(data) => {
          const list = data?.result?.model || [];
          return [...SysVars, ...list].map((item) => ({
            ...item,
            value: `<%${item.name}%>`,
            name: `<%${item.name}%>`,
          }));
        }}
        columns={[
          { title: "变量名称", dataIndex: "name" },
          {
            title: "变量类型",
            dataIndex: "type",
            render: (val) =>
              TypeMap?.[val as unknown as keyof typeof TypeMap] || "",
          },
        ]}
        defaultParams={[
          {
            id: nodeData?.wfdWorkflowId,
          },
        ]}
        value={undefined}
        trigger={
          <Button className="mb-12px" type="primary" size="small">
            +添加
          </Button>
        }
      />
      <Form.Item name="autoCallValue">
        <Input.TextArea
          placeholder="命令文本..."
          rows={5}
          onBlur={handleEditAutoHandle}
        />
      </Form.Item>
    </Form>
  );
}
