import {
  ReloadOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { Button, DatePicker, Form, Modal, Space } from "antd";
import * as echarts from "echarts";

import { useEffect, useRef } from "react";
import Table from "zy-react-library/components/Table";
import useTable from "zy-react-library/hooks/useTable";

// const COLLECT_INTERVAL_SECONDS = 10;
// const COLLECT_DURATION_SECONDS = 60 * 60;

// function getMockCollectData(record) {
//   const now = dayjs();
//   const rangeMin = Number(record.rangeMin);
//   const rangeMax = Number(record.rangeMax);
//   const hasRange = Number.isFinite(rangeMin) && Number.isFinite(rangeMax) && rangeMax > rangeMin;
//   const base = hasRange ? (rangeMin + rangeMax) / 2 : 50;
//   const amplitude = hasRange ? (rangeMax - rangeMin) * 0.18 : 8;
//   const count = COLLECT_DURATION_SECONDS / COLLECT_INTERVAL_SECONDS;
//
//   return Array.from({ length: count + 1 }, (_, index) => {
//     const time = now.subtract(COLLECT_DURATION_SECONDS - index * COLLECT_INTERVAL_SECONDS, "second");
//     const value = record.sensorAttr === "SWITCH"
//       ? Math.round(Math.random())
//       : base
//         + Math.sin(index / 10) * amplitude
//         + (Math.random() - 0.5) * amplitude * 0.5;
//
//     return {
//       time: time.format("HH:mm:ss"),
//       value: Number(value.toFixed(2)),
//     };
//   });
// }

function RealtimeModal(props) {
  const [form] = Form.useForm();
  const { tableProps, getData } = useTable(props.sensorDeviceList, {
    form,
    usePermission: false,
    transform: formData => ({
      alarmTimeStart: formData.createTime?.[0]?.format("YYYY-MM-DD"),
      alarmTimeEnd: formData.createTime?.[1]?.format("YYYY-MM-DD"),
      sensorDeviceId: props.record.sensorDeviceId,
    }),
  });
  const record = props.record || {};
  const chartRef = useRef(null);

  const handleReset = () => {
    form.resetFields();
    getData();
  };

  useEffect(() => {
    if (!props.open || !chartRef.current) {
      return;
    }
    console.log(props);
    props.sensorDeviceLineChart({ id: props.record.sensorDeviceId }).then((res) => {
      const data = res.data ? res.data : [];

      const chart = echarts.init(chartRef.current);

      chart.setOption({
        grid: {
          top: 48,
          right: 24,
          bottom: 48,
          left: 56,
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: data.map(item => item.alarmTime),
          axisLabel: {
            hideOverlap: true,
          },
        },
        yAxis: {
          type: "value",
          // name: `采集值${unit}`,
          scale: true,
        },
        series: [
          {
            name: "采集值",
            type: "line",
            smooth: true,
            showSymbol: false,
            data: data.map(item => item.currentValue),
            lineStyle: {
              width: 2,
            },
            areaStyle: {
              opacity: 0.08,
            },
          },
        ],
      });

      const handleResize = () => chart.resize();
      window.addEventListener("resize", handleResize);

      return () => {
        window.removeEventListener("resize", handleResize);
        chart.dispose();
      };
    });
  }, [props.open, record]);

  return (
    <Modal
      open={props.open}
      title="实时概览"
      onCancel={props.onCancel}
      footer={null}
      maskClosable={false}
      width={1200}
    >
      <div
        ref={chartRef}
        style={{ width: "100%", height: 320, marginBottom: 16 }}
      />

      <Form form={form} layout="inline" style={{ marginBottom: 16 }}>
        <Form.Item name="createTime" label="采集时间">
          <DatePicker.RangePicker format="YYYY-MM-DD" />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" icon={<SearchOutlined />} onClick={() => getData()}>
              搜索
            </Button>
            <Button icon={<ReloadOutlined />} onClick={handleReset}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <Table
        options={false}
        disabledResizer={true}
        columns={[
          { title: "传感器名称", dataIndex: "sensorName" },
          { title: "采集时间", dataIndex: "alarmTime" },
          { title: "报警描述", dataIndex: "alarmDesc" },
          { title: "告警值", dataIndex: "currentValue" },
          { title: "计量单位", dataIndex: "unitName" },
          { title: "高高报警阈值", dataIndex: "thresholdHighHigh" },
          { title: "高报警阈值", dataIndex: "thresholdHigh" },
          { title: "低低报警阈值", dataIndex: "thresholdLowLow" },
          { title: "低报警阈值", dataIndex: "thresholdLow" },
        ]}
        {...tableProps}
      />
    </Modal>
  );
}

export default RealtimeModal;
