<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref, useTemplateRef, watch } from 'vue';
import { useRoute } from 'vue-router';
import BScroll from '@better-scroll/core';
import MouseWheel from '@better-scroll/mouse-wheel';
import { message } from 'ant-design-vue';

import ButtonTabs from '@/components/ButtonTabs.vue';
import LineChart from '@/components/LineChart.vue';
import SvgIcon from '@/components/SvgIcon.vue';
import { useDictData } from '@/hooks/dict-data';
import { useRequest } from '@/hooks/request';
import { useUserInfoStore } from '@/stores/user-info';
import router from '@/router';
import { t } from '@/i18n';
import {
  addMonitorPoint,
  addRegion,
  deleteMonitorPoint,
  getDeviceGroupList,
  getDeviceListOptions,
  getDeviceListSimple,
  getGroupRegions,
  getMonitorPointAlarmHistory,
  getMonitorPointInfo,
  getPageList,
  getRegionsPointsData,
  getRegionsPointsValue,
  queryDevicesList,
  regionDelete,
  regionUpdate,
  updateMonitorPoint,
  updateRegionMonitorPoint,
} from '@/api';
import { OperatePermission } from '@/utils/permission-type';
import { DictCode, HumitureType } from '@/constants';

import AreaEditor from './AreaEditor.vue';
import AreaPreview from './AreaPreview.vue';
import EnvMonitorList from './EnvMonitorList.vue';
import HumitureCurve from './HumitureCurve.vue';

import type { CSSProperties } from 'vue';
import type { Meta2dData } from '@meta2d/core';
import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import type { DefaultOptionType, SelectValue } from 'ant-design-vue/es/select';
import type {
  AlarmHistoryItem,
  DeviceGroup,
  DeviceGroupItem,
  DeviceParams,
  DeviceParamType,
  DevicesListItem,
  DictValue,
  GroupRegions,
  MonitoringForm,
  MonitoringPointData,
  OutdooForm,
  RegionNameList,
  RegionsPointsItem,
} from '@/types';

interface TimeList {
  time: string;
  integral: boolean;
  index: number;
  backgroundShow: boolean;
}

interface RunStatusList {
  id: number;
  name: string;
}

interface QueryItem {
  monitorId?: number;
  parentDevGroupId?: number;
  devGroupId?: number;
}

const { dictData: paramAlgOperator, getDictData: getParamAlgOperator } = useDictData(DictCode.ParamAlgOperator);
const envMonitorListRef = useTemplateRef('envMonitorList');
const temperatureDifference = ref<DictValue[]>([]);
const oneDeviceGroup = ref<DeviceGroup[]>([]);
const twoDeviceGroup = ref<DeviceGroup[]>([]);
const runStatusList = ref<RunStatusList[]>([]);
const inputType = ref<number>(1);
const gradeOne = ref<number | undefined>(undefined);
const gradeTwo = ref<number | undefined>(undefined);
const monitoringPointOpen = ref<boolean>(false);
const outdoorOpen = ref<boolean>(false);
const regionNameOpen = ref<boolean>(false);
const monitoringDataOpen = ref<boolean>(false);
const regionCopyOpen = ref<boolean>(false);
const { booleanPermission } = useUserInfoStore();
const regionName = ref<string>('');
const regionNameEditor = ref<string>('');
const groupRegions = ref<GroupRegions[]>([]);
const titleRegions = ref<boolean>(true);
const titleMonitoring = ref<boolean>(true);
const deviceGroup = ref<DeviceGroupItem[]>([]);
const returnDevicesList = ref<DevicesListItem[]>([]);
const supplyDevicesList = ref<DevicesListItem[]>([]);
const outdoorDevicesList = ref<DevicesListItem[]>([]);
const freshDevicesList = ref<DevicesListItem[]>([]);
const runDevicesList = ref<DevicesListItem[]>([]);
const returnDeviceParamsList = ref<DeviceParams[]>([]);
const supplyDeviceParamsList = ref<DeviceParams[]>([]);
const outdoorDeviceParamsList = ref<DeviceParams[]>([]);
const freshDeviceParamsList = ref<DeviceParams[]>([]);
const runDeviceParamsList = ref<DeviceParamType[]>([]);
const queryItem = ref<QueryItem>({
  monitorId: undefined,
  parentDevGroupId: undefined,
  devGroupId: undefined,
});
const monitoringPointData = ref<MonitoringPointData[]>([]);
const regionNameList = ref<RegionNameList[]>([]);
const regionList = ref<RegionsPointsItem[]>([]);
const monitoringList = ref<RegionsPointsItem[]>([]);
const selectId = ref<number>(0);
const monitoringName = ref<string>();
const monitoringId = ref<number>();
const formRef = ref<FormInstance>();
const listDisplay = ref<boolean>(true);
const timeList = ref<TimeList[]>([]);
const timeLineIndex = ref<number>(0);
const chooseTime = ref<string>();
const alarmHistoryList = ref<AlarmHistoryItem[]>([]);
const route = useRoute();
const monitoringForm = ref<MonitoringForm>({
  name: '',
  tempHumidityControlMode: '2',
  regionId: undefined,
  returnDevGroupId: undefined,
  returnDevId: undefined,
  returnTempParamCode: undefined,
  returnHumidityParamCode: undefined,
  supplyDevGroupId: undefined,
  supplyTempParamCode: undefined,
  supplyHumidityParamCode: undefined,
  outdoorDevGroupId: undefined,
  outdoorDevId: undefined,
  outdoorTempParamCode: undefined,
  outdoorHumidityParamCode: undefined,
  tempUpper: undefined,
  tempLower: undefined,
  tempPreset: undefined,
  humidityUpper: undefined,
  humidityLower: undefined,
  humidityPreset: undefined,
  runStatusFlag: 0,
  supplyReturnTempDiff: undefined,
  supplyUpperTempDiff: undefined,
  runStatusDevGroupId: undefined,
  runStatusDevId: undefined,
  runStatusParamCode: undefined,
  runStatusConditionCode: undefined,
  runStatusConditionValue: undefined,
});

const outdooForm = ref<OutdooForm>({
  regionId: undefined,
  outsideDevGroupId: undefined,
  outsideDevId: undefined,
  outsideTempParamCode: undefined,
  outsideHumidityParamCode: undefined,
  outsideEnthalpyParamCode: undefined,
});

const headerStyle: CSSProperties = {
  borderBottom: 0,
  padding: '16px 16px 0 24px',
};

const footerStyle: CSSProperties = {
  borderTop: 0,
  padding: '16px 24px',
};

const rules: Record<string, Rule[]> = {
  name: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  regionId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  tempHumidityControlMode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  returnDevGroupId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  returnDevId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  returnTempParamCode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  returnHumidityParamCode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  supplyDevGroupId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  supplyDevId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  supplyTempParamCode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  supplyHumidityParamCode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  outdoorDevGroupId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  outdoorDevId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  outdoorTempParamCode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  outdoorHumidityParamCode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  runStatusFlag: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  supplyReturnTempDiff: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  supplyUpperTempDiff: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  tempUpper: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  tempPreset: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  tempLower: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  humidityUpper: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  humidityLower: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  humidityPreset: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  runStatusDevId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  runStatusParamCode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  runStatusConditionCode: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  runStatusConditionValue: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  runStatusDevGroupId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
};

const { handleRequest } = useRequest();

const getGroupRegionsList = () => {
  handleRequest(async () => {
    if (gradeTwo.value) {
      groupRegions.value = await getGroupRegions(gradeTwo.value);
    }
  });
};

const regionNameOk = () => {
  if (!regionName.value) {
    return message.warning(t('envMonitor.pleaseRegionName'));
  }
  handleRequest(async () => {
    if (gradeTwo.value && regionName.value) {
      if (titleRegions.value) {
        await addRegion({
          devGroupId: gradeTwo.value,
          regionName: regionName.value,
        });
      } else {
        if (regionNameEditor.value != regionName.value) {
          await regionUpdate({
            id: monitoringForm.value.regionId,
            devGroupId: gradeTwo.value,
            regionName: regionName.value,
          });
        }
      }
      getGroupRegionsList();

      if (gradeTwo.value) {
        getRegionsPointsList(gradeTwo.value, false);
        obtainRegionsPointsData(gradeTwo.value);
      }

      regionNameOpen.value = false;
    }
  });
};

const regionNameDelete = () => {
  if (!regionName.value) {
    return message.warning(t('envMonitor.pleaseRegionName'));
  }
  handleRequest(async () => {
    if (monitoringForm.value.regionId) {
      await regionDelete(monitoringForm.value.regionId);
      monitoringForm.value.regionId = undefined;
      getGroupRegionsList();

      if (gradeTwo.value) {
        getRegionsPointsList(gradeTwo.value, false);
        obtainRegionsPointsData(gradeTwo.value);
      }

      regionNameOpen.value = false;
    }
  });
};

const addRegionName = () => {
  titleRegions.value = true;
  regionNameOpen.value = true;
  regionName.value = '';
};

const addRegionList = (value: SelectValue, option: DefaultOptionType) => {
  regionNameEditor.value = option.regionName;
  regionName.value = option.regionName;
};

const editingRegionName = () => {
  if (monitoringForm.value.regionId) {
    groupRegions.value.forEach((item) => {
      if (item.id === monitoringForm.value.regionId) {
        regionName.value = item.regionName;
      }
    });
    titleRegions.value = false;
    regionNameOpen.value = true;
  } else {
    return message.warning(t('envMonitor.selectNameArea'));
  }
};

const addMonitoringPoint = () => {
  titleMonitoring.value = true;
  monitoringPointOpen.value = true;
};
const addAllGatewayList = (value: number) => {
  handleRequest(async () => {
    let item;
    if (value === -1) {
      item = {
        parentId: value,
        haveChild: true,
      };
    } else {
      item = {
        parentId: value,
      };
    }

    const data = await getDeviceGroupList(item);

    const { devGroupId, parentDevGroupId } = queryItem.value;

    if (data.length) {
      if (value === -1) {
        oneDeviceGroup.value = data;
        if (parentDevGroupId) {
          gradeOne.value = parentDevGroupId;
        } else {
          gradeOne.value = data[0].id;
        }
      } else {
        twoDeviceGroup.value = data;
        if (devGroupId) {
          gradeTwo.value = devGroupId;
        } else {
          gradeTwo.value = data[0].id;
        }
      }
    }
  });
};

const { isLoading, handleRequest: handleEnvMonitorRequest } = useRequest();

const getRegionsPointsList = (value: number, show: boolean) => {
  monitoringPointData.value = [];
  regionNameList.value = [];
  monitoringList.value = [];
  copyToRegionId.value = undefined;

  handleEnvMonitorRequest(async () => {
    let data: RegionsPointsItem[] = [];
    if (show) {
      if (chooseTime.value) {
        data = await getRegionsPointsValue(value, {
          endTime: `${getCurrentDate()} ${chooseTime.value.length > 6 ? chooseTime.value : chooseTime.value + ':00'}`,
        });

        regionList.value = data;
      }
    } else {
      data = await getRegionsPointsData(value);
    }

    if (data.length) {
      data.forEach((item) => {
        const { id, regionName } = item;
        if (item.points.length) {
          monitoringPointData.value.push(...item.points);
          monitoringList.value.push({ ...item, name: item.regionName });
        }

        regionNameList.value.push({
          name: regionName,
          id,
        });
      });
      if (monitoringPointData.value.length) {
        monitoringPointData.value.sort((item1, item2) => {
          // 优先级：3 > 2 > 其他
          const priority1 = item1.status === 3 ? 1 : item1.status === 2 ? 2 : item1.status === 1 ? 3 : 4;
          const priority2 = item2.status === 3 ? 1 : item2.status === 2 ? 2 : item2.status === 1 ? 3 : 4;

          return priority1 - priority2;
        });

        if (queryItem.value.monitorId) {
          monitoringId.value = queryItem.value.monitorId;
        } else {
          monitoringId.value = monitoringPointData.value[0].id;
        }
        selectId.value = monitoringPointData.value[0].regionId;
      } else {
        selectId.value = data[0].id;
      }
    }
  });
};

const confirmTimeLine = () => {
  if (gradeTwo.value) {
    getRegionsPointsList(gradeTwo.value, true);
  }
};

const obtainRegionsPointsData = (value: number) => {
  handleRequest(async () => {
    regionList.value = await getRegionsPointsData(value);
  });
};

const adddDeviceGroup = (value: SelectValue, option: DefaultOptionType, judgment: number) => {
  getDevicesGroupList(option.id, judgment, true);
};

const adddDevice = (value: SelectValue, option: DefaultOptionType, judgment: number) => {
  getDeviceParamsList(option.id, judgment, true);
};

const adddRunStatusDevice = (value: SelectValue, option: DefaultOptionType) => {
  monitoringForm.value.runStatusParamCode = undefined;
  monitoringForm.value.runStatusConditionCode = undefined;
  monitoringForm.value.runStatusConditionValue = undefined;
  getDeviceListOptionsList(option.id, false, '');
};

const getDeviceListOptionsList = (id: number, show: boolean, runStatusParamCode: string) => {
  handleRequest(async () => {
    runDeviceParamsList.value = await getDeviceListOptions(id);

    if (show) {
      runStatusList.value = [];
      runDeviceParamsList.value.forEach((item) => {
        if (item.deviceParamCode === runStatusParamCode) {
          inputType.value = item.type;

          if (item.type === 1) {
            item.candidates.forEach((item: string, index: number) => {
              runStatusList.value.push({
                id: index,
                name: item,
              });
            });
          }
        }
      });
    }
  });
};

const adddParametersDevice = (value: SelectValue, option: DefaultOptionType) => {
  runStatusList.value = [];
  inputType.value = option.type;
  monitoringForm.value.runStatusConditionCode = undefined;
  monitoringForm.value.runStatusConditionValue = undefined;

  if (option.type === 1) {
    option.candidates.forEach((item: string, index: number) => {
      runStatusList.value.push({
        id: index,
        name: item,
      });
    });
  }
};

const getDeviceParamsList = (id: number, judgment: number, show: boolean) => {
  handleRequest(async () => {
    const data = await getDeviceListSimple(id);

    if (judgment === HumitureType.ReturnAir) {
      returnDeviceParamsList.value = data;
      if (show) {
        monitoringForm.value.returnHumidityParamCode = undefined;
        monitoringForm.value.returnTempParamCode = undefined;
      }
    } else if (judgment === HumitureType.SupplyAir) {
      supplyDeviceParamsList.value = data;
      if (show) {
        monitoringForm.value.supplyHumidityParamCode = undefined;
        monitoringForm.value.supplyTempParamCode = undefined;
      }
    } else if (judgment === HumitureType.Outdoor) {
      outdoorDeviceParamsList.value = data;
      if (show) {
        outdooForm.value.outsideEnthalpyParamCode = undefined;
        outdooForm.value.outsideHumidityParamCode = undefined;
        outdooForm.value.outsideTempParamCode = undefined;
      }
    } else if (judgment === HumitureType.FreshAir) {
      freshDeviceParamsList.value = data;
      if (show) {
        monitoringForm.value.outdoorTempParamCode = undefined;
        monitoringForm.value.outdoorHumidityParamCode = undefined;
      }
    }
  });
};

const getDevicesGroupList = (id: number, judgment: number, show: boolean) => {
  handleRequest(async () => {
    const { records } = await queryDevicesList({
      pageIndex: 1,
      pageSize: 99999,
      groupId: id,
    });
    if (judgment === HumitureType.ReturnAir) {
      returnDevicesList.value = records;
      if (show) {
        monitoringForm.value.returnDevId = undefined;
        monitoringForm.value.returnHumidityParamCode = undefined;
        monitoringForm.value.returnTempParamCode = undefined;
      }
    } else if (judgment === HumitureType.SupplyAir) {
      supplyDevicesList.value = records;
      if (show) {
        monitoringForm.value.supplyDevId = undefined;
        monitoringForm.value.supplyHumidityParamCode = undefined;
        monitoringForm.value.supplyTempParamCode = undefined;
      }
    } else if (judgment === HumitureType.Outdoor) {
      outdoorDevicesList.value = records;
      if (show) {
        outdooForm.value.outsideDevId = undefined;
        outdooForm.value.outsideEnthalpyParamCode = undefined;
        outdooForm.value.outsideHumidityParamCode = undefined;
        outdooForm.value.outsideTempParamCode = undefined;
      }
    } else if (judgment === HumitureType.FreshAir) {
      freshDevicesList.value = records;
      if (show) {
        monitoringForm.value.outdoorDevId = undefined;
        monitoringForm.value.outdoorTempParamCode = undefined;
        monitoringForm.value.outdoorHumidityParamCode = undefined;
      }
    } else if (judgment === HumitureType.OperatingStatus) {
      runDevicesList.value = records;
      if (show) {
        monitoringForm.value.runStatusDevId = undefined;
        monitoringForm.value.runStatusParamCode = undefined;
        monitoringForm.value.runStatusConditionCode = undefined;
        monitoringForm.value.runStatusConditionValue = undefined;
      }
    }
  });
};
const deleteMonitoringPoint = () => {
  if (!titleMonitoring.value) {
    handleRequest(async () => {
      if (monitoringId.value) {
        await deleteMonitorPoint(monitoringId.value);
        if (gradeTwo.value) {
          getRegionsPointsList(gradeTwo.value, false);
          obtainRegionsPointsData(gradeTwo.value);
          timeLineIndex.value = timeList.value.length - 1;
        }

        closeModal();
      }
    });
  }

  monitoringPointOpen.value = false;
};

const saveMonitoringPoint = () => {
  formRef.value
    ?.validate()
    .then(() => {
      handleRequest(async () => {
        if (titleMonitoring.value) {
          delete monitoringForm.value.id;
          await addMonitorPoint(monitoringForm.value);
        } else {
          await updateMonitorPoint(monitoringForm.value);
        }
        if (gradeTwo.value) {
          getRegionsPointsList(gradeTwo.value, false);
          obtainRegionsPointsData(gradeTwo.value);
        }
        closeModal();
        monitoringPointOpen.value = false;
      });
    })
    .catch(() => {});
};

const getDeviceGroup = () => {
  handleRequest(async () => {
    deviceGroup.value = await getPageList();
  });
};

const offDrawer = () => {
  monitoringPointOpen.value = false;
  closeModal();
};

const selectClick = (id: number) => {
  selectId.value = id;
  copyToRegionId.value = undefined;
};

const historicalDataClick = (data: MonitoringPointData) => {
  monitoringName.value = data.name;
  monitoringId.value = data.id;
  selectId.value = data.regionId;
  monitoringDataOpen.value = true;
};

const editorClick = (monitoringPointId: number) => {
  handleRequest(async () => {
    const {
      humidityLower,
      humidityPreset,
      humidityUpper,
      name,
      regionId,
      returnDevGroupId,
      returnDevId,
      returnHumidityParamCode,
      returnTempParamCode,
      supplyDevGroupId,
      supplyDevId,
      supplyHumidityParamCode,
      supplyTempParamCode,
      tempHumidityControlMode,
      tempLower,
      tempPreset,
      tempUpper,
      id,
      outdoorDevGroupId,
      outdoorDevId,
      outdoorTempParamCode,
      outdoorHumidityParamCode,
      runStatusFlag,
      supplyReturnTempDiff,
      supplyUpperTempDiff,
      runStatusDevGroupId,
      runStatusDevId,
      runStatusParamCode,
      runStatusConditionCode,
      runStatusConditionValue,
    } = await getMonitorPointInfo(monitoringPointId);
    Object.assign(monitoringForm.value, {
      humidityLower,
      humidityPreset,
      humidityUpper,
      name,
      regionId,
      returnDevGroupId,
      returnDevId,
      returnHumidityParamCode,
      returnTempParamCode,
      supplyDevGroupId,
      supplyDevId,
      supplyHumidityParamCode,
      supplyTempParamCode,
      tempHumidityControlMode: String(tempHumidityControlMode),
      tempLower,
      tempPreset,
      tempUpper,
      id,
      outdoorDevGroupId,
      outdoorDevId,
      outdoorTempParamCode,
      outdoorHumidityParamCode,
      runStatusFlag,
      supplyReturnTempDiff,
      supplyUpperTempDiff,
      runStatusDevGroupId,
      runStatusDevId,
      runStatusParamCode,
      runStatusConditionCode,
      runStatusConditionValue,
    });
    monitoringId.value = id;
    getDevicesGroupList(returnDevGroupId, HumitureType.ReturnAir, false);
    getDevicesGroupList(supplyDevGroupId, HumitureType.SupplyAir, false);
    if (monitoringForm.value.tempHumidityControlMode === '1') {
      getDevicesGroupList(outdoorDevGroupId, HumitureType.FreshAir, false);
    }

    getDeviceParamsList(returnDevId, HumitureType.ReturnAir, false);
    getDeviceParamsList(supplyDevId, HumitureType.SupplyAir, false);

    if (monitoringForm.value.tempHumidityControlMode === '1') {
      getDeviceParamsList(outdoorDevId, HumitureType.FreshAir, false);
    }

    if (runStatusDevGroupId) {
      getDevicesGroupList(runStatusDevGroupId, HumitureType.OperatingStatus, false);
    }
    if (runStatusDevId) {
      if (runStatusParamCode) {
        getDeviceListOptionsList(runStatusDevId, true, runStatusParamCode);
      }
    }

    titleMonitoring.value = false;
    monitoringPointOpen.value = true;
  });
};

const closeModal = () => {
  returnDevicesList.value = [];
  returnDeviceParamsList.value = [];
  supplyDevicesList.value = [];
  supplyDeviceParamsList.value = [];
  freshDevicesList.value = [];
  freshDeviceParamsList.value = [];
  runDevicesList.value = [];
  runDeviceParamsList.value = [];
  runStatusList.value = [];

  monitoringForm.value = {
    name: '',
    tempHumidityControlMode: '2',
    regionId: undefined,
    returnDevGroupId: undefined,
    returnDevId: undefined,
    returnTempParamCode: undefined,
    returnHumidityParamCode: undefined,
    supplyDevGroupId: undefined,
    supplyTempParamCode: undefined,
    supplyHumidityParamCode: undefined,
    outdoorDevGroupId: undefined,
    outdoorDevId: undefined,
    outdoorTempParamCode: undefined,
    outdoorHumidityParamCode: undefined,
    tempUpper: undefined,
    tempLower: undefined,
    tempPreset: undefined,
    humidityUpper: undefined,
    humidityLower: undefined,
    humidityPreset: undefined,
    runStatusFlag: 0,
    supplyReturnTempDiff: undefined,
    supplyUpperTempDiff: undefined,
    runStatusDevGroupId: undefined,
    runStatusDevId: undefined,
    runStatusParamCode: undefined,
    runStatusConditionCode: undefined,
    runStatusConditionValue: undefined,
  };

  formRef.value?.resetFields();
};

const addOutdoorDrawer = () => {
  outdoorOpen.value = true;
  regionList.value.forEach((item) => {
    const {
      outsideEnthalpyParamCode,
      outsideHumidityParamCode,
      outsideTempParamCode,
      outsideDevGroupId,
      outsideDevId,
      id,
    } = item;
    if (item.id === selectId.value) {
      Object.assign(outdooForm.value, {
        outsideEnthalpyParamCode,
        outsideHumidityParamCode,
        outsideTempParamCode,
        outsideDevGroupId,
        outsideDevId,
        regionId: id,
      });
      if (outsideDevGroupId) {
        getDevicesGroupList(outsideDevGroupId, HumitureType.Outdoor, false);
      } else {
        outdoorDevicesList.value = [];
      }

      if (outsideDevId) {
        getDeviceParamsList(outsideDevId, HumitureType.Outdoor, false);
      } else {
        outdoorDeviceParamsList.value = [];
      }
    }
  });
};

const saveOutdoo = () => {
  handleRequest(async () => {
    await updateRegionMonitorPoint(outdooForm.value);
    if (gradeTwo.value) {
      obtainRegionsPointsData(gradeTwo.value);
    }

    outdoorOpen.value = false;
  });
};

const offOutdoorDrawer = () => {
  outdoorOpen.value = false;
};

const offMonitoringDrawer = () => {
  monitoringDataOpen.value = false;
};

const copyRegion = () => {
  regionCopyOpen.value = true;
};

const switchDisplay = () => {
  listDisplay.value = !listDisplay.value;
  if (!listDisplay.value) {
    envMonitorListRef.value?.getMonitoringList();
  }
};
const scrollWrapper = ref<HTMLElement | null>(null);
const scrollContent = ref<HTMLElement | null>(null); // 新增内容层 ref
let bs: BScroll | null = null;

const generateTimeArray = async () => {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();
  const minutes = [0, 10, 20, 30, 40, 50];
  const result = [];
  let index = 0;

  for (let hour = 0; hour <= currentHour; hour++) {
    for (const minute of minutes) {
      // 过滤超过当前时间的条目
      if (hour === currentHour && minute > currentMinute) break;

      // 生成时间字符串并添加 integral 标识
      const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
      result.push({
        time: timeStr,
        integral: minute === 0, // 分钟为0时标记为整点
        index: index++,
        backgroundShow: false,
      });
    }
  }

  timeList.value = result;

  // 关键步骤：数据更新后刷新滚动
  await nextTick();
  timeLineIndex.value = timeList.value.length - 1;
  chooseTime.value = getCurrentTime();
  // 关键修复：延迟确保渲染完成
  setTimeout(() => {
    returnCurrently();
  }, 50); // 增加短延迟
};

// 时间字符串转分钟数（支持带日期和不带日期）
function parseTimeToMinutes(timeStr: string): number {
  if (timeStr === null) return 24 * 60; // null视为次日0点
  if (!timeStr.trim()) return 24 * 60; // 空字符串视为次日0点
  const timePart = timeStr.includes(' ') ? timeStr.split(' ')[1] : timeStr;
  const [hours, minutes] = timePart.split(':').slice(0, 2).map(Number);
  return hours * 60 + minutes;
}

const getAlarmHistoryList = () => {
  handleRequest(async () => {
    if (gradeTwo.value) {
      alarmHistoryList.value = await getMonitorPointAlarmHistory(gradeTwo.value);
      if (alarmHistoryList.value.length) {
        // 核心逻辑
        for (const bItem of alarmHistoryList.value) {
          const triggerStart = parseTimeToMinutes(bItem.triggerTime);
          const recoverEnd = parseTimeToMinutes(bItem.recoverTime);

          for (const aItem of timeList.value) {
            const aStart = parseTimeToMinutes(aItem.time);
            const aEnd = aStart + 10;

            // 区间重叠判断（左闭右开）
            const isOverlap = triggerStart < aEnd && recoverEnd >= aStart;

            // 特殊处理：当recoverTime为空时，触发时间后的所有区间
            const recoverTimeString = bItem.recoverTime === null ? '' : bItem.recoverTime;
            const isInfiniteMode = !recoverTimeString.trim() && aStart >= triggerStart;

            if (isOverlap || isInfiniteMode) {
              aItem.backgroundShow = true;
            }
          }
        }
      } else {
        for (const aItem of timeList.value) {
          aItem.backgroundShow = false;
        }
      }
    }
  });
};

// 返回当前
const returnCurrently = () => {
  bs?.refresh();

  if (scrollContent.value && scrollWrapper.value) {
    const contentWidth = scrollContent.value.scrollWidth;
    const wrapperWidth = scrollWrapper.value.clientWidth;
    const maxScrollX = contentWidth - wrapperWidth;

    if (maxScrollX > 0) {
      bs?.scrollTo(-maxScrollX, 0, 800);
    }
    timeLineIndex.value = timeList.value.length - 1;
    chooseTime.value = getCurrentTime();
  }
};

// 获取当前日期（格式：HH:mm）
const getCurrentTime = () => {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, '0'); // 补零的小时（0~23）
  const minutes = String(now.getMinutes()).padStart(2, '0'); // 补零的分钟（0~59）
  const seconds = String(now.getSeconds()).padStart(2, '0'); // 补零的秒（0~59）
  return `${hours}:${minutes}:${seconds}`;
};

const addTimeLine = (value: TimeList) => {
  chooseTime.value = value.time;
  timeLineIndex.value = value.index;
};

// 获取当前日期（格式：YYYY-MM-DD）
const getCurrentDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(date.getDate()).padStart(2, '0'); // 日期补零
  return `${year}-${month}-${day}`;
};

// 注册鼠标滚轮插件
BScroll.use(MouseWheel);

// 初始化 Better-Scroll
const initScroll = async () => {
  await nextTick(); // 等待 DOM 更新
  if (scrollWrapper.value) {
    bs?.destroy(); // 销毁旧实例避免内存泄漏
    bs = new BScroll(scrollWrapper.value, {
      scrollX: true, // 启用横向滚动
      scrollY: false, // 禁用纵向滚动
      probeType: 3, // 实时派发滚动事件
      mouseWheel: {
        speed: 20, // 滚动速度
        invert: false, // 是否反转滚动方向
        easeTime: 300, // 动画缓动时间
        discreteTime: 300, // 离散滚动间隔
      },
      click: true, // 启用点击事件
      disableMouse: false, // 不禁用鼠标控制
    });
  }
};

onUnmounted(() => {
  if (bs) {
    bs.destroy(); // 组件卸载时销毁实例
  }
});

watch(
  () => gradeOne.value,
  (count) => {
    if (count) {
      addAllGatewayList(count);
    }
  },
);

watch(
  () => gradeTwo.value,
  (count) => {
    if (count) {
      getAlarmHistoryList();
      getRegionsPointsList(count, false);
      obtainRegionsPointsData(count);
      getGroupRegionsList();
      timeLineIndex.value = timeList.value.length - 1;
      chooseTime.value = getCurrentTime();
      generateTimeArray();
    }
  },
);

watch(
  () => route.query,
  (count) => {
    if (count) {
      const { monitorId, parentDevGroupId, devGroupId } = route.query;
      if (monitorId || parentDevGroupId || devGroupId) {
        queryItem.value = {
          monitorId: Number(monitorId),
          parentDevGroupId: Number(parentDevGroupId),
          devGroupId: Number(devGroupId),
        };
        gradeOne.value = Number(parentDevGroupId);
        gradeTwo.value = Number(devGroupId);
        monitoringId.value = Number(monitorId);
        router.replace({
          path: route.path,
          query: undefined,
        });
      }
    }
  },
  {
    deep: true, // 监听嵌套属性变化
    immediate: true, // 立即触发一次回调
  },
);

onMounted(() => {
  addAllGatewayList(-1);
  getDeviceGroup();
  generateTimeArray();
  initScroll();
  handleRequest(async () => {
    temperatureDifference.value = [];
    await getParamAlgOperator();
    paramAlgOperator.value.forEach((item) => {
      if (item.dictEngValue === 'eq' || item.dictEngValue === 'ne') {
        temperatureDifference.value.push(item);
      }
    });
  });
});

const areaEditorRef = useTemplateRef('areaEditor');
const areaPreviewRef = useTemplateRef('areaPreview');
const currentAreaData = computed(() => {
  return regionList.value.find((item) => item.id === selectId.value);
});

const saveAreaCanvas = (canvas: string) => {
  handleRequest(async () => {
    if (gradeTwo.value) {
      await regionUpdate({
        id: selectId.value,
        devGroupId: gradeTwo.value,
        canvas,
      });

      const currentAreaData = regionList.value.find((item) => item.id === selectId.value);

      if (currentAreaData) {
        currentAreaData.canvas = canvas;
      }

      areaEditorRef.value?.hideView();
    }
  });
};

const highlightEnvPoint = (id: number) => {
  const monitorPointContainerEle = document.querySelector(`.content-monitoring-canvas-left [data-point-id="${id}"]`);
  monitorPointContainerEle?.scrollIntoView();
  monitoringId.value = id;
};

const copyToRegionId = ref<number>();

const copyToRegionList = computed(() => {
  return regionNameList.value.filter((item) => item.id !== selectId.value);
});

const copyAreaCanvas = () => {
  if (!copyToRegionId.value) {
    message.warning(t('envMonitor.plzSelectRegion'));
    return;
  }

  handleRequest(async () => {
    if (gradeTwo.value && currentAreaData.value) {
      const data = JSON.parse(currentAreaData.value.canvas || '{}') as Meta2dData;

      if (!data.pens?.length) {
        message.warning(t('envMonitor.cannotCopyEmptyCanvas'));
        return;
      }

      // 复制画布中除开监测点控件以外的所有图元
      data.pens = data.pens.filter((item) => item.name !== 'monitorPoint');
      const canvas = JSON.stringify(data);

      await regionUpdate({
        id: copyToRegionId.value,
        devGroupId: gradeTwo.value,
        canvas,
      });

      const copyToAreaData = regionList.value.find((item) => item.id === copyToRegionId.value);

      if (copyToAreaData) {
        copyToAreaData.canvas = canvas;
      }

      regionCopyOpen.value = false;
      message.success(t('envMonitor.copyRegionSuccessful'));
    }
  });
};
</script>

<template>
  <div>
    <ASpin :spinning="isLoading">
      <AFlex justify="space-between">
        <AFlex align="center">
          <div class="text-top">{{ $t('navigation.envMonitor') }}</div>
          <div v-show="listDisplay">
            <ASelect
              class="select-width select-monitoring"
              v-model:value="gradeOne"
              :options="oneDeviceGroup"
              :field-names="{ label: 'groupName', value: 'id' }"
              :placeholder="$t('common.plzSelect')"
            />
            <ASelect
              class="select-width"
              v-model:value="gradeTwo"
              :options="twoDeviceGroup"
              :field-names="{ label: 'groupName', value: 'id' }"
              :placeholder="$t('common.plzSelect', { name: t('createDevice.groupName') })"
            />
          </div>
        </AFlex>

        <div>
          <AButton class="icon-button default-button" @click="switchDisplay">
            <AFlex align="center">
              <SvgIcon name="switch" />
              <span>{{ listDisplay ? $t('envMonitor.listDisplay') : $t('envMonitor.cardDisplay') }} </span>
            </AFlex>
          </AButton>
          <AButton
            type="primary"
            class="icon-button button-monitoring"
            @click="addMonitoringPoint"
            v-if="booleanPermission(OperatePermission.新增监测点)"
          >
            <AFlex align="center">
              <SvgIcon name="plus" />
              <span> {{ $t('envMonitor.addInspectionPoints') }} </span>
            </AFlex>
          </AButton>
        </div>
      </AFlex>

      <div class="content-monitoring" v-show="listDisplay">
        <AFlex class="content-monitoring-top" align="flex-end">
          <div class="scroll-wrapper" ref="scrollWrapper">
            <div class="scroll-content" ref="scrollContent">
              <AFlex align="flex-end" class="time-line">
                <div>&nbsp;&nbsp;&nbsp;</div>

                <div v-for="item in timeList" :key="item.time">
                  <AFlex align="flex-end" :class="item.backgroundShow ? 'background-alarm' : 'background-default'">
                    <AFlex :vertical="true">
                      <div v-if="item.integral" class="time-style">{{ item.time }}</div>
                      <div @click="addTimeLine(item)">
                        <AFlex align="flex-end" class="integral-style">
                          <AFlex
                            :vertical="true"
                            justify="center"
                            align="center"
                            v-if="item.index === timeLineIndex"
                            class="confirm-axis-div"
                          >
                            <div class="confirm-axis-circle"></div>
                            <div class="confirm-axis"></div>
                          </AFlex>
                          <div v-else :class="item.integral ? 'integral' : 'integral-height'"></div>
                        </AFlex>
                      </div>
                    </AFlex>
                  </AFlex>
                </div>
              </AFlex>
            </div>
          </div>
          <AFlex>
            <AButton type="text" class="return-currently" @click="returnCurrently">{{
              $t('envMonitor.returnCurrent')
            }}</AButton>
            <AButton type="primary" class="timeline-confirm" @click="confirmTimeLine">{{
              $t('common.confirm')
            }}</AButton>
          </AFlex>
        </AFlex>
        <AFlex class="content-monitoring-canvas">
          <div class="content-monitoring-canvas-left">
            <div v-for="item in monitoringPointData" :key="item.id" :data-point-id="item.id">
              <LineChart
                :data="item"
                :icon-show="true"
                :monitoring-id="monitoringId"
                @click="areaPreviewRef?.highlightCanvasPoint(item.id)"
                @editorClick="editorClick"
                @historicalDataClick="historicalDataClick"
              />
            </div>
          </div>

          <AFlex class="monitoring-img">
            <AFlex v-show="regionList.length" align="center" class="list-regions">
              <ButtonTabs
                :data="regionNameList"
                :select-id="selectId"
                :width="'75px'"
                :radius="'16px'"
                :tooltip="true"
                @selectClick="selectClick"
              />
            </AFlex>
            <div v-show="regionList.length" class="canvas-div">
              <AFlex justify="space-between" class="canvas-div-top">
                <AButton class="icon-button">
                  <SvgIcon name="outdoor" />
                  {{ currentAreaData?.outSideTemperature || '-' }}℃｜{{ currentAreaData?.outSideHumidity || '-' }}%
                </AButton>
                <AFlex>
                  <div @click="areaEditorRef?.showView" v-if="booleanPermission(OperatePermission.编辑平面图)">
                    <AFlex justify="center" align="center" class="button-icon">
                      <SvgIcon name="edit-o" />
                    </AFlex>
                  </div>
                  <div @click="copyRegion">
                    <AFlex justify="center" align="center" class="button-icon">
                      <SvgIcon name="copy" />
                    </AFlex>
                  </div>
                </AFlex>
              </AFlex>
              <div class="canvas-content">
                <AButton class="icon-button icon-button-margin home-temp-humidity-button">
                  <SvgIcon name="home" />
                  {{ currentAreaData?.avgTemperature || '-' }}℃｜{{ currentAreaData?.avgHumidity || '-' }}%
                </AButton>
                <AreaPreview
                  v-if="regionList.length"
                  ref="areaPreview"
                  :area-data="currentAreaData"
                  @highlight-env-point="highlightEnvPoint"
                />
              </div>
            </div>
          </AFlex>
        </AFlex>
      </div>

      <EnvMonitorList
        ref="envMonitorList"
        v-show="!listDisplay"
        :monitor-data="monitoringList"
        :monitoring-point-data="monitoringPointData"
      />

      <ADrawer
        width="600"
        :open="monitoringPointOpen"
        :closable="false"
        class="drawer-monitoring"
        :header-style="headerStyle"
        :footer-style="footerStyle"
      >
        <template #title
          >{{ titleMonitoring ? $t('envMonitor.addInspectionPoints') : $t('envMonitor.editorialMonitoringPoint') }}
        </template>
        <template #extra>
          <SvgIcon class="off-icon" @click="offDrawer" name="close" />
        </template>
        <AForm ref="formRef" class="form-ref" :model="monitoringForm" layout="vertical" :rules="rules">
          <AFormItem name="name">
            <AInput
              v-model:value="monitoringForm.name"
              class="input-wdith region-bottom"
              :placeholder="$t('common.pleaseEnter')"
            />
          </AFormItem>
          <AFormItem :label="$t('envMonitor.region')" name="regionId">
            <AFlex align="center">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.regionId"
                :options="groupRegions"
                :field-names="{ label: 'regionName', value: 'id' }"
                :placeholder="$t('common.plzSelect')"
                @change="addRegionList"
              />

              <div @click="editingRegionName">
                <AFlex justify="center" align="center" class="button-flex">
                  <SvgIcon name="edit-o" />
                </AFlex>
              </div>
              <div @click="addRegionName">
                <AFlex justify="center" align="center" class="button-flex button-plus">
                  <SvgIcon name="plus" />
                </AFlex>
              </div>
            </AFlex>
          </AFormItem>
          <AFormItem :label="t('envMonitor.humidityTemperatureControl')" name="tempHumidityControlMode">
            <ARadioGroup v-model:value="monitoringForm.tempHumidityControlMode" class="radio-group">
              <ARadio value="2">{{ $t('envMonitor.returnControl') }}</ARadio>
              <!-- <ARadio value="1">{{ $t('envMonitor.supplyControl') }}</ARadio> -->
            </ARadioGroup>
          </AFormItem>

          <AFlex justify="space-between">
            <div>
              <AFormItem
                class="form-item"
                :label="$t('envMonitor.returnTemperatureAndhumidity')"
                name="returnDevGroupId"
              >
                <ASelect
                  class="input-wdith"
                  v-model:value="monitoringForm.returnDevGroupId"
                  :options="twoDeviceGroup"
                  :field-names="{ label: 'groupName', value: 'id' }"
                  :placeholder="$t('common.plzSelect', { name: t('createDevice.groupName') })"
                  @change="(value, option) => adddDeviceGroup(value, option, HumitureType.ReturnAir)"
                />
              </AFormItem>
              <AFormItem name="returnDevId">
                <ASelect
                  class="input-wdith"
                  v-model:value="monitoringForm.returnDevId"
                  :options="returnDevicesList"
                  :field-names="{ label: 'deviceName', value: 'id' }"
                  :placeholder="$t('common.plzSelect', { name: t('deviceList.equipmentName') })"
                  @change="(value, option) => adddDevice(value, option, HumitureType.ReturnAir)"
                />
              </AFormItem>
              <AFormItem name="returnTempParamCode">
                <ASelect
                  class="input-wdith"
                  v-model:value="monitoringForm.returnTempParamCode"
                  :options="returnDeviceParamsList"
                  :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
                  :placeholder="
                    $t('common.plzSelect', { name: t('envMonitor.temperature') + t('createDevice.parameters') })
                  "
                />
              </AFormItem>
              <AFormItem name="returnHumidityParamCode">
                <ASelect
                  class="input-wdith"
                  v-model:value="monitoringForm.returnHumidityParamCode"
                  :options="returnDeviceParamsList"
                  :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
                  :placeholder="
                    $t('common.plzSelect', { name: t('envMonitor.humidity') + t('createDevice.parameters') })
                  "
                />
              </AFormItem>
            </div>
            <div>
              <AFormItem :label="$t('envMonitor.supplyTemperatureAndhumidity')" name="supplyDevGroupId">
                <ASelect
                  class="input-wdith"
                  v-model:value="monitoringForm.supplyDevGroupId"
                  :options="twoDeviceGroup"
                  :field-names="{ label: 'groupName', value: 'id' }"
                  :placeholder="$t('common.plzSelect', { name: t('createDevice.groupName') })"
                  @change="(value, option) => adddDeviceGroup(value, option, HumitureType.SupplyAir)"
                />
              </AFormItem>
              <AFormItem name="supplyDevId">
                <ASelect
                  class="input-wdith"
                  v-model:value="monitoringForm.supplyDevId"
                  :options="supplyDevicesList"
                  :field-names="{ label: 'deviceName', value: 'id' }"
                  :placeholder="$t('common.plzSelect', { name: t('deviceList.equipmentName') })"
                  @change="(value, option) => adddDevice(value, option, HumitureType.SupplyAir)"
                />
              </AFormItem>
              <AFormItem name="supplyTempParamCode">
                <ASelect
                  class="input-wdith"
                  v-model:value="monitoringForm.supplyTempParamCode"
                  :options="supplyDeviceParamsList"
                  :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
                  :placeholder="
                    $t('common.plzSelect', { name: t('envMonitor.temperature') + t('createDevice.parameters') })
                  "
                />
              </AFormItem>
              <AFormItem name="supplyHumidityParamCode">
                <ASelect
                  class="input-wdith"
                  v-model:value="monitoringForm.supplyHumidityParamCode"
                  :options="supplyDeviceParamsList"
                  :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
                  :placeholder="
                    $t('common.plzSelect', { name: t('envMonitor.humidity') + t('createDevice.parameters') })
                  "
                />
              </AFormItem>
            </div>
          </AFlex>
          <div v-if="monitoringForm.tempHumidityControlMode === '1'">
            <AFormItem
              class="form-item"
              :label="t('envMonitor.newAirTemperatureAndHumidityMeter')"
              name="outdoorDevGroupId"
            >
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.outdoorDevGroupId"
                :options="twoDeviceGroup"
                :field-names="{ label: 'groupName', value: 'id' }"
                :placeholder="$t('common.plzSelect', { name: t('createDevice.groupName') })"
                @change="(value, option) => adddDeviceGroup(value, option, HumitureType.FreshAir)"
              />
            </AFormItem>
            <AFormItem name="outdoorDevId">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.outdoorDevId"
                :options="freshDevicesList"
                :field-names="{ label: 'deviceName', value: 'id' }"
                :placeholder="$t('common.plzSelect', { name: t('deviceList.equipmentName') })"
                @change="(value, option) => adddDevice(value, option, HumitureType.FreshAir)"
              />
            </AFormItem>
            <AFormItem name="outdoorTempParamCode">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.outdoorTempParamCode"
                :options="freshDeviceParamsList"
                :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
                :placeholder="
                  $t('common.plzSelect', { name: t('envMonitor.temperature') + t('createDevice.parameters') })
                "
              />
            </AFormItem>
            <AFormItem name="outdoorHumidityParamCode">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.outdoorHumidityParamCode"
                :options="freshDeviceParamsList"
                :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
                :placeholder="$t('common.plzSelect', { name: t('envMonitor.humidity') + t('createDevice.parameters') })"
              />
            </AFormItem>
          </div>

          <AFlex>
            <div class="spacing-right">
              <AFormItem
                name="tempUpper"
                :label="
                  monitoringForm.tempHumidityControlMode === '1'
                    ? $t('envMonitor.fanTemperatureSetting')
                    : $t('envMonitor.indoorTemperatureConfiguration')
                "
              >
                <AFlex align="center">
                  <AInputNumber
                    class="input-number-width"
                    :placeholder="$t('common.pleaseEnter')"
                    v-model:value="monitoringForm.tempUpper"
                    :min="0"
                    :max="999"
                  />
                  <div class="configure-text">{{ $t('envMonitor.upperLimitValue') }}</div>
                </AFlex>
              </AFormItem>
              <AFormItem name="tempLower">
                <AFlex align="center">
                  <AInputNumber
                    class="input-number-width"
                    :placeholder="$t('common.pleaseEnter')"
                    v-model:value="monitoringForm.tempLower"
                    :min="0"
                    :max="999"
                  />
                  <div class="configure-text">{{ $t('envMonitor.lowerLimitValue') }}</div>
                </AFlex>
              </AFormItem>
              <AFormItem name="tempPreset">
                <AFlex align="center">
                  <AInputNumber
                    class="input-number-width"
                    v-model:value="monitoringForm.tempPreset"
                    :min="0"
                    :max="999"
                    :placeholder="$t('common.pleaseEnter')"
                  />
                  <div class="configure-text">{{ $t('envMonitor.limitValue') }}</div>
                </AFlex>
              </AFormItem>
            </div>
            <div>
              <AFormItem
                name="humidityUpper"
                :label="
                  monitoringForm.tempHumidityControlMode === '1'
                    ? t('envMonitor.fanAirHumiditySetting')
                    : $t('envMonitor.indoorHumiditySetting')
                "
              >
                <AFlex align="center">
                  <AInputNumber
                    class="input-number-width"
                    v-model:value="monitoringForm.humidityUpper"
                    :min="0"
                    :max="999"
                    :placeholder="$t('common.pleaseEnter')"
                  />
                  <div class="configure-text">{{ $t('envMonitor.upperLimitValue') }}</div>
                </AFlex>
              </AFormItem>
              <AFormItem name="humidityLower">
                <AFlex align="center">
                  <AInputNumber
                    class="input-number-width"
                    v-model:value="monitoringForm.humidityLower"
                    :min="0"
                    :max="999"
                    :placeholder="$t('common.pleaseEnter')"
                  />
                  <div class="configure-text">{{ $t('envMonitor.lowerLimitValue') }}</div>
                </AFlex>
              </AFormItem>
              <AFormItem name="humidityPreset">
                <AFlex align="center">
                  <AInputNumber
                    class="input-number-width"
                    v-model:value="monitoringForm.humidityPreset"
                    :min="0"
                    :max="999"
                    :placeholder="$t('common.pleaseEnter')"
                  />
                  <div class="configure-text">{{ $t('envMonitor.limitValue') }}</div>
                </AFlex>
              </AFormItem>
            </div>
          </AFlex>
          <AFormItem :label="t('envMonitor.monitoringPointStatusConfiguration')" name="runStatusFlag">
            <ARadioGroup v-model:value="monitoringForm.runStatusFlag" class="radio-group">
              <ARadio :value="0">{{ t('envMonitor.temperatureDifferenceJudgment') }}</ARadio>
              <ARadio :value="1">{{ t('envMonitor.operationStatusDetermination') }}</ARadio>
            </ARadioGroup>
          </AFormItem>
          <AFlex v-if="monitoringForm.runStatusFlag === 0">
            <AFormItem name="supplyReturnTempDiff">
              <AFlex align="center" class="spacing">
                <AInputNumber
                  class="input-number-width"
                  v-model:value="monitoringForm.supplyReturnTempDiff"
                  :min="0"
                  :max="999"
                  :placeholder="$t('common.pleaseEnter')"
                />
                <div class="configure-text">{{ t('envMonitor.returnAirTemperatureDifference') }}</div>
              </AFlex>
            </AFormItem>
            <AFormItem name="supplyUpperTempDiff">
              <AFlex align="center">
                <AInputNumber
                  class="input-number-width"
                  v-model:value="monitoringForm.supplyUpperTempDiff"
                  :min="0"
                  :max="999"
                  :placeholder="$t('common.pleaseEnter')"
                />
                <div class="configure-text">{{ t('envMonitor.upperLimitAirSupplyTemperatureDifference') }}</div>
              </AFlex>
            </AFormItem>
          </AFlex>
          <div v-else>
            <AFormItem name="runStatusDevGroupId">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.runStatusDevGroupId"
                :options="twoDeviceGroup"
                :field-names="{ label: 'groupName', value: 'id' }"
                :placeholder="$t('common.plzSelect', { name: t('createDevice.groupName') })"
                @change="(value, option) => adddDeviceGroup(value, option, HumitureType.OperatingStatus)"
              />
            </AFormItem>
            <AFormItem name="runStatusDevId">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.runStatusDevId"
                :options="runDevicesList"
                :field-names="{ label: 'deviceName', value: 'id' }"
                :placeholder="$t('common.plzSelect', { name: t('deviceList.equipmentName') })"
                @change="(value, option) => adddRunStatusDevice(value, option)"
              />
            </AFormItem>
            <AFormItem name="runStatusParamCode">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.runStatusParamCode"
                :options="runDeviceParamsList"
                :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
                :placeholder="$t('common.plzSelect', { name: t('alarmManage.equipmentParameters') })"
                @change="(value, option) => adddParametersDevice(value, option)"
              />
            </AFormItem>
            <AFormItem name="runStatusConditionCode">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.runStatusConditionCode"
                :options="inputType === 1 ? temperatureDifference : paramAlgOperator"
                :placeholder="$t('common.plzSelect', { name: t('alarmManage.operator') })"
                :field-names="{ label: 'dictValue', value: 'dictValue' }"
              />
            </AFormItem>
            <AFormItem v-if="inputType === 1" name="runStatusConditionValue">
              <ASelect
                class="input-wdith"
                v-model:value="monitoringForm.runStatusConditionValue"
                :options="runStatusList"
                :placeholder="$t('common.plzSelect')"
                :field-names="{ label: 'name', value: 'name' }"
              />
            </AFormItem>

            <AFormItem v-else name="runStatusConditionValue">
              <AInputNumber
                class="input-wdith"
                v-model:value="monitoringForm.runStatusConditionValue"
                :min="0"
                :max="999"
                :placeholder="$t('common.pleaseEnter')"
              />
            </AFormItem>
          </div>
        </AForm>
        <template #footer>
          <AFlex justify="flex-end" :gap="16">
            <AButton
              v-if="booleanPermission(OperatePermission.删除监测点)"
              class="default-button"
              @click="deleteMonitoringPoint"
              >{{ $t('common.delete') }}</AButton
            >
            <AButton type="primary" @click="saveMonitoringPoint">{{ $t('common.save') }}</AButton>
          </AFlex>
        </template>
      </ADrawer>

      <ADrawer
        class="drawer-monitoring"
        width="304"
        :open="outdoorOpen"
        :closable="false"
        :header-style="headerStyle"
        :footer-style="footerStyle"
      >
        <template #title>{{ $t('envMonitor.outdoorTemperatureAndHumidity') }}</template>
        <template #extra>
          <SvgIcon class="off-icon" @click="offOutdoorDrawer" name="close" />
        </template>
        <AForm ref="formOutdoorRef" :model="outdooForm" layout="vertical">
          <AFormItem :label="$t('envMonitor.outdoorTemperatureAndHumidityMeter')" name="outsideDevGroupId">
            <ASelect
              class="input-wdith"
              v-model:value="outdooForm.outsideDevGroupId"
              :options="twoDeviceGroup"
              :field-names="{ label: 'groupName', value: 'id' }"
              :placeholder="$t('common.plzSelect', { name: t('createDevice.groupName') })"
              @change="(value, option) => adddDeviceGroup(value, option, HumitureType.Outdoor)"
            />
          </AFormItem>
          <AFormItem name="outsideDevId">
            <ASelect
              class="input-wdith"
              v-model:value="outdooForm.outsideDevId"
              :options="outdoorDevicesList"
              :field-names="{ label: 'deviceName', value: 'id' }"
              :placeholder="$t('common.plzSelect', { name: t('deviceList.equipmentName') })"
              @change="(value, option) => adddDevice(value, option, HumitureType.Outdoor)"
            />
          </AFormItem>
          <AFormItem name="outsideTempParamCode">
            <ASelect
              class="input-wdith"
              v-model:value="outdooForm.outsideTempParamCode"
              :options="outdoorDeviceParamsList"
              :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
              :placeholder="
                $t('common.plzSelect', { name: t('envMonitor.temperature') + t('createDevice.parameters') })
              "
            />
          </AFormItem>
          <AFormItem name="outsideHumidityParamCode">
            <ASelect
              class="input-wdith"
              v-model:value="outdooForm.outsideHumidityParamCode"
              :options="outdoorDeviceParamsList"
              :field-names="{ label: 'deviceParamName', value: 'deviceParamCode' }"
              :placeholder="$t('common.plzSelect', { name: t('envMonitor.humidity') + t('createDevice.parameters') })"
            />
          </AFormItem>

          <AFormItem name="outsideEnthalpyParamCode">
            <ASelect
              class="input-wdith"
              v-model:value="outdooForm.outsideEnthalpyParamCode"
              :placeholder="$t('common.plzSelect', { name: t('envMonitor.hanValue') })"
            >
              <ASelectOption value="温度">{{ t('envMonitor.temperature') }}</ASelectOption>
              <ASelectOption value="湿度">{{ t('envMonitor.humidity') }}</ASelectOption>
            </ASelect>
          </AFormItem>
        </AForm>
        <template #footer>
          <AFlex justify="flex-end" :gap="16">
            <AButton type="primary" @click="saveOutdoo">{{ $t('common.save') }}</AButton>
          </AFlex>
        </template>
      </ADrawer>

      <ADrawer
        width="612"
        :open="monitoringDataOpen"
        :closable="false"
        class="drawer-monitoring"
        :header-style="headerStyle"
        :footer-style="footerStyle"
      >
        <template #title>{{ monitoringName }}</template>
        <template #extra>
          <SvgIcon class="off-icon" @click="offMonitoringDrawer" name="close" />
        </template>
        <HumitureCurve
          :monitoring-id="monitoringId"
          :monitoring-data="monitoringPointData"
          :set-show="true"
          :width="'580px'"
          :height="'700px'"
        />
      </ADrawer>

      <AModal
        v-model:open="regionNameOpen"
        :title="titleRegions ? $t('envMonitor.addArea') : $t('envMonitor.editArea')"
        :footer="null"
        width="460px"
        :mask-closable="false"
        :keyboard="false"
      >
        <div class="region-name">{{ $t('envMonitor.regionName') }}</div>
        <AInput v-model:value="regionName" :placeholder="$t('common.pleaseEnter')" />

        <AFlex justify="flex-end" class="region-name-top">
          <AButton v-if="!titleRegions" class="default-button" @click="regionNameDelete">{{
            $t('common.delete')
          }}</AButton>
          <AButton class="default-button cancel-button" @click="regionNameOpen = false">{{
            $t('common.cancel')
          }}</AButton>
          <AButton type="primary" @click="regionNameOk">{{ $t('common.confirm') }}</AButton>
        </AFlex>
      </AModal>

      <AModal
        v-model:open="regionCopyOpen"
        :title="$t('envMonitor.copyPanel')"
        :footer="null"
        width="460px"
        :mask-closable="false"
        :keyboard="false"
      >
        <div class="region-name">{{ $t('envMonitor.selectCopyArea') }}</div>
        <ASelect
          v-model:value="copyToRegionId"
          style="width: 100%"
          :options="copyToRegionList"
          :field-names="{ label: 'name', value: 'id' }"
          :placeholder="$t('common.plzSelect')"
        />
        <AFlex justify="flex-end" class="region-name-top">
          <AButton class="default-button cancel-button" @click="regionCopyOpen = false">{{
            $t('common.cancel')
          }}</AButton>
          <AButton type="primary" @click="copyAreaCanvas">{{ $t('common.confirm') }}</AButton>
        </AFlex>
      </AModal>
      <AreaEditor
        ref="areaEditor"
        :area-data="currentAreaData"
        @open-outdoor-drawer="addOutdoorDrawer"
        @save-area-canvas="saveAreaCanvas"
      />
    </ASpin>
  </div>
</template>

<style lang="scss" scoped>
.spacing {
  margin-right: 74px;
}

.spacing-right {
  margin-right: 102px;
}

.background-default {
  height: 40px;
  background-color: #fff;
}

.background-alarm {
  height: 40px;
  background-color: rgb(245 108 108 / 15%);
}

.confirm-axis-div {
  margin-left: -3px;
}

.confirm-axis-circle {
  width: 10px;
  height: 10px;
  background: #32bac0;
  border-radius: 50%;
}

.return-currently {
  margin-left: 10px;
  color: #32bac0;
}

.timeline-confirm {
  width: 76px;
  height: 32px;
  margin-right: 24px;
  margin-left: 10px;
  border-radius: 16px;
}

.scroll-wrapper {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.scroll-content {
  display: inline-block; /* 关键：横向布局 */
  white-space: nowrap; /* 禁止内容换行 */
}

.time-style {
  margin-left: -10px;
  font-size: 10px;
  font-style: normal;
  font-weight: 400;
  color: rgb(0 0 0 / 50%);
  text-align: left;
}

.time-line {
  height: 39px;
  border-bottom: 1px solid #979797;
}

.confirm-axis {
  width: 1px;
  height: 20px;
  border: 1px solid #32bac0;
}

.integral-style {
  width: 31px;
  height: 20px;
  cursor: pointer;
}

.integral-height {
  width: 1px;
  height: 5px;
  border: 1px solid #979797;
}

.integral {
  width: 1px;
  height: 10px;
  border: 1px solid #979797;
}

.icon-button-margin {
  margin: 16px 0 0 16px;
}

.canvas-div-top {
  margin-bottom: 16px;
  margin-left: 16px;
}

.canvas-div {
  width: 820px;
}

.button-icon {
  width: 32px;
  height: 32px;
  margin-left: 12px;
  font-size: 16px;
  color: var(--antd-color-primary);
  cursor: pointer;
  background: #fff;
  border: 1px solid #32bac0;
  border-radius: 4px;
}

.canvas-content {
  position: relative;
  width: 820px;
  height: 660px;
  background: #f5f7fa;
  border-radius: 12px;
  outline: 1px solid var(--antd-color-primary);
}

.home-temp-humidity-button {
  position: absolute;
}

.list-regions {
  height: 100%;
  margin-right: 16px;
}

.content-monitoring-canvas-left {
  width: 260px;
  padding-right: 30px;
  padding-bottom: 24px;
  overflow: hidden;
  overflow: hidden auto; /* 隐藏水平滚动条 */ /* 只显示垂直滚动条 */
}

.monitoring-img {
  width: 100%;
  height: 100%;
  background-image: radial-gradient(circle, #d8d8d8 1px, #fff 1px);
  background-position: center center;
  background-size: 15px 15px;
}

.content-monitoring-canvas {
  height: calc(100% - 45px);
  padding-top: 24px;
}

.content-monitoring-top {
  height: 40px;
}

.drawer-monitoring .form-ref .ant-form-item .ant-form-item-label > label {
  color: #666;
}

.configure-text {
  margin-left: 12px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: #666;
  text-align: left;
}

.radio-group {
  margin: 8px 0 10px;
}

.region-bottom {
  margin-bottom: 8px;
}

.drawer-monitoring .ant-form-item {
  margin-bottom: 16px;
}

.input-number-width {
  width: 140px;

  // margin-bottom: 16px;
}

.segmented-monitoring {
  width: 196px;
  margin-bottom: 24px;
}

.off-icon {
  cursor: pointer;
}

.cancel-button {
  margin: 0 16px;
}

.region-name-top {
  margin-top: 40px;
}

.region-name {
  margin-top: 16px;
  margin-bottom: 5px;
  color: #666;
}

.button-plus {
  margin-left: 12px !important;
  font-size: 16px;
}

.button-flex {
  width: 32px;
  height: 32px;
  margin-left: 16px;
  cursor: pointer;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.input-wdith {
  width: 256px;
}

.button-monitoring {
  margin-left: 16px;
}

.content-monitoring {
  height: calc(100vh - 85px);

  // min-height: 100%;
  padding: 24px 0 0 24px; // 上、右、下、左
  margin-top: 16px;

  // overflow: hidden;
  background-color: #fff;
  border-radius: 16px;
}

.select-monitoring {
  margin-right: 16px;
  margin-left: 32px;
}

.select-width {
  width: 192px;
}

.text-top {
  font-size: 20px;
  font-style: normal;
  font-weight: 500;
  line-height: 32px;
  color: rgb(0 0 0 / 85%);
  text-align: left;
}
</style>
