<template>
  <div>
    <!-- 基础组件 -->
    <BasicComponent
      :disaster-type="DisasterType.RAINSTORM"
      :key="route.fullPath"
    />

    <!-- 灾害链影响列表组件 -->
    <DisasterChainPointComponent
      v-if="
        statusStore.appLoadingCompleted &&
        statusStore.uiComponents.disasterChainPointShow.loading
      "
      :select-options="selectOptions"
      :table-data-list="tableDatas"
      :table-columns="tableColumns"
      :page-option="paginationConfig"
      @change-conditions="changeConditions"
      @change-current-page="changeCurrentPage"
    />

    <!-- 左侧按钮组件 -->
    <LeftButtonComponent
      v-if="
        statusStore.appLoadingCompleted &&
        statusStore.uiComponents.leftButton.loading
      "
      :button-list="leftButtonInfo"
    />

    <!-- 左侧图例组件 -->
    <LeftLegendComponent
      v-if="
        statusStore.appLoadingCompleted &&
        statusStore.uiComponents.leftLegend.loading
      "
    />

    <!-- 右侧按钮组件 -->
    <RightButtonComponent
      v-if="
        statusStore.appLoadingCompleted &&
        statusStore.uiComponents.rightButton.loading
      "
      :button-list="rightButtonInfo"
    />

    <!-- 控制显示组件 -->
    <ControlShowComponent :constrol-show-list="controlPanel" />

    <!-- 控制显示详情组件 -->
    <ControlShowDetailComponent />

    <!-- 功能组件 -->
    <FunctionComponent />

    <!-- 步骤组件 -->
    <StepComponent />
  </div>
</template>

<script setup lang="ts">
  import BasicComponent from '@/component/rain-earthquake/BasicComponent.vue';
  import ControlShowComponent from '@/component/rain-earthquake/ControlShowComponent.vue';
  import ControlShowDetailComponent from '@/component/rain-earthquake/ControlShowDetailComponent.vue';
  import DisasterChainPointComponent from '@/component/rain-earthquake/DisasterChainPointComponent.vue';
  import FunctionComponent from '@/component/rain-earthquake/FunctionComponent.vue';
  import LeftButtonComponent from '@/component/rain-earthquake/LeftButtonComponent.vue';
  import LeftLegendComponent from '@/component/rain-earthquake/LeftLegendComponent.vue';
  import RightButtonComponent from '@/component/rain-earthquake/RightButtonComponent.vue';
  import StepComponent from '@/component/rain-earthquake/StepComponent.vue';
  import { useRainDisasterChain } from '@/hooks/rainstorm/useRainDisasterChain';
  import { useAroundAnalysis } from '@/hooks/rain-earthquake/useAroundAnalysis';
  import type { AroundAnalysisState } from '@/types/common/useAroundAnalysisType';
  import type { PointResource } from '@/types/common/useAroundAnalysisType';
  import type { XianHiddenDangerSpots } from '@/types/base/XianHiddenDangerSpots';
  import {
    useDisasterChainTable,
    type SearchConditions,
  } from '@/hooks/useDisasterChainTable';
  import { useStatusStore } from '@/stores/useStatusStore';
  import {
    DisasterType,
    PointType,
    HiddenDangerPointTypeMap,
  } from '@/types/common/DisasterType.ts';
  import { onBeforeMount, watch, provide } from 'vue';
  import { useRoute } from 'vue-router';

  const route = useRoute();

  const { leftButtonInfo, rightButtonInfo, controlPanel } =
    useRainDisasterChain();

  const statusStore = useStatusStore();

  // 在父组件中创建 useAroundAnalysis 实例，并通过 provide 提供给子组件
  const aroundAnalysisState = useAroundAnalysis();
  provide<AroundAnalysisState>('aroundAnalysisState', aroundAnalysisState);

  const {
    selectOptions,
    tableColumns,
    tableDatas,
    paginationConfig,
    conditions,
    changeConditions,
    setConditions,
    changeCurrentPage,
    setSelectOptions,
    setTableColumns,
    setTableDatas,
  } = useDisasterChainTable();

  onBeforeMount(() => {
    // 设置下拉选项
    setSelectOptions([
      { value: PointType.LANDSLIDE, label: '滑坡' },
      { value: PointType.DEBRIS_FLOW, label: '泥石流' },
      { value: PointType.WATER_LOGGING, label: '内涝' },
      { value: PointType.FLASH_FLOOD, label: '山洪' },
      { value: PointType.COLLAPSE, label: '崩塌' },
    ]);

    // 设置表格列配置
    setTableColumns([
      { title: '名称', key: 'disasterName' },
      { title: '位置', key: 'position' },
      { title: '规模等级', key: 'scaleGrade' },
      { title: '险情等级', key: 'riskGrade' },
    ]);

    /**
     * 条件改变执行
     * @param value
     */
    changeConditions.value = (value: SearchConditions) => {
      setConditions(value);
    };
  });

    // 监听脉冲点变化和下拉选项变化，过滤并更新表格数据
  watch(
    [
      () => aroundAnalysisState.pulsePoints.value,
      () => conditions.value.hiddenPoint,
    ],
    ([newPulsePoints, hiddenPointType]: [PointResource[], PointType]) => {
      console.log('=== 脉冲点变化 ===');
      console.log('newPulsePoints:', newPulsePoints);
      console.log('newPulsePoints.length:', newPulsePoints?.length);
      console.log('hiddenPointType:', hiddenPointType);

      if (newPulsePoints && newPulsePoints.length > 0) {
        // 根据选中的隐患点类型过滤
        const englishType = HiddenDangerPointTypeMap[hiddenPointType];
        const filteredPoints = newPulsePoints.filter(point => {
          if (point.category === 'hidden-danger') {
            return point.originalType === englishType;
          }
          if (
            hiddenPointType === PointType.RISK_AREA &&
            point.category === 'risk-point'
          ) {
            return true;
          }
          return false;
        });

        // 将 PointResource 转换为 XianHiddenDangerSpots 格式
        const convertedData: XianHiddenDangerSpots[] = filteredPoints.map(
          point => ({
            id:
              typeof point.id === 'number'
                ? point.id
                : parseInt(String(point.id), 10),
            name: point.value,
            disasterName: point.value,
            position:
              point.lon !== undefined && point.lat !== undefined
                ? `${point.lon.toFixed(4)}, ${point.lat.toFixed(4)}`
                : '未知位置',
            scaleGrade: String(point.scale_grade || '未知'),
            riskGrade: String(point.risk_grade || '一般'),
            lon: point.lon,
            lat: point.lat,
            fieldCode: String(point.id),
            province: '陕西省',
            city: '西安市',
            county: '',
            village: '',
            isDelete: 0,
          })
        );

        console.log('convertedData:', convertedData);
        setTableDatas(convertedData);
      } else {
        // 如果没有脉冲点，则清空表格数据
        console.log('清空表格数据');
        setTableDatas([]);
      }
    },
    { immediate: true, deep: true }
  );
</script>

<style scoped></style>