import React, { useState, useEffect } from "react";
import { Input, Select, Modal, Form, message, Tooltip } from "antd";
import { Condition_Type, Judge_Rule1, Judge_Rule2 } from "../entity";
import _ from "lodash";
import { systemListApi } from "@/pages/admin/Privilege/api";
import usePagination from "@/hooks/usePagination";
import { getAllRoleCodeApi } from "@/common/api";
import useInitial from "@/hooks/useInitail";
import { saveApproveCondition } from "../api";

const { Option } = Select;
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
interface Props {
  item: PreSetting.Item;
  setItem: any;
  approvalConfigId: number;
  setListLoading: any;
}

export default function CreateItem({
 item,
 setItem,
  approvalConfigId,
  setListLoading,
}: Props) {
  const [form] = Form.useForm();
  const {visible, id, currentItem} = item;
  const [conditionType, setConditionType] = useState<number>();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible&& id) {
        currentItem?.type&& setConditionType(currentItem.type);
       form.setFieldsValue({ ...currentItem });
    }
  }, [visible]);

  const onFinish = () => {
    form
      .validateFields()
      .then((fileds) => {
        const pa = {
          ...fileds,
          id: id || undefined,
          approvalConfigId,
        };
        setLoading(true);
        saveApproveCondition(pa)
          .then((res) => {
            message.success("保存成功");
            setItem({visible: false});
            setListLoading(true);
          })
          .catch((err) => message.error(err.message))
          .finally(() => {
            setLoading(false);
          });
      })
      .catch((err) => message.error(err.message));
  };
  return (
    <Modal
      title={`${id?'编辑':'新增'}预设条件`}
      visible={visible}
      onCancel={() => setItem({ visible: false })}
      onOk={() => form.submit()}
      confirmLoading={loading}
      afterClose={() => form.resetFields()}
    >
      <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
        <Form.Item
          name="name"
          label="条件名称"
          rules={[{ required: true, message: "请输入预设条件名称" }]}
        >
          <Input placeholder="请输入" maxLength={8} />
        </Form.Item>
        <Form.Item
          name="paramName"
          label="参数名称"
          rules={[{ required: true, message: "请输入参数名称" }]}
        >
          <Input placeholder="请输入" maxLength={16} />
        </Form.Item>
        <Form.Item
          name="type"
          label="条件类型"
          rules={[{ required: true, message: "请选择条件类型" }]}
        >
          <Select
            placeholder="请选择"
            onChange={(value) => {
              setConditionType(value);
              // 条件类型改变，清空单位和判断规则
              form.setFields([{ name: "unit", value: undefined, errors: undefined },
            { name: "judgeRule", value: undefined, errors: undefined }
          ]);
            }}
          >
            {Condition_Type.map((item) => (
              <Option value={item.value} key={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
        >
          {({ getFieldValue }) => ([1, 2].includes(getFieldValue("type")) ? (
            <Form.Item name="unit" label="单位" rules={[{ required: true }]}>
              <Input placeholder="请输入单位" maxLength={4} />
            </Form.Item>
            ) : null)}
        </Form.Item>
        {conditionType && (
          <Form.Item
            name="judgeRule"
            label="判断规则"
            rules={[{ required: true, message: "请选择判断规则" }]}
          >
            <Select placeholder="请选择">
              {[1, 2].includes(conditionType)
                ? Judge_Rule1.map((item) => (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                  ))
                : Judge_Rule2.map((item) => (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                  ))}
            </Select>
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
}
