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

function SensorTypeModal(props) {
  const [form] = Form.useForm();
  const submitLockRef = useRef(false);
  const [submitting, setSubmitting] = useState(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();
  };

  useEffect(() => {
    if (!props.open) {
      return;
    }
    let active = true;
    submitLockRef.current = false;
    form.resetFields();

    if (!props.currentId) {
      form.setFieldsValue({
        sensorAttr: "NUMBER",
      });
      return () => {
        active = false;
      };
    }
    console.log(props.currentId);
    props["sensorTypeInfo"]({ id: props.currentId }).then((res) => {
      if (!active || !res?.success) {
        return;
      }
      form.setFieldsValue({
        sensorAttr: "NUMBER",
        ...(res.data || {}),
      });
    });
    return () => {
      active = false;
    };
  }, [form, props.currentId, props.open]);

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

  const handleSubmit = async (values) => {
    if (submitLockRef.current) {
      return;
    }
    submitLockRef.current = true;
    setSubmitting(true);
    let res;
    try {
      if (props.currentId) {
        res = await props.sensorTypeEdit({ ...values, id: props.currentId });
      }
      else {
        res = await props.sensorTypeSave(values);
      }
      if (res?.success) {
        message.success("操作成功！");
        handleCancel();
        props.getData();
        return;
      }
      submitLockRef.current = false;
      setSubmitting(false);
    }
    catch (error) {
      submitLockRef.current = false;
      setSubmitting(false);
      throw error;
    }
  };

  return (
    <Modal
      destroyOnClose
      open={props.open}
      title={props.currentId ? "编辑传感器类型" : "新增传感器类型"}
      onCancel={handleCancel}
      onOk={form.submit}
      confirmLoading={props.loading || submitting}
      maskClosable={false}
      width={640}
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        layout="horizontal"
        onFinish={handleSubmit}
        loading={props.loading}
        initialValues={{
          sensorAttr: "NUMBER",
        }}
      >
        {/* <Form.Item */}
        {/*  label="类型编码" */}
        {/*  name="typeCode" */}
        {/*  rules={[{ required: true, message: "请输入类型编码" }]} */}
        {/* > */}
        {/*  <Input maxLength={64} placeholder="请输入类型编码" /> */}
        {/* </Form.Item> */}
        <Form.Item
          label="传感器类型"
          name="typeName"
          rules={[{ required: true, message: "请输入传感器类型" }]}
        >
          <Input maxLength={50} placeholder="请输入传感器类型" />
        </Form.Item>
        <Form.Item
          label="传感器属性"
          name="sensorAttr"
          rules={[{ required: true, message: "请选择传感器属性" }]}
        >
          <Select
            disabled={props.currentId}
            options={SENSOR_ATTR_OPTIONS.map(item => ({
              value: item.bianma,
              label: item.name,
            }))}
            placeholder="请选择传感器属性"
          />
          {/* <Radio.Group disabled={!!props.currentId}> */}
          {/*  {SENSOR_ATTR_OPTIONS.map(item => ( */}
          {/*    <Radio key={item.bianma} value={item.bianma}> */}
          {/*      {item.name} */}
          {/*    </Radio> */}
          {/*  ))} */}
          {/* </Radio.Group> */}
        </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 SensorTypeModal;
