<template>
  <a-modal
    :open="visible"
    :title="title"
    width="80vw"
    :footer="null"
    :closable="true"
    @cancel="handleClose"
    :destroyOnClose="true"
    class="map-modal"
  >
    <div v-if="modelStore.showStcdSelector" class="stcd-selector-wrapper">
      <a-select
        v-model:value="modelStore.params.stcd"
        placeholder="请选择测站"
        style="width: 240px; margin-bottom: 12px"
        :options="modelStore.stcdOptions"
        show-search
        :filter-option="filterOption"
        @change="handleStcdChange"
      >
      </a-select>
    </div>
    <a-tabs :active-key="currentActiveKey" @change="onTabChange">
      <a-tab-pane v-for="tab in tabsConfig" :key="tab.key" :tab="tab.name">
      </a-tab-pane>
      <template #rightExtra>
        <a-tooltip :title="!isEngConfig ? '' : '该电站无专题配置'">
          <a-button type="primary" :disabled="isEngConfig">
            <i class="icon iconfont icon-topic mr-[5px]"></i>
            电站专题
          </a-button></a-tooltip
        >
      </template>
    </a-tabs>
    <!-- 内容区域 - 使用动态组件 + keep-alive 实现按需加载和缓存 -->
    <keep-alive>
      <div class="content">
        <!-- 基本信息 -->
        <BasicInfo
          v-show="currentActiveKey === 'basicInfo'"
          :url="getTabUrl('basicInfo')"
          :is-active="currentActiveKey === 'basicInfo'"
        />
        <!-- 实时视频 -->
        <VideoInfo
          v-show="currentActiveKey === 'videoInfo'"
          :is-active="currentActiveKey === 'videoInfo'"
        />
        <!-- 全景影像 -->
        <PanoramaInfo
          v-show="currentActiveKey === 'panoramaInfo'"
          :url="getTabUrl('panoramaInfo')"
          :is-active="currentActiveKey === 'panoramaInfo'"
        />
        <!-- 监测数据 -->
        <MonitorInfo
          v-show="currentActiveKey === 'monitorInfo'"
          :is-active="currentActiveKey === 'monitorInfo'"
          :code="getTabCode('monitorInfo')"
        />
        <!-- 预警提示 -->
        <EarlyWarningAlert
          v-show="currentActiveKey === 'tableTabs'"
          :tabs-items="getTabChildren('tableTabs')"
          :is-active="currentActiveKey === 'tableTabs'"
        />
        <!-- 鱼类繁殖适宜性分析 -->
        <WaterTemperatureRep
          v-show="currentActiveKey === 'WaterTemperatureRep'"
          :is-active="currentActiveKey === 'WaterTemperatureRep'"
        />
        <!-- 查看报告 -->
        <Attachment
          v-show="currentActiveKey === 'attachment'"
          :is-active="currentActiveKey === 'attachment'"
          tabKey="attachment"
          :show-download="false"
          :url="getTabUrl('attachment')"
        />
        <!-- 批复文件 -->
        <Attachment
          v-show="currentActiveKey === 'approval'"
          :is-active="currentActiveKey === 'approval'"
          tabKey="approval"
          :show-download="true"
          :url="getTabUrl('approval')"
        />
      </div>
    </keep-alive>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, computed } from 'vue';
// 导入预定义的 Tab 内容组件
import BasicInfo from './components/BasicInfo.vue'; // 基本信息
import VideoInfo from './components/videoInfo.vue'; // 实时视频
import PanoramaInfo from './components/PanoramaInfo.vue'; // 全景影像
import MonitorInfo from './components/MonitorInfo.vue'; // 监测数据
import EarlyWarningAlert from './components/EarlyWarningAlert.vue'; // 预警提示
import Attachment from './components/Attachment.vue'; // 查看报告/批复文件
import WaterTemperatureRep from './components/WaterTemperatureRep.vue'; // 水温对比数据
import { useModelStore } from '@/store/modules/model';
import { handleTabs } from './setting.config';

const modelStore = useModelStore();
const tabsConfig = ref([]);
// 判断是否显示电站专题配置
const isEngConfig = ref(true);
// import MapView from './components/MapView.vue';
// import SurroundingInfo from './components/SurroundingInfo.vue';

// 定义 Tab 配置项接口
interface TabItem {
  key: string;
  title: string;
  url: string;
}
// 获取 Tab 配置项的 URL
const getTabUrl = (key: string) => {
  const tab = tabsConfig.value.find((item: any) => item.key === key);
  return tab?.url || '';
};
// 获取 Tab 配置项的子 Tab
const getTabChildren = (key: string) => {
  console.log(tabsConfig.value);
  const tab = tabsConfig.value.find((item: any) => item.key === key);
  return tab?.tabs || [];
};
// 获取 Tab 配置项的 code
const getTabCode = (key: string) => {
  const tab = tabsConfig.value.find((item: any) => item.key === key);
  return tab?.code || '';
};
// 定义 Props
const props = defineProps<{
  visible: boolean;
  title?: string;
  activeKey?: string; // 外部控制的当前激活 tab
  data?: any; // 可选：传递给内部组件的数据
}>();

// 定义 Emits
// 添加 'update:activeKey' 以支持 v-model:active-key
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'change', key: string): void;
}>();

// 内部维护的 activeKey
const currentActiveKey = ref<string>('');

// 监听外部传入的 activeKey 变化，同步到内部状态
watch(
  () => props.activeKey,
  newVal => {
    if (newVal && newVal !== currentActiveKey.value) {
      currentActiveKey.value = newVal;
    }
  },
  { immediate: true }
);
watch(
  () => modelStore.params,
  newVal => {
    if (!newVal || Object.keys(newVal).length === 0) return;
    console.log(newVal);
    tabsConfig.value = handleTabs(newVal);
    let value = tabsConfig.value.find((item: any) => item.default);
    currentActiveKey.value = value?.key;
  },
  { deep: true, immediate: true }
);
// 监听内部 tab 切换
const onTabChange = (key: string) => {
  currentActiveKey.value = key;
  // 通知父组件更新 activeKey (支持 v-model)
  // 通知父组件发生了切换事件 (用于业务逻辑，如加载数据)
  emit('change', key);
};

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false);
  modelStore.params = {};
  // 清理状态,避免影响下次打开
  modelStore.showStcdSelector = false;
  modelStore.stcdOptions = [];
};

// 为了方便模板中使用，将 props.data 暴露给模板
const modalData = ref(props.data);
watch(
  () => props.data,
  newVal => {
    modalData.value = newVal;
  }
);
// 搜索过滤函数
const filterOption = (input: string, option: any) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 处理测站切换
const handleStcdChange = (newStcd: string) => {
  console.log('【测站切换】', newStcd);
  // 由于 BasicInfo.vue 监听了 stcd 变化,这里只需更新 store
  // 如果需要刷新所有 tab 的数据,可以在这里触发事件
};
</script>

<style lang="scss" scoped>
.map-modal {
  .content {
    min-height: 600px;
  }
}
</style>
