<template>
  <div class="xmdak-detail-container">
    <!-- 主 Tab 切换区域 -->
    <div class="main-tab-wrapper">
      <div class="main-tab-container">
        <div
          v-for="(tab, index) in tabs"
          :key="index"
          :class="['main-tab-item', { active: activeTab === index }]"
          @click="switchTab(index)"
        >
          <span class="tab-label">{{ tab.label }}</span>
        </div>
      </div>
    </div>

    <!-- 子项导航区域 -->
    <div class="sub-tab-wrapper">
      <div class="sub-tab-container">
        <div
          v-for="(item, idx) in currentTabChildren"
          :key="idx"
          :class="['sub-tab-item', { active: activeSubItem === item.name }]"
          @click="handleSubItemClick(item)"
        >
          <span class="sub-tab-label">{{ item.title }}</span>
        </div>
      </div>
    </div>

    <!-- 详情内容区域 -->
    <div class="detail-section">
      <div v-if="isLoading" class="loading-overlay">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在加载...</span>
      </div>
      <div v-else class="detail-content">
        <component
          :is="currentComponent"
          v-if="currentComponent"
          :project-id="projectId"
          :projectLzType="projectLzType"
          :key="activeTab + activeSubItem"
        />
        <div v-else class="empty-content">
          <el-empty description="请选择上方功能模块">
            <template #image>
              <el-icon :size="80"><Document /></el-icon>
            </template>
          </el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  markRaw,
  onMounted,
  watch,
  getCurrentInstance,
} from "vue";
import { useRoute } from "vue-router";
import { useProjectInfoStore } from "@/stores/projectInfo";

const { proxy } = getCurrentInstance();
const projectInfoStore = useProjectInfoStore();
import {
  Document,
  FolderOpened,
  Management,
  Finished,
  Loading,
} from "@element-plus/icons-vue";

const route = useRoute();

// Tab 配置
const tabs = ref([
  {
    label: "投前管理",
    key: "projectManage",
    icon: markRaw(FolderOpened),
  },
  {
    label: "投中管理",
    key: "investingManage",
    icon: markRaw(Management),
  },
  {
    label: "投后管理",
    key: "castbehind",
    icon: markRaw(Finished),
  },
]);

// 当前激活的 Tab
const activeTab = ref(0);
// 当前激活的子项
const activeSubItem = ref("");
// 当前组件
const currentComponent = ref(null);
const isLoading = ref(false);

// 获取 projectId
const projectId = ref(route.query.projectId || "");
// 获取项目流转类型
const projectLzType = route.query.projectLzType || "";

// sessionStorage 缓存 key
const STORAGE_KEY = "xmdak_detail_tab_state";

// 保存当前 tab 状态到 sessionStorage
const saveTabState = () => {
  const state = {
    projectId: projectId.value,
    activeTab: activeTab.value,
    activeSubItem: activeSubItem.value,
  };
  sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state));
};

// 从 sessionStorage 恢复 tab 状态
const restoreTabState = () => {
  try {
    const raw = sessionStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const state = JSON.parse(raw);
    // 只在 projectId 一致时恢复，不同项目不恢复
    if (state.projectId === projectId.value) {
      return state;
    }
    // projectId 不一致，清除旧缓存
    sessionStorage.removeItem(STORAGE_KEY);
    return null;
  } catch {
    return null;
  }
};

// 路由配置 - 使用Add结尾的详情组件
const routeChildren = {
  projectManage: [
    {
      name: "projectDraft",
      title: "项目遴选",
      desc: "项目初选与评估",
      importFn: () => import("@/views/projectManage/addProject.vue"),
    },
    {
      name: "projectSetUp",
      title: "项目立项",
      desc: "项目立项申请",
      importFn: () => import("@/views/projectManage/addProject.vue"),
    },
    {
      name: "projectArgument",
      title: "项目论证",
      desc: "项目论证分析",
      importFn: () => import("@/views/projectManage/addProject.vue"),
    },
    {
      name: "projectDecision",
      title: "项目决策",
      desc: "项目投资决策",
      importFn: () => import("@/views/projectManage/addProject.vue"),
    },
  ],
  investingManage: [
    {
      name: "targetLiabilityStatement",
      title: "投资目标责任书",
      desc: "投资目标责任管理",
      importFn: () =>
        import("@/views/investingManage/targetLiabilityStatement.vue"),
    },
    {
      name: "targetControl",
      title: "投资控制",
      desc: "投资过程控制",
      importFn: () => import("@/views/investingManage/targetControl.vue"),
    },
    {
      name: "majorRisk",
      title: "重大风险防控",
      desc: "风险识别与防控",
      importFn: () => import("@/views/investingManage/majorRisk.vue"),
    },
    {
      name: "constructionTime",
      title: "建设期投资回收",
      desc: "建设期资金回收",
      importFn: () => import("@/views/investingManage/constructionTime.vue"),
    },
    {
      name: "construction",
      title: "建设期投资检查",
      desc: "建设期投资监督",
      importFn: () => import("@/views/investingManage/construction.vue"),
    },
    {
      name: "bigIssues",
      title: "重大事项审批",
      desc: "重大事项审批流程",
      importFn: () => import("@/views/investingManage/bigIssues.vue"),
    },
    {
      name: "quit",
      title: "项目退出",
      desc: "项目退出管理",
      importFn: () => import("@/views/investingManage/quit.vue"),
    },
    {
      name: "decision",
      title: "重新决策",
      desc: "重新决策评估",
      importFn: () => import("@/views/investingManage/decision.vue"),
    },
  ],
  castbehind: [
    {
      name: "investmentCecovery",
      title: "运营期投资回收",
      desc: "运营期收益回收",
      importFn: () => import("@/views/castbehind/investmentCecovery.vue"),
    },
    {
      name: "runningPeriod",
      title: "运营期投资检查",
      desc: "运营期监督检查",
      importFn: () => import("@/views/castbehind/runningPeriod.vue"),
    },
    {
      name: "evaluate",
      title: "投资后评价",
      desc: "投资效果评价",
      importFn: () => import("@/views/castbehind/evaluate.vue"),
    },
    {
      name: "turnover",
      title: "移交管理",
      desc: "项目移交管理",
      importFn: () => import("@/views/castbehind/turnover.vue"),
    },
  ],
};

// 获取当前 Tab 的子项
const currentTabChildren = computed(() => {
  const currentKey = tabs.value[activeTab.value].key;
  return routeChildren[currentKey] || [];
});

// 请求项目详情并保存到 sessionStorage
const fetchProjectInfo = () => {
  if (!projectId.value) return;
  projectInfoStore.fetchProjectInfo(proxy, projectId.value);
};

// 初始化：优先恢复缓存状态，否则加载默认 tab
onMounted(async () => {
  if (projectId.value) {
    // 请求项目详情并缓存
    fetchProjectInfo();

    const saved = restoreTabState();
    if (saved && saved.activeTab !== undefined && saved.activeSubItem) {
      // 恢复之前离开的位置
      activeTab.value = saved.activeTab;
      const children = routeChildren[tabs.value[saved.activeTab].key];
      const targetItem = children?.find((c) => c.name === saved.activeSubItem);
      if (targetItem) {
        await handleSubItemClick(targetItem, false);
      } else {
        await switchTab(saved.activeTab);
      }
    } else {
      await switchTab(0);
    }
  }
});

// 切换 Tab
const switchTab = async (index) => {
  activeTab.value = index;

  // 获取当前Tab的第一个子项
  const children = routeChildren[tabs.value[index].key];
  if (children && children.length > 0) {
    await handleSubItemClick(children[0]);
  } else {
    activeSubItem.value = "";
    currentComponent.value = null;
  }
};

// 处理子项点击 - 直接加载详情组件
const handleSubItemClick = async (item, shouldSave = true) => {
  if (!projectId.value) {
    console.warn("缺少 projectId 参数");
    return;
  }

  activeSubItem.value = item.name;
  isLoading.value = true;
  currentComponent.value = null;

  // 切换后保存状态
  if (shouldSave) {
    saveTabState();
  }

  try {
    const module = await item.importFn();
    currentComponent.value = markRaw(module.default);
  } catch (error) {
    console.error("组件加载失败:", error);
    currentComponent.value = null;
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped lang="scss">
.xmdak-detail-container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.detail-section {
  .tab-content {
    padding: 16px !important;
  }
  ::v-deep .add-project-back {
    display: none;
  }
  ::v-deep .navigation-wrapper {
    display: none;
  }
  ::v-deep .tab-content {
    padding-top: 16px;
  }
  ::v-deep .el-tabs__header {
    padding: 8px 0 0 16px;
  }
}

.main-tab-wrapper {
  background: white;
  padding: 0;
  position: sticky;
  top: 0;
  z-index: 100;
  border-bottom: 1px solid #e8f4fd;
}

.main-tab-container {
  display: flex;
  max-width: 1400px;
  margin: 0 auto;
  gap: 4px;
  background: transparent;
  padding: 0 20px;
}

.main-tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  margin-top: 0;

  .tab-label {
    font-size: 14px;
    font-weight: 500;
    color: #5a6c7d;
    letter-spacing: 0.5px;
    transition: all 0.3s ease;
    position: relative;
    z-index: 1;
  }

  &::before {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: transparent;
    transition: all 0.3s ease;
  }

  &:hover {
    background: #f8fbff;

    .tab-label {
      color: #0056b3;
    }

    &::before {
      background: #4dabf7;
      opacity: 0.6;
    }
  }

  &.active {
    background: white;

    .tab-label {
      color: #0056b3;
      font-weight: 600;
    }

    &::before {
      background: #0056b3;
    }
  }
}

// 子项导航区域
.sub-tab-wrapper {
  background: #ffffff;
  border-bottom: 1px solid #e8f4fd;
  padding: 8px 24px;
  position: sticky;
  top: 46px;
  z-index: 99;
}

.sub-tab-container {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  max-width: 1400px;
  margin: 0 auto;
  justify-content: center;
}

.sub-tab-item {
  display: flex;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  border: 1px solid #e8f4fd;
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      rgba(77, 171, 247, 0.05),
      rgba(0, 86, 179, 0.05)
    );
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  .sub-tab-label {
    font-size: 14px;
    color: #5a6c7d;
    font-weight: 500;
    transition: all 0.3s ease;
    position: relative;
    z-index: 1;
    letter-spacing: 0.3px;
  }

  &:hover {
    border-color: #4dabf7;
    transform: translateY(-1px);

    &::before {
      opacity: 1;
    }

    .sub-tab-label {
      color: #0056b3;
    }
  }

  &.active {
    background: #0056b3;
    border-color: #0056b3;
    transform: translateY(-1px);

    &::before {
      background: transparent;
    }

    .sub-tab-label {
      color: white;
      font-weight: 600;
    }
  }
}

// 详情内容区域
.detail-section {
  flex: 1;
  background: #f5f7fa;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.loading-overlay {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #0056b3;
  font-size: 16px;

  .el-icon {
    font-size: 40px;
    margin-bottom: 16px;
    color: #0056b3;
  }
}

.detail-content {
  flex: 1;
  overflow-y: auto;
  // padding: 20px;
  min-height: 500px;
}

.empty-content {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 500px;
  background: white;
  border-radius: 4px;

  .el-icon {
    color: #0056b3;
    opacity: 0.3;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .main-tab-item {
    padding: 12px 16px;

    .tab-label {
      font-size: 14px;
    }
  }

  .sub-tab-container {
    gap: 6px;
  }

  .sub-tab-item {
    padding: 8px 14px;

    .sub-tab-label {
      font-size: 14px;
    }
  }
}
</style>
