import React, { useEffect, useRef, useState } from "react";
import {
  Button,
  Switch,
  Space,
  Modal,
  message,
  Form,
  Select,
  Input,
} from "antd";
import {
  GetNodeActions,
  EditNodeAction,
  DeleteActionReturnToNodes,
  ActionItemType,
  GetAllWorkflowVariable,
  GetOtherStepNodes,
  EditNodeActions,
  EditActionEnable,
} from "@/api/node";
import { useConfigStore } from "..";
import { useRequest, useModel } from "umi";
import { EventOptions } from "@/constants";
import {
  ModalForm,
  DragSortTable,
  ProColumns,
} from "@ant-design/pro-components";
import LangInput from "@/components/LangInput";
import SelectModal from "@/components/SelectModal";
import { SysVars, TypeMap } from "@/constants";

export default function Action() {
  const nodeData = useConfigStore((state) => state?.nodeData);
  const [dataSource, setDataSource] = useState<ActionItemType[]>([]);
  const otherSetpNodes = useRef<any>();
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const { mode } = useModel("flowModel");

  const { run, loading, refresh } = useRequest(GetNodeActions, {
    manual: true,
    onSuccess: (res) => {
      setDataSource(res?.result || []);
    },
  });

  const { run: runOtherStepNodes } = useRequest(GetOtherStepNodes, {
    manual: true,
    onSuccess: (res) => {
      otherSetpNodes.current = res?.result;
    },
  });

  // 删除
  const deleteAction = async (record: ActionItemType) => {
    Modal.confirm({
      title: "删除",
      content: "确定删除该动作？",
      centered: true,
      onOk: async () => {
        await DeleteActionReturnToNodes(record);
        refresh();
        message.success("删除成功");
      },
    });
  };

  const editRecord = useRef<ActionItemType | null>(null);

  // 编辑
  const handleEdit = (record: ActionItemType) => {
    editRecord.current = record;
    setOpen(true);
    const arr = record.variableValue?.split("=") || [];
    form.setFieldsValue({
      langName: record.langName,
      type: record.type,
      variableName: arr.length > 1 ? arr[0] : undefined,
      variableValue: arr.length > 1 ? arr[1] : undefined,
    });
  };

  const changeEnable = async (record: ActionItemType, val: boolean) => {
    EditActionEnable({
      ...record,
      isEnable: val,
    });
    setDataSource((state) =>
      state.map((item) =>
        item.id === record.id ? { ...item, isEnable: val } : item
      )
    );
  };

  const columns: ProColumns<ActionItemType>[] = [
    {
      title: "排序",
      dataIndex: "sort",
      width: 60,
      hidden: mode === "ops",
      className: "drag-visible",
    },
    {
      title: "按钮",
      dataIndex: "name",
      width: 100,
      render: (val, record) => (
        <Button type="primary" size="small">
          {val}
        </Button>
      ),
    },
    {
      title: "是否启用",
      dataIndex: "isEnable",
      width: 100,
      render: (val, record) => (
        <Switch
          checked={!!val}
          onChange={(val) => changeEnable(record, val)}
          disabled={mode === "ops"}
        />
      ),
    },
    {
      title: "对应事件",
      dataIndex: "type",
      width: 100,
      render: (val) =>
        val ? EventOptions.find((item) => item.value === val)?.label : "-",
    },
    {
      title: "跳转节点",
      dataIndex: "returnToNodes",
    },
    {
      title: "跳转排除",
      dataIndex: "returnToExceptNodes",
    },
    {
      title: "设置变量",
      width: 120,
      dataIndex: "variableValue",
    },
    {
      title: "操作",
      key: "action",
      hidden: mode === "ops",
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" danger onClick={() => deleteAction(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    if (nodeData) {
      run({ id: nodeData?.actionLinkId });
      runOtherStepNodes({
        id: nodeData?.id,
        selectedId: nodeData?.wfdWorkflowId,
      });
    }
  }, [nodeData]);

  // 提交表单
  const handleSubmit = async (values: any) => {
    const val = {
      langNameList: values.langName,
      langName: "",
      type: values.type,
      variableValue: `${values.variableName || ""}${values.variableValue ? `=${values.variableValue}` : ""}`,
    };
    const param = {
      isEnable: true,
      displayOrder: 0,
      actionLinkId: nodeData?.actionLinkId,
      workflowNodes: otherSetpNodes.current,
      returnToNodes: "",
      returnToExceptNodes: "",
    };
    // 判断是编辑还是新增
    await EditNodeAction(
      editRecord.current
        ? {
            ...editRecord.current,
            ...val,
          }
        : {
            ...param,
            ...val,
          }
    );
    message.success("保存成功");
    form.resetFields();
    refresh();
    return true;
  };

  // 拖拽完成
  const handleDragSortEnd = async (
    beforeIndex: number,
    afterIndex: number,
    newDataSource: ActionItemType[]
  ) => {
    console.log("排序后的数据", newDataSource);
    const result = newDataSource.map((item, index) => ({
      ...item,
      displayOrder: index + 1,
    }));
    setDataSource(result);
    await EditNodeActions(result);
    message.success("修改列表排序成功");
  };

  return (
    <div>
      <div className="mb-12px">
        <ModalForm
          title="编辑动作"
          trigger={
            <Button
              type="primary"
              style={{ display: mode === "ops" ? "none" : "block" }}
              onClick={() => (editRecord.current = null)}
            >
              +添加
            </Button>
          }
          autoFocusFirstInput
          width={440}
          open={open}
          onOpenChange={setOpen}
          modalProps={{
            destroyOnHidden: true,
          }}
          onFinish={handleSubmit}
          form={form}
          disabled={mode === "ops"}
        >
          <Form.Item label="按钮名称" name="langName" required>
            <LangInput />
          </Form.Item>
          <Form.Item label="对应事件" name="type" required>
            <Select placeholder="请选择" options={EventOptions} />
          </Form.Item>
          <Form.Item label="变量名称" name="variableName">
            <SelectModal
              key={1}
              labelKey="name"
              valueKey="value"
              api={GetAllWorkflowVariable}
              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,
                },
              ]}
            />
          </Form.Item>
          <Form.Item label="变量值" name="variableValue">
            <Input placeholder="请输入" />
          </Form.Item>
        </ModalForm>
      </div>
      <DragSortTable
        rowKey={"id"}
        dragSortKey="sort"
        size="small"
        loading={loading}
        columns={columns}
        dataSource={dataSource}
        onDragSortEnd={handleDragSortEnd}
        options={false}
        search={false}
        pagination={false}
      />
    </div>
  );
}
