import React, {
  useEffect,
  useState,
  forwardRef,
  useImperativeHandle,
} from "react";
import { Form, Input, Select, message, Switch, Space, Col, Tabs } from "antd";
import { Modal, Button, Radio } from "antd";
import styles from "./detail.module.less";
import API from "../../../api/alarm";
import { useMemoizedFn } from "ahooks";
import { CloseOutlined } from "@ant-design/icons";
import _ from "lodash";
import AlarmHistory from "./components/AlarmHistory";
import AlarmDetail from "./components/AlarmDetail";
import AlarmConfirm from "./components/AlarmConfirm";
// import { AlarmConfig } from "./components/AlarmConfig";

const Detail = (props) => {
  const { options, isDiagram } = props;
  const [tags, setTags] = useState([]);
  const [current, setCurrent] = useState("history");
  const [ruleId, setRuleId] = useState(-1);
  const [showConfirm, setShowConfirm] = useState(false);
  // const [showAlarmConfig, setShowAlarmConfig] = useState(false);
  const getRuleIdByPointId = useMemoizedFn(async (ruleId, pointId) => {
    const ids = [];
    if (options.pointId) {
      const res = await API.getRuleIdByPointId(pointId);
      ids.push(res?.data?.[0]?.id);
    }
    if (options.ruleId) {
      ids.push(ruleId);
    }
    setRuleId(ids);
    setCurrent("history");
    setTags([]);
  });
  useEffect(() => {
    if (options.ruleId || options.pointId) {
      getRuleIdByPointId(options.ruleId, options.pointId);
    } else if (options.detail) {
      setRuleId([options.detail.rule_id]);
      setTags([
        {
          id: options.detail.id,
          data: options.detail,
        },
      ]);
      setCurrent(options.detail.id);
    }
  }, [options.detail, options.ruleId, options.pointId]);
  const currentData = tags.find((item) => item.id === current) ?? {};
  const onRemove = (index) => {
    const newTags = _.cloneDeep(tags);
    newTags.splice(index, 1);
    setTags(newTags);
  };
  const onSelect = (record) => {
    if (!tags.some((item) => item.id === record.id)) {
      const newTags = _.cloneDeep(tags);
      newTags.push({
        id: record.id,
        data: record,
      });
      setTags(newTags);
    }
    setCurrent(record.id);
  };
  const onAlarmConfirm = (newRecord) => {
    if (newRecord) {
      const newTags = _.clone(tags);
      const currentIndex = newTags.findIndex((item) => item.id === current);
      newTags[currentIndex].data = newRecord;
      setTags(newTags);
    }
  };

  return (
    <>
      <Modal
        title="告警记录"
        open={props.open}
        width="90vw"
        onCancel={() => {
          props.onCancel();
        }}
        zIndex="1001"
        footer={null}
        destroyOnClose
        style={{
          top: 50,
        }}
        bodyStyle={{
          height: "calc(90vh - 80px)",
        }}
      >
        {props.open && (
          <>
            <div className={styles.header}>
              <div className={styles.tags}>
                <Tabs
                  hideAdd
                  onChange={setCurrent}
                  activeKey={current}
                  type="card"
                  items={[
                    { label: "告警记录", children: null, key: "history" },
                    ...tags.map((item, index) => ({
                      label: (
                        <div className={styles.tagContainer}>
                          <div className={styles.label}>详情{index + 1}</div>
                          <CloseOutlined
                            style={{ fontSize: 10 }}
                            onClick={(e) => {
                              e.stopPropagation();
                              if (current === item.id) {
                                setCurrent("history");
                              }
                              onRemove(index);
                            }}
                          />
                        </div>
                      ),
                      children: null,
                      key: item.id,
                    })),
                  ]}
                />
                {/* <Radio.Group
                  value={current}
                  onChange={(e) => setCurrent(e.target.value)}
                  size="middle"
                >
                  <Radio.Button value="history">告警记录</Radio.Button>
                  {tags.map((item, index) => (
                    <Radio.Button value={item.id}>
                      <div className={styles.tagContainer}>
                        <div className={styles.label}>详情{index + 1}</div>
                        <CloseOutlined
                          style={{ fontSize: 10 }}
                          onClick={() => {
                            if (current === item.id) {
                              setCurrent("history");
                            }
                            onRemove(index);
                          }}
                        />
                      </div>
                    </Radio.Button>
                  ))}
                </Radio.Group> */}
              </div>
              <div className={styles.oper}>
                {current !== "history" && (
                  <Button
                    disabled={currentData?.data?.op_status === 1}
                    onClick={() => setShowConfirm(true)}
                  >
                    {currentData?.data?.op_status === 1 ? "已确认" : "确认"}
                  </Button>
                )}
                <Button onClick={props?.onSetting} style={{ marginLeft: 10 }}>
                  告警配置
                </Button>
              </div>
            </div>

            {current === "history" && (
              <AlarmHistory onSelect={onSelect} ruleId={ruleId}></AlarmHistory>
            )}
            {current !== "history" && (
              <AlarmDetail data={currentData}></AlarmDetail>
            )}
          </>
        )}
      </Modal>
      <AlarmConfirm
        currentAlarm={currentData?.data}
        open={showConfirm}
        onCancel={() => setShowConfirm(false)}
        onConfirm={onAlarmConfirm}
      />
      {/* <AlarmConfig
        visible={showAlarmConfig}
        pointId={props.alarmConfig?.pointId}
        ruleId={props.alarmConfig?.ruleId}
        onClose={() => {
          setShowAlarmConfig(false);
        }}
        onConfirm={({ id }) => props.onConfirm?.({ ruleId: id ?? 0 })}
        isDiagram={isDiagram}
      ></AlarmConfig> */}
    </>
  );
};

export default Detail;
