<template>
  <div class="home-wrapper">
    <div class="home-main" ref="containerRef">
      <div class="home-top-bg"></div>
      <div class="to-back">
        <div class="to-back-btn" @click="goToAllThinkTank">
          <div class="back-image">
            <img src="../assets/images/arrow-left.png" />
          </div>
          <div class="back-text">
            {{ "返回" }}
          </div>
        </div>
      </div>
      <div class="item-box">
        <div class="box-header">
          <div class="box-header-text">
            <div class="box-title">{{ "美国科技智库" }}</div>
            <div class="number-btn">
              <div class="number-text">
                {{ total }}{{ "家" }}
              </div>
            </div>
          </div>
          <div class="select-box">
            <div class="search-box">
              <el-input placeholder="搜索智库" v-model="searchPolicy" @keyup.enter="handleGetThinkTankList()">
                <template #suffix>
                  <img src="../assets/images/Line_Search.png" class="search-icon" alt="搜索"
                    @click="handleGetThinkTankList()">
                </template>
              </el-input>

            </div>
            <div class="select-box-sort">
              <el-select v-model="sort" placeholder="报告数量" :teleported="true" :placement="'bottom-start'"
                :popper-options="{
                  modifiers: [
                    {
                      name: 'preventOverflow', // 禁用自动翻转逻辑
                      options: {
                        mainAxis: false, // 禁用垂直方向的自动调整
                        altAxis: false, // 禁用水平方向的自动调整
                      }
                    },
                    {
                      name: 'flip', // 完全禁用翻转功能
                      enabled: false
                    }
                  ]
                }">
                <template #prefix>
                  <img src="../assets/images/sort-asc.png" class="select-prefix-img" alt="" @click.stop="toggleSort()"
                    :key="true" label="正序" :value="true" v-if="sort !== false" />
                  <img src="../assets/images/sort-desc.png" class="select-prefix-img" alt="" @click.stop="toggleSort()"
                    :key="false" label="倒序" :value="false" v-if="sort === false" />
                </template>
                <el-option :key="true" label="正序" :value="true" />
                <el-option :key="false" label="倒序" :value="false" />
              </el-select>
            </div>
          </div>
        </div>
        <div class="title-info-bar">
          <div class="title-info">
            <div class="info">
              <img src="../assets/images/info.png" />
            </div>
            <div class="title">
              {{ "近期美国智库机构发布涉华报告数量汇总" }}
            </div>
          </div>
          <div class="time-tab-pane">
            <TimeTabPane :activeTime="'近一年'" @time-click="handleTimeClick" />
          </div>
        </div>
        <div class="all-item">
          <div class="item-card" v-for="(item, index) in sortedCardList" :key="item.id || index"
            @click="handleClick(item)">
            <div class="red-info" v-if="item.increaseReportNumber != 0 && item.increaseReportNumber != null">{{ "+" }}{{
              item.increaseReportNumber }}</div>
            <div class="item-header">
              <div class="item-header-image">
                <img :src=item.logo alt="" />
              </div>
              <div class="item-header-text">
                <div class="text">{{ item.reportNumber }}{{ "篇报告" }}</div>
              </div>
            </div>
            <div class="item-middle">
              <div class="think-tank-name">{{ item.name }}</div>
              <div class="country">{{ item.country }}</div>
            </div>
            <div class="item-content">
              {{ item.desc }}
            </div>
            <div class="tag-box">
              <AreaTag v-for="(val, idx) in item.tagList" :key="idx" :tagName="val.industryName"></AreaTag>
            </div>
          </div>
        </div>
        <div class="page-box">
          <div class="page-change">
            <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="total"
              layout="prev, pager, next" background @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { getAllThinkTankList } from "@/api/thinkTank/overview"
import { useRouter } from 'vue-router';
import router from "@/router";
import TimeTabPane from '@/components/base/TimeTabPane/index.vue'
const cardList = ref([]);
// 按 reportNumber 从大到小排序，保证从左到右从上到下排列
const sortedCardList = computed(() => {
  return [...cardList.value].sort((a, b) => {
    const an = Number(a?.reportNumber ?? 0);
    const bn = Number(b?.reportNumber ?? 0);
    // 只有选择“倒序(false)”才反转；初始为 null 时走“正序”规则
    return sort.value === false ? an - bn : bn - an;
  });
});
// el-pagination 是 1-based
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)
const timePeriod = ref("YEAR")

const handleTimeClick = item => {
  const time = item?.time
  if (time === "近一周") {
    timePeriod.value = "WEEK"
  } else if (time === "近一月") {
    timePeriod.value = "MONTH"
  } else if (time === "近一年") {
    timePeriod.value = "YEAR"
  }
  // 切换时间范围后重新拉取（从第一页开始）
  currentPage.value = 1
  handleGetThinkTankList()
}

const handleCurrentChange = page => {
  currentPage.value = page;
  handleGetThinkTankList()
};
const routerTo = useRouter()

// 跳转到全部智库页面
const goToAllThinkTank = () => {
  // 替换为你的实际路由路径
  routerTo.push('/thinkTank');
};
const handleGetThinkTankList = async () => {
  try {
    const res = await getAllThinkTankList({
      // 后端通常是 0-based，这里做一次转换
      currentPage: currentPage.value - 1,
      pageSize: pageSize.value,
      keyword: searchPolicy.value,
      timePeriod: timePeriod.value
    });
    console.log("智库列表", res);
    cardList.value = [];
    total.value = 0;
    if (res.code === 200 && res.data) {
      const list = res.data?.content || [];
      total.value = res.data.totalElements;

      cardList.value = list.map(item => ({
        ...item,
        id: item.id,
        logo: item.imageUrl,
        name: item.name,
        tagList: item.tags,
        country: item.country,
        desc: item.describe,
        rank: item.id,
        reportNumber: item.reportNumber
      }));

    }
  } catch (error) {
    console.error("获取智库列表error", error);
    cardList.value = [];
    total.value = 0;
  }
};
// 默认显示 placeholder「报告数量」，但前缀图标显示正序
const sort = ref(null);
const toggleSort = () => {
  sort.value = sort.value === false ? true : false
};
const searchPolicy = ref("");
const handleClick = tank => {
  console.log(tank);
  window.sessionStorage.setItem("curTabName", tank.name + "概览");
  // router.push({ name: "ThinkTankDetail", params: { id: tank.id } });
  if (!tank.id) {
    ElMessage.warning("当前智库id为空,无法进入详情页");
    return;
  }
  const curRoute = router.resolve({ name: "ThinkTankDetail", params: { id: tank.id, name: tank.name } });
  window.open(curRoute.href, "_blank");
};
onMounted(async () => {
  handleGetThinkTankList();

});
</script>
<style lang="scss" scoped>
.home-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  overflow-y: hidden;



  .home-main {
    position: relative;
    width: 100%;
    height: 100%;
    overflow-y: auto;
    background-size: 100% 100%;
    display: flex;

    flex-direction: column;
    align-items: center;


    .home-top-bg {
      background:
        url("../assets/images/background.png"),
        linear-gradient(180deg, rgba(229, 241, 254, 1) 0%, rgba(246, 251, 255, 0) 30%);
      background-size: 100% 100%;
      position: absolute;
      width: 100%;
      height: 100%;
      z-index: -100;
      top: -64px;
    }

    .to-back {
      width: 100%;
      height: 80px;
      box-sizing: border-box;
      min-height: 80px;
      position: relative;

      .to-back-btn {
        position: absolute;
        left: calc(50% - 76px - 1600px/2 - 20px - 33px);
        /* 核心公式 */
        width: 92px;
        height: 38px;
        border-radius: 32px;
        background-color: rgba(255, 255, 255, 0.65);
        border: 1px solid rgba(25, 69, 130, 0.1);
        display: flex;
        padding-left: 20px;
        margin-top: 24px;
        box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);


        .back-text {
          height: 30px;
          margin-top: 3px;
          font-family: "Source Han Sans CN", sans-serif;
          font-weight: 400;
          font-size: 16px;
          line-height: 30px;
          letter-spacing: 0;
          text-align: center;
          color: rgb(95, 101, 108);
        }

        .back-image {
          width: 16px;
          height: 16px;
          margin-top: 11px;
          margin-right: 4px;

          img {
            width: 100%;
            height: 100%;
          }
        }
      }

    }

    .item-box {
      width: 1600px;
      height: 962px;
      box-sizing: border-box;
      min-height: 962px;

      .box-header {
        width: 1600px;
        height: 62px;
        display: flex;
        justify-content: space-between;

        .box-header-text {
          height: 62px;
          display: flex;


          .box-title {
            font-family: "YouSheBiaoTiHei";
            font-weight: 400;
            font-size: 48px;
            line-height: 62px;
            letter-spacing: 0;
            text-align: left;
            color: rgb(34, 41, 52);
            margin-left: 2px;
          }

          .number-btn {

            height: 35px;
            border-radius: 50px;
            background-color: rgb(5, 95, 194);

            display: flex;
            padding: 2px 16px;
            margin-top: 13.5px;
            margin-left: 12px;



            .number-text {
              font-family: "YouSheBiaoTiHei";
              font-weight: 400;
              font-size: 24px;
              line-height: 31px;
              letter-spacing: 0;
              text-align: left;
              color: rgb(255, 255, 255);
            }


          }
        }

        .select-box {

          height: 32px;

          margin-top: 15px;
          display: flex;
          gap: 12px;


          .search-box {
            width: 160px;
            height: 32px;
            border: 1px solid rgb(230, 231, 232);
            background-color: rgb(255, 255, 255);
            border-radius: 4px;

            :deep(.el-input__wrapper) {
              height: 32px;
              border: 1px solid rgb(230, 231, 232);
              background-color: #fff;
              border-radius: 4px;
              box-shadow: none;
              padding: 0 10px;
            }

            .search-icon {
              width: 16px;
              height: 16px;
              cursor: pointer;
            }

          }

          .select-box-sort {

            .select-prefix-img {
              width: 6.72px;
              height: 14px;
              margin-right: 10px;
            }
          }

          :deep(.el-select-dropdown) {
            left: 0 !important;
            /* 强制下拉框左对齐选择框 */
            top: 100% !important;
            /* 强制下拉框在选择框正下方 */
            transform: none !important;
            /* 禁用默认的位移变换 */
          }




        }
      }

      .title-info-bar {
        width: 1600px;
        height: 36px;
        margin-top: 14px;
        display: flex;
        justify-content: space-between;

        .title-info {
          height: 24px;
          margin-top: 6px;
          display: flex;

          .info {
            width: 16px;
            height: 16px;
            margin-top: 4px;
            margin-right: 8px;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .title {
            font-family: "Source Han Sans CN";
            font-weight: 400;
            font-size: 18px;
            line-height: 24px;
            letter-spacing: 0;
            text-align: left;
            color: rgb(59, 65, 75);
          }
        }

        .time-tab-pane {
          width: 248px;
          height: 36px;
        }
      }

      .all-item {
        width: 1600px;
        height: 716px;
        margin-top: 30px;
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
        /* 👉 加上这一行就自动换行了！ */

        .item-card {
          width: 307px;
          height: 228px;
          box-shadow: 0 0 20px 0 rgba(25, 69, 130, 0.1);
          background-color: rgba(255, 255, 255, 0.65);
          border: 1px solid rgb(255, 255, 255);
          border-radius: 10px;
          padding-left: 20px;
          padding-top: 17px;
          padding-bottom: 21px;
          position: relative;

          .red-info {
            color: rgb(255, 255, 255);
            display: inline-flex;

            position: absolute;
            left: 277px;
            bottom: 208px;
            background-color: rgba(255, 77, 79, 1);
            align-items: center;
            justify-content: center;
            border-radius: 50px;
            border: 1px solid rgb(255, 255, 255);
            width: auto;
            font-family: "Source Han Sans CN";
            font-weight: 700;
            font-size: 18px;
            line-height: 24px;
            letter-spacing: 0px;

            padding: 2px 8px;
            /* 左右留空隙，更美观 */
            white-space: nowrap;
            z-index: 9999;
          }

          .item-header {
            width: 287px;
            height: 36px;
            display: flex;

            .item-header-image {
              width: 36px;
              height: 36px;

              img {
                width: 100%;
                height: 100%;
              }
            }

            .item-header-text {
              height: 32px;
              width: 180px;
              margin-top: 2px;
              margin-left: 71px;

              background: linear-gradient(270deg, rgba(5, 95, 194, 0.1), rgba(5, 95, 194, 0) 100%);

              .text {
                font-family: "Source Han Sans CN";
                font-weight: 700;
                font-size: 18px;
                line-height: 24px;
                letter-spacing: 0;
                text-align: right;
                color: rgb(5, 95, 194);
                width: 136px;
                height: 24px;
                margin-top: 4px;
                margin-left: 26px;
              }
            }
          }

          .item-middle {
            height: 24px;
            display: flex;
            justify-content: space-between;
            margin-top: 11px;

            .think-tank-name {
              font-family: "Source Han Sans CN";
              font-weight: 700;
              font-size: 16px;
              line-height: 24px;
              letter-spacing: 1px;
              text-align: left;
              color: rgb(59, 65, 75);
              height: 24px;
            }

            .country {
              color: rgb(132, 136, 142);
              font-family: "Source Han Sans CN";
              font-weight: 400;
              font-size: 14px;
              line-height: 22px;
              letter-spacing: 0;
              text-align: right;
              height: 22px;
              margin-right: 21px;
            }
          }

          .item-content {
            width: 266px;
            height: 66px;
            margin-top: 13px;
            font-family: "Source Han Sans CN";
            font-weight: 400;
            font-size: 14px;
            line-height: 22px;
            letter-spacing: 0;
            text-align: justify;
            color: rgb(95, 101, 108);
            /* 👇 下面这 4 行是核心：控制 3 行溢出显示 ... */
            display: -webkit-box;
            -webkit-line-clamp: 3;
            /* 限制 3 行 */
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .tag-box {
            margin-top: 14px;
            margin-right: 21px;
            display: flex;
            gap: 8px;
            height: 24px;
            display: flex;
            flex-wrap: wrap;
            /* 允许换行 */
            gap: 8px;
            overflow: auto;
            /* 根据内容自动调整高度 */
            // max-width: calc(3 * 40px + 2 * 8px);
            /* 每行 3 列，每个 tag 最大宽度 200px，gap 8px */




          }
        }
      }

      .page-box {

        height: 32px;
        margin-top: 36px;
        display: flex;
        justify-content: center;


      }
    }


  }
}

:deep(.el-select) {
  width: 160px;
  height: 32px;
}
</style>