<template>
  <div class="real-pages">
    <div>
      <div class="real-info">
        <div class="title">{{ dataInfo.title }}</div>
        <div class="time">{{ dataInfo.releaseTime }}</div>
        <div v-if="dataInfo.content" class="real-html" v-html="dataInfo.content"></div>
      </div>
    </div>
    <el-affix :offset="0">
      <div class="related-bos">
        <div class="related-box">
          <div class="flex-row-between related-title">
            <div>相关专题</div>
            <div class="flex-row-start related-huan" @click="getList">
              <el-icon><Sort /></el-icon>
              <div style="margin-left: 4px">换一换</div>
            </div>
          </div>
          <div class="procure-bos">
            <div v-for="(item, index) in dataList" :key="index" class="procure-list" @click="onPath('/plan_info/guide?id=' + item.id)">
              <img :src="item.coverImage" alt="" />
              <div class="procure1">{{ item.title }}</div>
              <div class="procure2">{{ item.releaseTime }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-affix>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute, onBeforeRouteUpdate } from 'vue-router';
import { getPurchaseGuideDetail, getPurchaseGuideList } from '@/api/plan/index';
import { onPath } from '@/utils/siteConfig';

const route = useRoute();
const id = ref<any>(null);
const dataInfo = ref<any>({});
const dataList = ref<any>([]);

// 封装获取详情的逻辑
const getInfo = () => {
  // 防御性编程：如果 id 为空，可以不请求或清空数据
  if (!id.value) return;

  // 可选：添加 loading 状态或清空旧数据以避免视觉残留
  // dataInfo.value = {};

  getPurchaseGuideDetail(id.value).then((res) => {
    if (res.code == 200) {
      console.log('详情数据已更新，ID:', id.value);
      dataInfo.value = res.data;
    }
  });
};

// 封装获取列表的逻辑
const getList = () => {
  getPurchaseGuideList({
    pageSize: 10,
    pageNum: 1
  }).then((res) => {
    if (res.code == 200) {
      if (res.rows && res.rows.length > 0) {
        if (res.rows.length <= 2) {
          dataList.value = res.rows;
        } else {
          dataList.value = getRandomElements(res.rows, 3);
        }
      }
    }
  });
};

// 核心修复：统一初始化函数
const initData = () => {
  // 1. 【关键步骤】先从路由获取最新的 ID
  id.value = route.query.id;
  console.log('当前路由 ID 已更新为:', id.value);

  // 2. 再请求数据
  getInfo();
  getList();
};

onMounted(() => {
  initData();
});

// 修复后的路由更新监听
onBeforeRouteUpdate((to, from, next) => {
  // 执行初始化逻辑（包含更新 id 和请求数据）
  initData();
  next();
});

function getRandomElements(arr: any, count: any) {
  if (count > arr.length) {
    throw new Error('要取的数量不能超过数组长度');
  }
  const copy = [...arr];
  const result = [];
  for (let i = 0; i < count; i++) {
    const randomIndex = Math.floor(Math.random() * copy.length);
    result.push(copy.splice(randomIndex, 1)[0]);
  }
  return result;
}
</script>

<style lang="scss" scoped>
.real-pages {
  width: 1200px;
  margin: 0 auto;
  display: flex;
  gap: 0 20px;
  padding-bottom: 50px;
  .real-info {
    width: 715px;
    background: #ffffff;
    border-radius: 10px;
    padding: 20px;
    .title {
      font-size: 20px;
      color: #666666;
    }
    .time {
      font-size: 14px;
      color: #999999;
      margin: 10px 0 18px 0;
    }
    .real-html {
      width: 679px;
      :deep(img) {
        max-width: 100%;
        height: auto;
      }
    }
    .img {
      width: 679px;
      height: 351px;
      border-radius: 10px;
    }
    .head {
      font-weight: 600;
      font-size: 14px;
      color: #101828;
      margin: 10px 0 18px 0;
    }
    .info {
      font-size: 14px;
      color: #364153;
      margin-bottom: 15px;
    }
  }

  .related-bos {
    flex: 1;
    .related-box {
      width: 100%;
      background-color: #ffffff;
      border-radius: 10px;
      padding: 20px;
      .related-title {
        font-size: 16px;
        color: #666666;
        .related-huan {
          font-size: 14px;
          cursor: pointer;
        }
      }
      // 采购指南
      .procure-bos {
        width: 100%;
        display: flex;
        flex-direction: column;
        margin-top: 12px;
        gap: 12px 0px;
        .procure-list {
          width: 100%;
          height: 268px;
          background: #ffffff;
          cursor: pointer;
          border-radius: 10px;
          overflow: hidden;
          border: 1px solid #d0d5dd;
          img {
            width: 100%;
            height: 200px;
            border-bottom: 1px solid #d0d5dd;
          }
          .procure1 {
            padding: 12px 0 4px 20px;
            font-weight: 600;
            font-size: 14px;
            color: #101828;
          }
          .procure2 {
            padding-left: 20px;
            font-size: 12px;
            color: #364153;
          }
        }
      }
    }
  }
}
</style>
