import { DatePicker, Form, Input, Modal, Select } from "antd";
import dayjs from "dayjs";
import { useEffect, useReducer, useRef, useState } from "react";
import { getLabelName } from "zy-react-library/utils";
import { SENSOR_ATTR_OPTIONS, SENSOR_STATUS_OPTIONS, YES_NO_OPTIONS } from "~/enumerate/constant";

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

  useEffect(() => {
    if (!props.open) {
      return;
    }
    let active = true;
    submitLockRef.current = false;
    form.resetFields();
    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 || {}) };
      if (data.factoryDate) {
        data.factoryDate = dayjs(data.factoryDate);
      }
      form.setFieldsValue(data);
    }).finally(() => {
      if (active) {
        dispatchDetailLoading(false);
      }
    });
    return () => {
      active = false;
    };
  }, [form, props.currentId, props.open]);

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

  const handleSubmit = async (values) => {
    if (submitLockRef.current) {
      return;
    }
    submitLockRef.current = true;
    setSubmitting(true);
    values.sensorStatusName = getLabelName({ status: values.sensorStatus, list: SENSOR_STATUS_OPTIONS });
    const payload = {
      ...values,
      factoryDate: values.factoryDate ? values.factoryDate.format("YYYY-MM-DD") : undefined,
    };
    let res;
    try {
      if (props.currentId) {
        res = await props.sensorDeviceEdit({ ...payload, id: props.currentId });
      }
      else {
        res = await props.sensorDeviceSave(payload);
      }
      if (res?.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 || detailLoading}
      loading={!!props.currentId && (props.loading || detailLoading)}
      maskClosable={false}
      width={720}

    >
      <Form
        form={form}
        layout="horizontal"
        onFinish={handleSubmit}
        labelCol={{ span: 6 }}

      >
        <Form.Item
          label="传感器编码"
          name="sensorCode"
          rules={[{ required: true, message: "请输入传感器编码" }]}
        >
          <Input maxLength={50} placeholder="请输入传感器编码" />
        </Form.Item>
        <Form.Item
          label="传感器名称"
          name="sensorName"
          rules={[{ required: true, message: "请输入传感器名称" }]}
        >
          <Input maxLength={50} placeholder="请输入传感器名称" />
        </Form.Item>
        <Form.Item
          label="传感器类型"
          name="sensorTypeId"
          rules={[{ required: true, message: "请选择传感器类型" }]}
        >
          <Select
            allowClear
            showSearch
            optionFilterProp="label"
            disabled={!!props.currentId}
            placeholder="请选择传感器类型"
            options={props.sensorTypeOptions.map(item => ({
              value: item.id,
              label: `${item.typeName}${item.typeCode ? `（${item.typeCode}）` : ""}`,
            }))}
            onChange={(e) => {
              props.sensorTypeOptions.forEach((item) => {
                if (item.id === e) {
                  form.setFieldsValue({ sensorAttr: item.sensorAttr });
                }
              });
            }}
          />
        </Form.Item>
        <Form.Item
          label="传感器属性"
          name="sensorAttr"
        >
          <Select

            options={SENSOR_ATTR_OPTIONS.map(item => ({
              value: item.bianma,
              label: item.name,
            }))}
            placeholder="请选择传感器属性"
            disabled
          />

        </Form.Item>
        <Form.Item
          label="传感器状态"
          name="sensorStatus"
        >
          <Select
            options={SENSOR_STATUS_OPTIONS.map(item => ({
              value: item.bianma,
              label: item.name,
            }))}
            placeholder="请选择传感器状态"

          />

        </Form.Item>
        <Form.Item
          label="安装位置"
          name="installPosition"
        >
          <Input maxLength={50} placeholder="请输入安装位置" />
        </Form.Item>
        <Form.Item
          label="出厂日期"
          name="factoryDate"
        >
          <DatePicker format="YYYY-MM-DD" style={{ width: "100%" }} placeholder="请选择出厂日期" />
        </Form.Item>
        <Form.Item
          label="是否通过系统设定报警"
          name="thresholdFlag"
          rules={[{ required: true, message: "请选择是否通过系统设定报警" }]}
        >
          <Select
            options={YES_NO_OPTIONS.map(item => ({
              value: item.bianma,
              label: item.name,
            }))}
            placeholder="请选择是否通过系统设定报警"
            disabled={!!props.currentId}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default SensorDeviceModal;
