import React from "react";
import { Switch, Input, Button, Form, Space, message } from "antd";
import {
  EditEntryCondition,
  EditEntryEnable,
  GetAllWorkflowVariable,
  GetFormattedResult,
} from "@/api/node";
import { useConfigStore } from "..";
import SelectModal from "@/components/SelectModal";
import { SysVars, TypeMap } from "@/constants";
import ColumnModal from "@/components/ColumnModal";
import { useModel } from "umi";

export default function Admission() {
  const nodeData = useConfigStore((state) => state?.nodeData);
  const [form] = Form.useForm();
  const [formattedResult, setFormattedResult] = React.useState("");
  const updateState = useConfigStore((state) => state.updateState);
  const { mode } = useModel("flowModel");

  // 设置是否启用
  const handleEnabled = async (checked: boolean) => {
    await EditEntryEnable({
      ...nodeData,
      isEntryEnable: checked,
    });
    message.success("保存成功");
    updateState({
      nodeData: {
        ...nodeData,
        isEntryEnable: checked,
      },
    });
  };

  // 设置变量值
  const setEntryCondition = async (val: string) => {
    if (val === nodeData?.entryCondition) return;
    const res = await EditEntryCondition({
      ...nodeData,
      entryCondition: val,
    });
    console.log(res);
    message.success("保存成功");
    updateState({
      nodeData: {
        ...nodeData,
        entryCondition: val,
      },
    });
  };

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

  return (
    <>
      <Form
        form={form}
        initialValues={{
          isEntryEnable: nodeData?.isEntryEnable,
          entryCondition: nodeData?.entryCondition,
        }}
        disabled={mode === "ops"}
      >
        <Form.Item label="是否启用" name="isEntryEnable">
          <Switch onChange={handleEnabled}/>
        </Form.Item>
        <Form.Item label="" shouldUpdate>
          {({ getFieldValue, setFieldValue }) => {
            const enabled = getFieldValue("isEntryEnable");
            const addVariable = (val: string) => {
              const text = getFieldValue("entryCondition");
              setFieldValue("entryCondition", `${text}${val}`);
              setEntryCondition(`${text}${val}`);
            };
            return (
              <>
                <Form.Item label="" name="entryCondition">
                  <Input.TextArea
                    disabled={!enabled}
                    rows={5}
                    placeholder="准入条件..."
                    onBlur={(e) => setEntryCondition(e.target.value)}
                  />
                </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>
    </>
  );
}
