import { Col, Descriptions, Divider, Form, message, Modal, Row, Select } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import DictionarySelect from "zy-react-library/components/Select/Dictionary";
import PersonnelSelect from "zy-react-library/components/Select/Personnel/Gwj";
import useGetUserInfo from "zy-react-library/hooks/useGetUserInfo";
import { getLabelName } from "zy-react-library/utils";
import BaiduMap from "~/components/BaiduMap";
import { DISPOSAL_STATIS, SENSOR_ATTR_OPTIONS } from "~/enumerate/constant";
import { renderAlarmCurrentValue } from "~/utils/alarm";

function AssignModal(props) {
  const [form] = Form.useForm();
  const [detail, setDetail] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [corpinfoId, setCorpinfoId] = useState(null);
  const { getUserInfo } = useGetUserInfo();
  const alarmLevelName = useRef(null);
  const alarmTypeName = useRef(null);
  const disposeStatus = Form.useWatch("disposeStatus", form);

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

    form.resetFields();
    setDetail({});

    if (!props.isBatch && props.alarmId && props.alarmRecordInfo) {
      props.alarmRecordInfo({ id: props.alarmId }).then((res) => {
        if (res?.success) {
          setDetail(res.data || {});
        }
      });
    }
  }, [props.open]);

  useEffect(() => {
    getUserInfo().then((data) => {
      setCorpinfoId(data.corpinfoId);
    });
  }, []);

  useEffect(() => {
    if (disposeStatus !== 1) {
      return;
    }

    form.setFieldsValue({
      alarmType: undefined,
      alarmLevel: undefined,
      disposeUserId: undefined,
    });
  }, [disposeStatus]);

  const handleCancel = () => {
    form.resetFields();
    setDetail({});
    props.onCancel();
  };

  const handleSubmit = async (values) => {
    if (submitting) {
      return;
    }

    setSubmitting(true);
    values.alarmLevelName = alarmLevelName.current;
    values.alarmTypeName = alarmTypeName.current;
    values.status = values.disposeStatus === 1 ? 40 : 20;

    try {
      let res;
      if (props.isBatch) {
        values.ids = props.alarmIds;
        res = await props.alarmAssign(values);
      }
      else {
        values.ids = [props.alarmId];
        res = await props.alarmAssign(values);
      }

      if (res?.success) {
        handleCancel();
        props.getData();
        message.success("处置成功");
      }
    }
    finally {
      setSubmitting(false);
    }
  };

  const formatTime = (value) => {
    if (!value) {
      return "-";
    }

    const time = dayjs(value);
    return time.isValid() ? time.format("YYYY-MM-DD HH:mm:ss") : value;
  };

  return (
    <Modal
      destroyOnClose
      open={props.open}
      title={props.isBatch ? "批量分配" : "分配处置"}
      onCancel={handleCancel}
      onOk={form.submit}
      confirmLoading={props.loading || submitting}
      maskClosable={false}
      width={1200}
    >
      {!props.isBatch && (
        <>
          <Divider orientation="left">报警信息</Divider>
          <Descriptions column={2} bordered labelStyle={{ width: 200 }}>
            <Descriptions.Item label="传感器编码">{detail.sensorCode || "-"}</Descriptions.Item>
            <Descriptions.Item label="传感器名称">{detail.sensorName || "-"}</Descriptions.Item>
            <Descriptions.Item label="传感器类型">{detail.sensorTypeName || "-"}</Descriptions.Item>
            <Descriptions.Item label="传感器属性">
              {getLabelName({ status: detail.sensorAttr, list: SENSOR_ATTR_OPTIONS }) || "-"}
            </Descriptions.Item>
            <Descriptions.Item label="告警值">{renderAlarmCurrentValue(detail)}</Descriptions.Item>
            <Descriptions.Item label="计量单位">{detail.unitName || "-"}</Descriptions.Item>
            <Descriptions.Item label="高高报警阈值">{detail.thresholdHighHigh || "-"}</Descriptions.Item>
            <Descriptions.Item label="高报警阈值">{detail.thresholdHigh || "-"}</Descriptions.Item>
            <Descriptions.Item label="低低报警阈值">{detail.thresholdLowLow || "-"}</Descriptions.Item>
            <Descriptions.Item label="低报警阈值">{detail.thresholdLow || "-"}</Descriptions.Item>
            <Descriptions.Item label="报警编号">{detail.alarmNo || "-"}</Descriptions.Item>
            <Descriptions.Item label="报警时间">{formatTime(detail.alarmTime)}</Descriptions.Item>
            <Descriptions.Item label="报警描述" span={2}>
              {detail.alarmDesc || detail.deviceSourceDesc || "-"}
            </Descriptions.Item>
            <Descriptions.Item label="报警位置" span={2}>
              {detail.longitude && detail.latitude
                ? (
                    <BaiduMap
                      longitude={detail.longitude}
                      latitude={detail.latitude}
                      style={{
                        border: "1px solid #f0f0f0",
                        borderRadius: 4,
                        overflow: "hidden",
                      }}
                    />
                  )
                : "暂无定位信息"}
            </Descriptions.Item>
          </Descriptions>
        </>
      )}

      <Divider orientation="left">处置分配</Divider>
      <Form
        form={form}
        layout="horizontal"
        onFinish={handleSubmit}
        labelCol={{ span: 4 }}
        initialValues={{ disposeStatus: 0 }}
      >
        <Row>
          <Col span={12}>
            <Form.Item
              label="报警处置"
              name="disposeStatus"
              rules={[{ required: true, message: "请选择报警处置" }]}
            >
              <Select
                options={DISPOSAL_STATIS.map(item => ({
                  value: item.bianma,
                  label: item.name,
                }))}
                placeholder="请选择报警处置"
              />
            </Form.Item>
          </Col>

          {disposeStatus !== 1 && (
            <Col span={12}>
              <Form.Item
                label="报警类型"
                name="alarmType"
                rules={[{ required: true, message: "请选择报警类型" }]}
              >
                <DictionarySelect
                  dictValue="alarmType"
                  onGetLabel={(label) => {
                    alarmTypeName.current = label;
                  }}
                />
              </Form.Item>
            </Col>
          )}
        </Row>

        {disposeStatus !== 1 && (
          <Row>
            <Col span={12}>
              <Form.Item
                label="报警级别"
                name="alarmLevel"
                rules={[{ required: true, message: "请选择报警级别" }]}
              >
                <DictionarySelect
                  dictValue="alarmLevel"
                  onGetLabel={(label) => {
                    alarmLevelName.current = label;
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="处置人"
                name="disposeUserId"
                rules={[{ required: true, message: "请选择处置人" }]}
              >
                <PersonnelSelect
                  placeholder="请选择处置人"
                  isNeedDepartmentId={false}
                  isNeedCorpInfoId={true}
                  params={{ corpinfoId }}
                />
              </Form.Item>
            </Col>
          </Row>
        )}
      </Form>
    </Modal>
  );
}

export default AssignModal;
