import {
  Form,
  Modal,
  Switch,
  Input,
  Space,
  Button,
  message,
  Select,
  Divider,
} from "antd";
import { useState, useContext } from "react";
import SelectModal from "../SelectModal";
import ColumnModal from "../ColumnModal";
import { GetAllWorkflowVariable, GetFormattedResult } from "@/api/node";
import { SysVars, TypeMap, ActorOptions } from "@/constants";

import JobModal from "./JobModal";
import Level2LevelModal from "./Level2LevelModal";
import LevelModal from "./LevelModal";
import NodeModal from "./NodeModal";
import RoleModal from "./RoleModal";
import UserModal from "./UserModal";

export default function SelectProcessorModal({
  trigger,
  nodeData,
}: {
  trigger?: React.ReactNode;
  nodeData?: any;
}) {
  const [open, setOpen] = useState(false);
  const [formattedResult, setFormattedResult] = useState<string>("");
  const [form] = Form.useForm();
  const [comp, setComp] = useState<React.ReactNode>(null);

  const handleOk = () => {
    setOpen(false);
  };

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

  // 切换人员类型
  const handleTypeChange = () => {
    // 清空数据
    form.setFieldsValue({
      dataType: undefined,
      dataValue: undefined,
      dataValueName: undefined,
      baseType: undefined,
      baseValue: undefined,
    });
  };

  // 打开弹窗
  const getModalValue = (
    // 选择类型
    type: "base" | "data"
  ) => {
    return new Promise((resolve, reject) => {
      const values = form.getFieldsValue();
      const handleValueChange = (data: any) => {
        console.log("data", data);
        setComp(null);
        resolve(data);
      };

      const handleClose = () => {
        setComp(null);
        reject();
      };

      // TODO 根据不同类型打开不同弹窗
      setComp(
        <JobModal
          defaultOpen={true}
          onChange={handleValueChange}
          onClose={handleClose}
        />
      );
    });
  };

  // 选择来源类型
  const handleDataTypeChange = async (val: number) => {
    // 清空数据
    form.setFieldsValue({
      dataValue: undefined,
      dataValueName: undefined,
    });
    
    // TODO 打开弹窗选择
    const res = await getModalValue("data");
    console.log("res: ", res);
  };

  // 选择过滤身份
  const handleBaseTypeChange = async (val: number) => {
    // 清空数据
    form.setFieldsValue({
      baseValue: undefined,
    });

    // TODO 打开弹窗选择
    const res = await getModalValue("base");
    console.log("res: ", res);
  };

  return (
    <>
      <span onClick={() => setOpen(true)}>{trigger}</span>
      <Modal
        title="请选择处理人"
        open={open}
        width={800}
        onOk={handleOk}
        onCancel={() => setOpen(false)}
      >
        <Form form={form}>
          <Form.Item label="生效条件" name="activeConditionEnable">
            <Switch />
          </Form.Item>
          <Form.Item label="" shouldUpdate>
            {({ getFieldValue, setFieldValue }) => {
              const enabled = getFieldValue("activeConditionEnable");
              const addVariable = (val: string) => {
                const text = getFieldValue("activeCondition");
                setFieldValue("activeCondition", `${text}${val}`);
              };
              return (
                <>
                  <Form.Item label="" name="activeCondition">
                    <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>
          <Divider />
          <Form.Item label="人员类型" name="type">
            <Select
              placeholder="请选择"
              options={ActorOptions}
              defaultValue={0}
              onChange={handleTypeChange}
            />
          </Form.Item>
          <Form.Item label="" shouldUpdate>
            {({ getFieldsValue, setFieldsValue }) => {
              const values = getFieldsValue();
              console.log(values);
              const typeToDataTypeMap = {
                selectSource: [
                  2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
                  21, 22, 23,
                ],
                dataField: [2, 3, 4, 14, 15, 16, 17, 18, 22, 17, 1],
                variable: [
                  1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 21,
                  22, 23,
                ],
                baseType: [6, 7, 8, 9, 10, 16, 17, 18, 21, 11, 23],
              };

              const dataTypes = [
                {
                  label: "选择来源",
                  value: 0,
                  types: typeToDataTypeMap.selectSource,
                },
                {
                  label: "数据字段",
                  value: 1,
                  types: typeToDataTypeMap.dataField,
                },
                { label: "变量", value: 2, types: typeToDataTypeMap.variable },
              ].filter((item) => item.types.includes(values?.type));

              const baseTypes = typeToDataTypeMap.baseType.includes(
                values?.type
              )
                ? [
                    { label: "按申请人", value: 0 },
                    { label: "按字段", value: 1 },
                    { label: "按变量", value: 2 },
                  ]
                : [];
              // 能否手动输入
              const canEdit =
                [6, 17].includes(values?.type) && values?.dataType === 0;

              return (
                <>
                  <Space>
                    <Form.Item label="来源类型" name="dataType">
                      <Select
                        style={{ width: 120 }}
                        placeholder="请选择"
                        options={dataTypes}
                        disabled={dataTypes.length === 0}
                        onChange={handleDataTypeChange}
                      />
                    </Form.Item>
                    <Form.Item label="来源值" name="dataValue">
                      {/* 6 17 需要手动输入 */}
                      <Input
                        style={{ width: 420 }}
                        disabled={!canEdit}
                        placeholder={canEdit ? "请手动输入" : ""}
                      />
                    </Form.Item>
                    <Form.Item label="" name="dataValueName"></Form.Item>
                  </Space>
                  <Space>
                    <Form.Item label="过滤身份" name="baseType">
                      <Select
                        style={{ width: 120 }}
                        placeholder="请选择"
                        options={baseTypes}
                        disabled={baseTypes.length === 0}
                        onChange={handleBaseTypeChange}
                      />
                    </Form.Item>
                    <Form.Item label="过滤值" name="baseValue">
                      <Input style={{ width: 420 }} disabled />
                    </Form.Item>
                  </Space>
                </>
              );
            }}
          </Form.Item>
        </Form>
      </Modal>
      {comp}
    </>
  );
}
