import { Form, Input, InputNumber, Modal, Select } from "antd";
import { useEffect, useReducer, useRef, useState } from "react";
import { SENSOR_ATTR_OPTIONS } from "~/enumerate/constant";

function ThresholdModal(props) {
  const [form] = Form.useForm();
  const submitLockRef = useRef(false);
  const [sensorAttr, setSensorAttr] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [detailLoading, dispatchDetailLoading] = useReducer((_, value) => value, false);

  useEffect(() => {
    if (!props.open) {
      return;
    }

    let active = true;
    submitLockRef.current = false;
    setSubmitting(false);
    form.resetFields();
    setSensorAttr("");

    if (!props.currentId) {
      dispatchDetailLoading(false);
      return () => {
        active = false;
      };
    }

    dispatchDetailLoading(true);
    props.sensorDeviceInfo({ id: props.currentId }).then((res) => {
      if (!active || !res?.success) {
        return;
      }

      const data = { ...(res.data || {}) };
      data.sensorTypeName = data.sensorTypeName || props.record.sensorTypeName;
      form.setFieldsValue(data);
      setSensorAttr(data.sensorAttr || "");
    }).finally(() => {
      if (active) {
        dispatchDetailLoading(false);
      }
    });

    return () => {
      active = false;
    };
  }, []);

  const validateHighAlarm = (_, value) => {
    const highHighAlarm = form.getFieldValue("thresholdHighHigh");
    if (value === undefined || value === null || highHighAlarm === undefined || highHighAlarm === null) {
      return Promise.resolve();
    }
    if (Number(value) > Number(highHighAlarm)) {
      return Promise.reject(new Error("高报警阈值默认值不能大于高高报警阈值默认值"));
    }
    return Promise.resolve();
  };

  const validateLowAlarm = (_, value) => {
    const lowLowAlarm = form.getFieldValue("thresholdLowLow");
    if (value === undefined || value === null || lowLowAlarm === undefined || lowLowAlarm === null) {
      return Promise.resolve();
    }
    if (Number(value) < Number(lowLowAlarm)) {
      return Promise.reject(new Error("低报警阈值默认值不能小于低低报警阈值默认值"));
    }
    return Promise.resolve();
  };

  const handleCancel = () => {
    submitLockRef.current = false;
    setSubmitting(false);
    dispatchDetailLoading(false);
    form.resetFields();
    setSensorAttr("");
    props.onCancel();
  };

  const handleSubmit = async (values) => {
    if (submitLockRef.current) {
      return;
    }

    submitLockRef.current = true;
    setSubmitting(true);

    try {
      const res = await props.sensorDeviceEdit({ ...values, id: props.currentId });
      if (res?.success) {
        handleCancel();
        props.getData();
        return;
      }
      submitLockRef.current = false;
      setSubmitting(false);
    }
    catch (error) {
      submitLockRef.current = false;
      setSubmitting(false);
      throw error;
    }
  };

  const isNumberType = sensorAttr === "NUMBER";

  return (
    <Modal
      destroyOnClose
      open={props.open}
      title="阈值设置"
      onCancel={handleCancel}
      onOk={isNumberType ? form.submit : undefined}
      confirmLoading={props.loading || submitting || detailLoading}
      loading={props.loading || detailLoading}
      maskClosable={false}
      width={800}
      footer={isNumberType ? undefined : null}
    >
      <Form form={form} layout="horizontal" onFinish={handleSubmit} labelCol={{ span: 6 }}>
        <Form.Item label="传感器编码" name="sensorCode">
          <Input maxLength={50} placeholder="请输入传感器编码" disabled />
        </Form.Item>
        <Form.Item label="传感器名称" name="sensorName">
          <Input maxLength={50} placeholder="请输入传感器名称" disabled />
        </Form.Item>
        <Form.Item label="传感器类型" name="sensorTypeName">
          <Input maxLength={50} placeholder="请输入传感器类型" disabled />
        </Form.Item>
        <Form.Item label="传感器属性" name="sensorAttr">
          <Select
            options={SENSOR_ATTR_OPTIONS.map(item => ({
              value: item.bianma,
              label: item.name,
            }))}
            disabled
            placeholder="请选择传感器属性"
          />
        </Form.Item>
        <Form.Item noStyle shouldUpdate={(prevValues, nextValues) => prevValues.sensorAttr !== nextValues.sensorAttr}>
          {({ getFieldValue }) => getFieldValue("sensorAttr") === "NUMBER" && (
            <>
              <Form.Item
                preserve={false}
                label="计量单位"
                name="unitName"
                rules={[{ required: true, message: "请输入计量单位" }]}
              >
                <Input maxLength={50} placeholder="请输入计量单位" />
              </Form.Item>
              <Form.Item
                preserve={false}
                label="量程上限默认值"
                name="rangeMax"
                rules={[{ required: true, message: "请输入量程上限默认值" }]}
              >
                <InputNumber min={0} precision={2} style={{ width: "100%" }} placeholder="请输入量程上限默认值" />
              </Form.Item>
              <Form.Item
                preserve={false}
                label="量程下限默认值"
                name="rangeMin"
                rules={[{ required: true, message: "请输入量程下限默认值" }]}
              >
                <InputNumber min={0} precision={2} style={{ width: "100%" }} placeholder="请输入量程下限默认值" />
              </Form.Item>
              <Form.Item preserve={false} label="高高报警阈值默认值" name="thresholdHighHigh">
                <InputNumber min={0} precision={2} style={{ width: "100%" }} placeholder="请输入高高报警阈值默认值" />
              </Form.Item>
              <Form.Item
                preserve={false}
                dependencies={["thresholdHighHigh"]}
                label="高报警阈值默认值"
                name="thresholdHigh"
                rules={[
                  { required: true, message: "请输入高报警阈值默认值" },
                  { validator: validateHighAlarm },
                ]}
              >
                <InputNumber min={0} precision={2} style={{ width: "100%" }} placeholder="请输入高报警阈值默认值" />
              </Form.Item>
              <Form.Item preserve={false} label="低低报警阈值默认值" name="thresholdLowLow">
                <InputNumber min={0} precision={2} style={{ width: "100%" }} placeholder="请输入低低报警阈值默认值" />
              </Form.Item>
              <Form.Item
                preserve={false}
                dependencies={["thresholdLowLow"]}
                label="低报警阈值默认值"
                name="thresholdLow"
                rules={[
                  { required: true, message: "请输入低报警阈值默认值" },
                  { validator: validateLowAlarm },
                ]}
              >
                <InputNumber min={0} precision={2} style={{ width: "100%" }} placeholder="请输入低报警阈值默认值" />
              </Form.Item>
            </>
          )}
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default ThresholdModal;
