import React, { useEffect, useState } from "react";
import { Drawer, Form, Input, Switch, Space, Button, message } from "antd";
import { useModel, useRequest } from "umi";
import { GetLink, SaveSingleLink } from "@/api/link";
import { GetAllWorkflowVariable, GetFormattedResult } from "@/api/node";
import SelectModal from "@/components/SelectModal";
import { SysVars, TypeMap } from "@/constants";
import ColumnModal from "@/components/ColumnModal";
import LangInput from "@/components/LangInput";

export default function LineModal() {
  const [open, setOpen] = React.useState(false);
  const { graph, mode } = useModel("flowModel");
  const [form] = Form.useForm();
  const [nodeData, setNodeData] = useState<any>(null);
  const [formattedResult, setFormattedResult] = React.useState("");

  const { run, loading } = useRequest(GetLink, {
    manual: true,
    onSuccess: (res) => {
      setNodeData(res?.result || {});
    },
  });

  useEffect(() => {
    graph?.on("edge:dblclick", (args) => {
      const data = args.cell.getData();
      run({ id: data.id });
      setOpen(true);
    });
  }, [graph]);

  const handleClose = () => {
    setFormattedResult("");
    setNodeData(null);
    setOpen(false);
  };

  const handleSubmit = () => {
    const values = form.getFieldsValue();
    SaveSingleLink({
      ...nodeData,
      ...values,
      langMemo: undefined
    }).then(() => {
      message.success("保存成功");
      handleClose();
    });
  };

  // 查看格式化结果
  const handleViewFormatResult = () => {
    const values = form.getFieldsValue();
    if (!values?.conditionValue) {
      message.warning("请先输入准入条件");
      return;
    }
    GetFormattedResult({
      data: values?.conditionValue,
    }).then((res) => {
      setFormattedResult(res?.result.data);
    });
  };

  return (
    <Drawer
      title="节点属性"
      width={440}
      open={open}
      loading={loading}
      onClose={handleClose}
      styles={{
        body: {
          paddingTop: 0,
        },
      }}
      footer={<div className="flex justify-end">
        <Button key="cancel" onClick={handleClose} className="mr-12px">
          取消
        </Button>
        <Button key="submit" type="primary" onClick={handleSubmit} disabled={mode === 'ops'}>
          保存
        </Button>
      </div>}
      destroyOnHidden
    >
      <Form
        form={form}
        initialValues={{
          langMemo: nodeData?.langMemo,
          useCondition: nodeData?.useCondition,
          conditionValue: nodeData?.conditionValue,
        }}
        disabled={mode === "ops"}
      >
        <Form.Item label="连线名称" name="langMemo"> 
          <LangInput />
        </Form.Item>
        <Form.Item label="是否启用" name="useCondition">
          <Switch />
        </Form.Item>
        <Form.Item label="" shouldUpdate>
          {({ getFieldValue, setFieldValue }) => {
            const enabled = getFieldValue("useCondition");
            const addVariable = (val: string) => {
              const text = getFieldValue("conditionValue");
              setFieldValue("conditionValue", `${text}${val}`);
            };
            return (
              <>
                <Form.Item label="" name="conditionValue">
                  <Input.TextArea
                    disabled={!enabled}
                    rows={5}
                    placeholder="准入条件..."
                  />
                </Form.Item>
                <Space className="w-full mb-12px" align="end" content="end">
                  <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 disabled={!enabled}>+变量</Button>}
                  />
                  <ColumnModal
                    trigger={<Button disabled={!enabled}>+字段</Button>}
                    onChange={(list) => {
                      if (list.length) {
                        const data = list[0];
                        addVariable(
                          `<%${data.schemaName}.${data.c_SchemaName}%>`
                        );
                      }
                    }}
                  />
                  <Button
                    disabled={!enabled}
                    type="primary"
                    onClick={handleViewFormatResult}
                  >
                    查看
                  </Button>
                </Space>
              </>
            );
          }}
        </Form.Item>
        <div className="text-gray-500">
          {formattedResult && <>格式化结果: {formattedResult}</>}
        </div>
        <div className="mt-12px">
          注意:
          <br />
          <p>1. 这里是SQL中WHERE的写法，支持MS SQL中的内置函数</p>
          <p>2. 如果是比较日期，请注意是否要比较时分秒，否则需要做日期转换</p>
          <p>3. 如果连线准入条件不满足，则此分支中断</p>
        </div>
      </Form>
    </Drawer>
  );
}
