<template>
  <DefaultLayout>
    <!-- banner -->
    <section class="banner-section">
      <img src="@assets/cases-banner.png" alt="" srcset="">
    </section>

    <!-- 案例详情内容 -->
    <section class="case-details">
      <div class="container">
        <div class="content-wrapper">
          <!-- 左侧菜单 -->
          <div class="sidebar">
            <div v-if="loading" class="loading-container">
              <div class="loading-text">加载中...</div>
            </div>
            <div v-else-if="menuItems.length === 0" class="empty-container">
              <div class="empty-text">暂无案例数据</div>
            </div>
            <div v-else class="menu-list">
              <div v-for="item in menuItems" :key="item.id" class="menu-item"
                :class="{ 'has-children': item.children && item.children.length > 0 }">
                <!-- 一级菜单 -->
                <div class="menu-title" :class="{
                  'active': isMenuActive(item),
                  'expanded': expandedMenus.includes(item.id)
                }" @click="handleMenuClick(item)">
                  <span>{{ item.title }}</span>
                  <img src="@assets/arrow-down.svg" v-if="item.children && item.children.length > 0" class="expand-icon"
                    :class="{ 'expanded': expandedMenus.includes(item.id) }" alt="" srcset="">
                  <!-- <i v-if="item.children && item.children.length > 0" class="expand-icon"
                    :class="{ 'expanded': expandedMenus.includes(item.id) }">▼</i> -->
                </div>

                <!-- 二级菜单 -->
                <div v-if="item.children && item.children.length > 0" class="submenu"
                  :class="{ 'expanded': expandedMenus.includes(item.id) }">
                  <div v-for="child in item.children" :key="child.id" class="submenu-item"
                    :class="{ 'active': currentCaseId === child.id }" @click="selectCase(child)">
                    {{ child.title }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧内容 -->
          <div class="main-content">
            <div class="case-content">
              <h1 class="case-title">{{ currentCase?.title || '' }}</h1>
              <div class="case-body" v-html="currentCase?.content || ''"></div>
              <img :src="imgHost + currentCase?.image" style="max-width: 100%;" alt="" srcset="">

              <!-- 导航按钮 -->
              <div class="navigation">
                <div class="nav-item prev-nav">
                  <span class="nav-label">上一篇：</span>
                  <span class="nav-title" :class="{ 'disabled': !prevCase }" @click="goToPrevCase">
                    {{ prevCase ? prevCase.title : '没有了' }}
                  </span>
                </div>

                <div class="nav-item next-nav">
                  <span class="nav-label">下一篇：</span>
                  <span class="nav-title" :class="{ 'disabled': !nextCase }" @click="goToNextCase">
                    {{ nextCase ? nextCase.title : '没有了' }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </DefaultLayout>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import DefaultLayout from '@/layouts/DefaultLayout.vue'
import { getProjectClassifyTree, getProjectList } from '@/api/modules/home'

export default {
  name: 'CaseDetailsPage',
  components: {
    DefaultLayout
  },
  setup() {
    // 环境变量
    const imgHost = import.meta.env.VITE_APP_IMG_HOST
    const route = useRoute()
    const router = useRouter()

    const currentCaseId = ref(null)
    const expandedMenus = ref([])
    const searchKeyword = ref('')
    const loading = ref(false)
    const isUpdatingRoute = ref(false) // 标记是否正在更新路由

    // 案例菜单数据 - 从API获取
    const menuItems = ref([])

    // 当前选中的案例
    const currentCase = ref(null)

    // 获取左侧分类树数据
    const fetchMenuData = async () => {
      try {
        loading.value = true
        const response = await getProjectClassifyTree({
          classifyType: 2 // 2：行业案例
        })
        // console.log('左侧分类树数据', response.rows)

        if (response.rows && response.rows.length > 0) {
          // 转换API数据格式为组件需要的格式
          menuItems.value = response.rows.map(item => {
            // 如果有children，使用children数据
            if (item.children && item.children.length > 0) {
              return {
                id: `category_${item.id}`, // 给分类添加前缀避免ID冲突
                originalId: item.id,
                title: item.classifyName || item.name,
                type: 'category',
                children: item.children.map(child => ({
                  id: `project_${child.id}`, // 给项目添加前缀避免ID冲突
                  originalId: child.id,
                  title: child.projectName || child.name,
                  projectType: child.projectType,
                  type: 'project',
                  // 标记这个项目需要通过API获取详细内容
                  needFetchDetail: true
                }))
              }
            } else {
              // 如果没有children，该分类本身就是一个可点击的项目
              return {
                id: `category_${item.id}`, // 给分类添加前缀避免ID冲突
                originalId: item.id,
                title: item.classifyName || item.name,
                classifyId: item.id, // 使用分类ID作为classifyId
                type: 'category',
                // 标记需要通过classifyId获取该分类下的项目列表
                needFetchByClassify: true,
                children: []
              }
            }
          })
        }
      } catch (error) {
        console.error('获取分类数据失败:', error)
        menuItems.value = []
      } finally {
        loading.value = false
      }
    }

    // 获取案例详情数据（通过ID）
    const fetchCaseDetail = async (projectId) => {
      try {
        const response = await getProjectList({
          projectType: 2, // 2：行业案例
          id: projectId,
        })
        // console.log('response.rows', response.rows)
        if (response.rows && response.rows.length > 0) {
          const caseData = response.rows[0]
          // console.log('caseData', caseData)
          return {
            id: caseData.id,
            title: caseData.projectName || '未命名案例',
            content: caseData.projectDescribe || caseData.projectProfile || '<p>暂无详细内容</p>',
            image: caseData.projectImage
          }
        }
        return null
      } catch (error) {
        console.error('获取案例详情失败:', error)
        return null
      }
    }

    // 搜索过滤后的菜单项
    const filteredMenuItems = computed(() => {
      if (!searchKeyword.value) {
        return menuItems.value
      }

      return menuItems.value.filter(item => {
        const titleMatch = item.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
        const childrenMatch = item.children && item.children.some(child =>
          child.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
        )
        return titleMatch || childrenMatch
      })
    })

    // 扁平化所有案例（用于上一篇/下一篇导航）
    const flattenedCases = computed(() => {
      const cases = []
      menuItems.value.forEach(menu => {
        if (menu.children && menu.children.length > 0) {
          // 有子菜单的情况，添加所有子项
          cases.push(...menu.children)
        } else if (menu.needFetchByClassify || menu.content) {
          // 没有子菜单但需要获取数据或有内容的情况，添加菜单项本身
          cases.push(menu)
        }
      })
      return cases
    })

    // 当前案例的索引
    const currentCaseIndex = computed(() => {
      return flattenedCases.value.findIndex(c => c.id === currentCaseId.value)
    })

    // 上一篇案例
    const prevCase = computed(() => {
      const index = currentCaseIndex.value
      return index > 0 ? flattenedCases.value[index - 1] : null
    })

    // 下一篇案例
    const nextCase = computed(() => {
      const index = currentCaseIndex.value
      return index < flattenedCases.value.length - 1 ? flattenedCases.value[index + 1] : null
    })

    // 判断菜单是否激活
    const isMenuActive = (menu) => {
      if (menu.children && menu.children.length > 0) {
        // 有子菜单的情况：检查是否有子项被选中
        return menu.children.some(child => child.id === currentCaseId.value)
      } else {
        // 没有子菜单的情况：检查自身是否被选中
        // 对于needFetchByClassify的情况，可能当前选中的是该分类下的某个项目
        return menu.id === currentCaseId.value
      }
    }

    // 处理菜单点击
    const handleMenuClick = (menu) => {
      // console.log('处理菜单点击', menu)
      if (menu.children && menu.children.length > 0) {
        // 有子菜单的情况：切换展开/收起状态
        const index = expandedMenus.value.indexOf(menu.id)
        if (index > -1) {
          expandedMenus.value.splice(index, 1)
        } else {
          expandedMenus.value.push(menu.id)
        }
      } else {
        // 没有子菜单的情况：直接选中该菜单项
        selectCase(menu)
      }
    }

    // 选择案例
    const selectCase = async (caseItem, skipRouteUpdate = false) => {
      // console.log('选择案例', caseItem)

      // 如果当前已经是这个案例，直接返回
      if (currentCaseId.value === caseItem.id) {
        return
      }

      currentCaseId.value = caseItem.id

      try {
        // 如果需要通过classifyId获取该分类下的项目列表
        if (caseItem.needFetchByClassify && caseItem.classifyId) {
          const response = await getProjectList({
            projectType: 2, // 2：行业案例
            classifyId: caseItem.classifyId
          })

          if (response.rows && response.rows.length > 0) {
            // 取第一个项目作为默认显示内容，但保持分类ID作为当前案例ID
            const caseData = response.rows[0]
            currentCase.value = {
              id: caseItem.id, // 使用分类ID，而不是项目ID
              title: caseData.projectName || caseItem.title,
              content: caseData.projectDescribe || caseData.projectProfile || '<p>暂无详细内容</p>',
              image: caseData.projectImage
            }
            // 保持分类ID作为当前案例ID，不要被项目ID覆盖
            // currentCaseId.value 已经在函数开始时设置为 caseItem.id
          } else {
            // 如果API没有返回数据，显示分类信息
            currentCase.value = {
              id: caseItem.id,
              title: caseItem.title,
              content: '<p>该分类下暂无案例</p>'
            }
          }
        }
        // 如果需要获取详细内容（从左侧菜单点击的项目）
        else if (caseItem.needFetchDetail) {
          const response = await getProjectList({
            projectType: 2, // 2：行业案例
            id: caseItem.originalId || caseItem.id // 使用原始ID进行API调用
          })

          if (response.rows && response.rows.length > 0) {
            const caseData = response.rows[0]
            currentCase.value = {
              id: caseItem.id, // 保持带前缀的ID用于界面状态
              title: caseData.projectName || caseItem.title,
              content: caseData.projectDescribe || caseData.projectProfile || '<p>暂无详细内容</p>',
              image: caseData.projectImage
            }
          } else {
            // 如果API没有返回数据，使用基本信息
            currentCase.value = {
              id: caseItem.id,
              title: caseItem.title,
              content: '<p>暂无详细内容</p>'
            }
          }
        } else {
          // 直接使用传入的案例数据
          currentCase.value = caseItem
        }
      } catch (error) {
        console.error('获取案例数据失败:', error)
        currentCase.value = {
          id: caseItem.id,
          title: caseItem.title,
          content: '<p>获取内容失败，请稍后重试</p>'
        }
      }

      // 更新URL（除非明确跳过）
      if (!skipRouteUpdate) {
        isUpdatingRoute.value = true
        // 使用原始ID更新路由，而不是带前缀的ID
        const routeId = caseItem.originalId || (typeof caseItem.id === 'string' && caseItem.id.includes('_')
          ? caseItem.id.split('_')[1]
          : caseItem.id)
        // console.log('开始更新路由到ID:', routeId)

        await router.replace({
          name: 'Casesdetails',
          query: { id: routeId }
        })

        // console.log('路由更新完成')
        // 延迟重置标志，确保路由更新完成
        setTimeout(() => {
          isUpdatingRoute.value = false
          // console.log('路由更新标志重置')
        }, 200) // 增加延迟时间
      }
    }

    // 搜索处理
    const handleSearch = () => {
      // 搜索时自动展开所有匹配的菜单
      if (searchKeyword.value) {
        const expandIds = []
        menuItems.value.forEach(menu => {
          if (menu.children && menu.children.length > 0) {
            const hasMatch = menu.children.some(child =>
              child.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
            )
            if (hasMatch || menu.title.toLowerCase().includes(searchKeyword.value.toLowerCase())) {
              expandIds.push(menu.id)
            }
          }
        })
        expandedMenus.value = expandIds
      }
    }

    // 上一篇
    const goToPrevCase = () => {
      if (prevCase.value) {
        selectCase(prevCase.value)
      }
    }

    // 下一篇
    const goToNextCase = () => {
      if (nextCase.value) {
        selectCase(nextCase.value)
      }
    }

    // 根据classifyId判断分类是否有children
    const getClassifyInfo = (classifyId) => {
      const id = parseInt(classifyId)
      return menuItems.value.find(menu => menu.originalId === id)
    }

    // 根据ID和classifyId获取案例详情
    const fetchCaseDetailByParams = async (caseId, classifyId) => {
      const id = parseInt(caseId)
      const classify = getClassifyInfo(classifyId)

      // console.log('根据参数获取案例详情', { caseId, classifyId, classify })

      if (classify) {
        if (classify.children && classify.children.length > 0) {
          // 有children的情况：直接通过项目ID获取详情
          // console.log('分类有children，通过项目ID获取详情')
          const response = await getProjectList({
            projectType: 2,
            id: id
          })

          if (response.rows && response.rows.length > 0) {
            const caseData = response.rows[0]
            return {
              id: `project_${id}`,
              originalId: id,
              title: caseData.projectName || '未命名案例',
              content: caseData.projectDescribe || caseData.projectProfile || '<p>暂无详细内容</p>',
              image: caseData.projectImage,
              type: 'project',
              needFetchDetail: true
            }
          }
        } else {
          // 没有children的情况：通过classifyId获取该分类下的项目列表
          // console.log('分类没有children，通过classifyId获取分类下的项目')
          const response = await getProjectList({
            projectType: 2,
            classifyId: parseInt(classifyId)
          })

          if (response.rows && response.rows.length > 0) {
            // 如果传入了具体的项目ID，查找对应的项目
            let caseData = response.rows[0] // 默认取第一个
            if (id) {
              const foundProject = response.rows.find(item => item.id === id)
              if (foundProject) {
                caseData = foundProject
              }
            }

            return {
              id: `category_${classifyId}`,
              originalId: parseInt(classifyId),
              title: caseData.projectName || classify.title,
              content: caseData.projectDescribe || caseData.projectProfile || '<p>暂无详细内容</p>',
              image: caseData.projectImage,
              type: 'category',
              classifyId: parseInt(classifyId),
              needFetchByClassify: true
            }
          }
        }
      }

      return null
    }

    // 根据ID查找并高亮案例
    const findAndHighlightCase = async (caseId, classifyId = null, skipRouteUpdate = false) => {
      const id = parseInt(caseId) || caseId // 支持字符串ID
      // console.log('查找并高亮案例', { caseId, classifyId, id, skipRouteUpdate })

      let foundCase = null
      let parentMenuId = null

      // 如果提供了classifyId，使用新的逻辑
      if (classifyId) {
        // console.log('使用classifyId逻辑获取案例详情')
        const caseDetail = await fetchCaseDetailByParams(caseId, classifyId)
        if (caseDetail) {
          // 查找对应的菜单项来设置高亮和展开状态
          const classify = getClassifyInfo(classifyId)
          if (classify) {
            if (classify.children && classify.children.length > 0) {
              // 有children的情况：高亮对应的子项
              const childCase = classify.children.find(child => child.originalId === parseInt(caseId))
              if (childCase) {
                foundCase = childCase
                parentMenuId = classify.id
              }
            } else {
              // 没有children的情况：高亮分类本身
              foundCase = classify
            }
          }

          // 设置当前案例
          currentCaseId.value = caseDetail.id
          currentCase.value = caseDetail
        }
      } else {
        // 原有的查找逻辑
        for (const menu of menuItems.value) {
          if (menu.children && menu.children.length > 0) {
            // 在子菜单中查找 - 匹配原始ID
            const found = menu.children.find(child =>
              child.originalId === id || child.id === id || child.id === `project_${id}`
            )
            if (found) {
              foundCase = found
              parentMenuId = menu.id
              break
            }
          } else {
            // 在一级菜单中查找 - 匹配原始ID
            if (menu.originalId === id || menu.id === id || menu.id === `category_${id}`) {
              foundCase = menu
              break
            }
          }
        }

        if (foundCase) {
          // console.log('找到案例', foundCase)
          // 选中案例
          await selectCase(foundCase, skipRouteUpdate)
          return
        } else {
          // console.log('在菜单中没找到案例，尝试直接获取详情')
          // 如果在菜单中没找到，可能是直接通过URL访问，尝试直接获取详情
          const caseDetail = await fetchCaseDetail(id)
          if (caseDetail) {
            // 为直接访问的案例创建一个临时的带前缀ID
            const tempId = `direct_${id}`
            currentCaseId.value = tempId
            currentCase.value = {
              ...caseDetail,
              id: tempId
            }
          }
          return
        }
      }

      // 展开父菜单（如果有的话）
      if (parentMenuId && !expandedMenus.value.includes(parentMenuId)) {
        expandedMenus.value.push(parentMenuId)
      }
    }

    // 监听路由变化
    watch(() => [route.query.id, route.query.classifyId], async ([newId, newClassifyId], [oldId, oldClassifyId]) => {
      // console.log('路由变化监听', {
      //   newId, newClassifyId, oldId, oldClassifyId,
      //   currentCaseId: currentCaseId.value,
      //   isUpdatingRoute: isUpdatingRoute.value
      // })

      // 如果正在更新路由，跳过处理
      if (isUpdatingRoute.value) {
        // console.log('正在更新路由，跳过处理')
        return
      }

      // 检查当前案例ID是否匹配新的路由ID（考虑前缀）
      const currentOriginalId = currentCaseId.value && typeof currentCaseId.value === 'string' && currentCaseId.value.includes('_')
        ? currentCaseId.value.split('_')[1]
        : currentCaseId.value

      if (newId && parseInt(newId) === parseInt(currentOriginalId) &&
        (!newClassifyId || newClassifyId === oldClassifyId)) {
        // console.log('新ID和当前案例原始ID相同，跳过处理')
        return
      }

      // 只有当ID真正发生变化且菜单数据已加载时才执行
      if (newId && (newId !== oldId || newClassifyId !== oldClassifyId) && menuItems.value.length > 0) {
        // console.log('执行路由变化处理')
        await findAndHighlightCase(newId, newClassifyId, true) // 跳过路由更新，因为这是由路由变化触发的
      }
    })

    onMounted(async () => {
      // 首先获取菜单数据
      await fetchMenuData()

      // 初始化时根据URL参数加载案例
      const caseId = route.query.id
      const classifyId = route.query.classifyId

      if (caseId) {
        await findAndHighlightCase(caseId, classifyId)
      } else {
        // 默认选择第一个案例并展开其父菜单
        const firstCase = flattenedCases.value[0]
        if (firstCase) {
          // 找到第一个案例的父菜单并展开（如果有父菜单的话）
          for (const menu of menuItems.value) {
            if (menu.children && menu.children.some(child => child.id === firstCase.id)) {
              if (!expandedMenus.value.includes(menu.id)) {
                expandedMenus.value.push(menu.id)
              }
              break
            }
          }
          await selectCase(firstCase)
        }
      }
    })

    return {
      imgHost,
      currentCaseId,
      currentCase,
      menuItems,
      filteredMenuItems,
      expandedMenus,
      searchKeyword,
      loading,
      isUpdatingRoute,
      prevCase,
      nextCase,
      isMenuActive,
      handleMenuClick,
      selectCase,
      handleSearch,
      goToPrevCase,
      goToNextCase,
      fetchMenuData,
      fetchCaseDetail
    }
  }
}
</script>

<style lang="scss" scoped>
// banner区域
.banner-section {
  position: relative;

  img {
    width: 100%;
  }
}

// 案例详情区域
.case-details {
  padding: 40px 0 80px;
  background: #F5F9FF;
  position: relative;

  &::before {
    position: absolute;
    content: '';
    left: 0;
    right: 0;
    top: 0;
    bottom: -138px;
    background: #F5F9FF;
    background-size: cover;
  }

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .content-wrapper {
    display: flex;
    gap: 30px;
    align-items: flex-start;
  }

  // 左侧菜单
  .sidebar {
    width: 280px;
    position: sticky;
    top: 105px;

    .loading-container,
    .empty-container {
      padding: 40px 20px;
      text-align: center;
      background: #fff;
      border-radius: 8px;

      .loading-text,
      .empty-text {
        color: #666;
        font-size: 14px;
      }
    }

    .menu-list {
      .menu-item {
        margin-bottom: 0;

        .menu-title {
          padding: 15px 20px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: 500;
          color: #333;
          transition: all 0.3s ease;
          margin-bottom: 17px;
          background: #fff;
          height: 48px;

          &:hover {
            border-color: #4a90e2;
            color: #4a90e2;
          }

          &.active {
            border-color: #4a90e2;
            color: #0054FF;
            background: linear-gradient(to right, #CAE0FF, #E4EFFF);
          }

          .expand-icon {
            font-size: 12px;
            transition: transform 0.3s ease;
            color: #999;
            width: 25px;
            height: auto;

            &.expanded {
              transform: rotate(180deg);
            }
          }
        }

        .submenu {
          max-height: 0;
          overflow: hidden;
          transition: max-height 0.3s ease;

          &.expanded {
            max-height: 500px;
          }

          .submenu-item {
            padding: 12px 20px;
            cursor: pointer;
            color: #666;
            font-size: 14px;
            transition: all 0.3s ease;
            margin-bottom: 15px;
            margin-left: 20px;
            background: #fff;

            &:hover {
              border-color: #4a90e2;
              color: #4a90e2;
            }

            &.active {
              border-color: #0054FF;
              color: #4a90e2;
              background: linear-gradient(to right, #CAE0FF, #E4EFFF);
              font-weight: 500;
            }
          }
        }
      }
    }
  }

  // 右侧内容
  .main-content {
    flex: 1;
    padding: 30px;
    background: #fff;

    .case-content {
      .case-title {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 30px;
        text-align: center;
        border-bottom: 2px dashed #ccc;
        padding-bottom: 15px;
      }

      .case-body {
        line-height: 1.8;
        color: #555;
        margin-bottom: 40px;

        h3 {
          font-size: 18px;
          font-weight: bold;
          color: #333;
          margin: 25px 0 15px;
        }

        :deep(p) {
          margin-bottom: 15px;
          text-align: justify;
          text-indent: 2em;
        }

        strong {
          color: #333;
          font-weight: 600;
        }

        :deep(img) {
          max-width: 100%;
          height: auto;
          display: block;
          margin: 20px auto;
          border-radius: 8px;
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
      }

      .navigation {
        display: flex;
        justify-content: space-between;
        padding-top: 20px;

        .nav-item {
          display: flex;
          align-items: center;
          font-size: 14px;

          .nav-label {
            color: #666;
            margin-right: 5px;
          }

          .nav-title {
            color: #4a90e2;
            cursor: pointer;
            transition: color 0.3s ease;

            &:hover:not(.disabled) {
              color: #2c5aa0;
              text-decoration: underline;
            }

            &.disabled {
              color: #999;
              cursor: not-allowed;
            }
          }
        }

        .next-nav {
          text-align: right;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .case-details {
    padding: 20px 0 40px;

    .content-wrapper {
      flex-direction: column;
      gap: 20px;
    }

    .sidebar {
      width: 100%;
      position: static;
    }

    .main-content {
      .case-content {
        padding: 20px;

        .case-title {
          font-size: 24px;
        }

        .navigation {
          flex-direction: column;
          gap: 15px;

          .nav-btn {
            max-width: 100%;
            align-items: center;
          }
        }
      }
    }
  }
}
</style>