<template>
  <div class="solve">
    <div class="solve-head">
      <div class="head-bos">
        <div class="nav-bos flex-row-start">
          <div
            @click="onNav(item)"
            v-for="(item, index) in navList"
            :key="index"
            class="nav-list"
            :class="item.id == httpObj.tweetsCategory ? 'hig' : ''"
          >
            {{ item.categoryName }}
          </div>
        </div>
        <div class="filter-bos">
          <div v-for="(item1, index1) in filterListy" :key="index1" class="filter-list flex-row-start">
            <div class="filter-title">{{ item1.title }}</div>
            <div
              @click="onFilter(item1, item2)"
              v-for="(item2, index2) in item1.list"
              :key="index2"
              class="filter-item"
              :class="item1.id == item2.id ? 'hig' : ''"
            >
              {{ item2.title }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="data-all">
      <!-- 数据 -->
      <div class="data-bos">
        <div v-for="(item, index) in dataList" :key="index" class="data-list" @click="onPath('/plan_info/procure?id=' + item.id)">
          <img class="data-img" :src="item.coverImage" alt="" />
          <div class="data-box">
            <div class="title ellipsis">{{ item.title }}</div>
            <div class="info ellipsis2">
              {{ item.describe }}
            </div>
            <div class="time">2026-03-12</div>
          </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>
            <div class="procure-bos">
              <div v-for="(item, index) in goodsList" :key="index" class="procure-list" @click="onPath('/item?id=' + item.id)">
                <img :src="item.productImage" alt="" />
                <div>
                  <div class="procure1">{{ item.itemName }}</div>
                  <div class="procure2">¥{{ item.memberPrice }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-affix>
    </div>

    <!-- 游标分页控制 -->
    <div class="pagination-bos flex-row-between">
      <div></div>
      <pagination
        v-show="dataList.length > 0"
        v-model:page="httpObj.pageNum"
        v-model:limit="httpObj.pageSize"
        v-model:way="way"
        :cursor-mode="true"
        :has-more="hasMore"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onPath } from '@/utils/siteConfig';
import {
  getProductProgramPage,
  getPurchaseCategoryList,
  getAdaptSceneList,
  getCustomerIndustry,
  getPriceRangeList,
  getCustomerTag
} from '@/api/plan/index';
import { browsingHistoryList } from '@/api/goods/index';
import Pagination from '@/components/Pagination/index.vue';
const httpObj = ref<any>({
  tweetsCategory: '',
  adaptNo: '',
  adaptIndustry: '',
  price: '',
  lable: '',
  pageSize: 10,
  pageNum: 1
});
const dataList = ref<any>([]);
const hasMore = ref(true); // 是否还有更多数据
const way = ref<any>(1);
const navList = ref<any>([]);
const goodsList = ref<any>([]);

const filterListy = ref<any>([
  {
    title: '适配场景',
    key: 'adaptNo',
    id: '',
    list: [
      {
        id: '',
        title: '全部'
      }
    ]
  },
  {
    title: '适配行业',
    key: 'adaptIndustry',
    id: '',
    list: [
      {
        id: '',
        title: '全部'
      }
    ]
  },
  {
    title: '价格区间',
    key: 'price',
    id: '',
    list: [
      {
        id: '',
        title: '全部'
      }
    ]
  },
  {
    title: '推荐标签',
    key: 'lable',
    id: '',
    list: [
      {
        id: '',
        title: '全部'
      }
    ]
  }
]);

onMounted(() => {
  // 采购分类列表
  getPurchaseCategoryList({}).then((res) => {
    if (res.code == 200) {
      res.data.unshift({
        id: '',
        categoryName: '全部'
      });
      navList.value = res.data;
      httpObj.value.tweetsCategory = '';
    }
  });

  // 适配场景列表
  getAdaptSceneList({}).then((res) => {
    if (res.code == 200) {
      res.data.forEach((item: any) => {
        item.title = item.sceneName;
        filterListy.value[0].list.push(item);
      });
    }
  });

  //适配行业
  getCustomerIndustry({}).then((res) => {
    if (res.code == 200) {
      res.data.forEach((item: any) => {
        item.title = item.industryCategoryName;
        filterListy.value[1].list.push(item);
      });
    }
  });

  // 获取价格区间列表
  getPriceRangeList({}).then((res) => {
    if (res.code == 200) {
      res.data.forEach((item: any) => {
        item.title = item.minPrice + '-' + item.maxPrice;
        item.id = item.minPrice + '-' + item.maxPrice;
        filterListy.value[2].list.push(item);
      });
    }
  });

  // 推荐标签
  getCustomerTag({}).then((res) => {
    if (res.code == 200) {
      res.data.forEach((item: any) => {
        item.title = item.tagName;
        filterListy.value[3].list.push(item);
      });
    }
  });

  // 历史
  browsingHistoryList({}).then((res) => {
    if (res.code == 200) {
      goodsList.value = getLatest5Items(res.data);
      console.log(goodsList.value);
    }
  });

  getList();
});
const getList = () => {
  getProductProgramPage(httpObj.value).then((res) => {
    if (res.code == 200) {
      dataList.value = res.rows;
      // 判断是否还有更多数据
      hasMore.value = res.total > httpObj.value.pageSize * httpObj.value.pageNum;
    }
  });
};

const onNav = (item: any) => {
  httpObj.value.tweetsCategory = item.id;
  getList();
};

const onFilter = (item1: any, item2: any) => {
  item1.id = item2.id;
  httpObj.value[item1.key] = item2.id;
  getList();
};
/**
 * 获取最新日期的 5 个商品
 * 逻辑：先按日期降序，然后依次从每个日期的列表中取商品，凑满 5 个即停止
 */
function getLatest5Items(data: any): any[] {
  if (!data) return [];

  // 1. 获取所有日期并按时间倒序排序 (最新的在前面)
  const sortedDates = Object.keys(data).sort((a, b) => {
    return new Date(b).getTime() - new Date(a).getTime();
  });

  const result: any[] = [];
  const seenIds = new Set(); // 用于去重，防止不同日期出现相同商品

  // 2. 遍历排序后的日期
  for (const date of sortedDates) {
    if (result.length >= 5) break; // 如果已经凑满 5 个，直接跳出循环

    const items = data[date] || [];

    for (const item of items) {
      if (result.length >= 5) break; // 再次检查，防止单次循环多取

      // 可选：如果同一个商品在不同日期出现，只取一次（推荐）
      const itemId = String(item.id);
      if (seenIds.has(itemId)) continue;

      result.push(item);
      seenIds.add(itemId);
    }
  }

  return result;
}
</script>

<style lang="scss" scoped>
.solve {
  width: 100%;

  .solve-head {
    width: 100%;
    background: #ffffff;

    .head-bos {
      width: 1200px;
      margin: 0 auto;
      padding-bottom: 20px;
    }
  }

  .nav-bos {
    border-bottom: 1px solid #e5e7eb;
    width: 1200px;
    padding-bottom: 20px;

    .nav-list {
      height: 32px;
      padding: 0 12px;
      background: #f7f8fa;
      border-radius: 2px 2px 2px 2px;
      font-size: 14px;
      color: #4e5969;
      margin-right: 8px;
      line-height: 32px;
      cursor: pointer;

      &.hig {
        background: #ffe8e8;
        color: #e7000b;
      }

      &:hover {
        color: #e7000b;
      }
    }
  }

  .filter-bos {
    .filter-list {
      margin-top: 20px;

      .filter-title {
        font-size: 14px;
        color: #101828;
        margin-right: 40px;
      }

      .filter-item {
        font-size: 14px;
        color: #364153;
        margin-right: 30px;
        cursor: pointer;

        &.hig {
          color: #e7000b;
        }
      }
    }
  }
  .data-all {
    display: flex;
    width: 1200px;
    margin: 22px auto 0 auto;
    gap: 0 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: 130px;
            background: #ffffff;
            cursor: pointer;
            border-radius: 10px;
            overflow: hidden;
            border: 1px solid #d0d5dd;
            padding: 15px;
            display: flex;
            img {
              width: 100px;
              height: 100px;
              border-radius: 5px;
            }
            .procure1 {
              padding: 12px 0 10px 20px;
              font-weight: 600;
              font-size: 14px;
              color: #101828;
            }
            .procure2 {
              padding-left: 20px;
              color: var(--el-color-primary);
              font-size: 16px;
              color: #e7000b;
            }
          }
        }
      }
    }
  }

  // 数据
  .data-bos {
    width: 778px;
    padding: 0px 0 40px 0;

    .data-list {
      width: 778px;
      height: 200px;
      background: #ffffff;
      border-radius: 10px;
      overflow: hidden;
      cursor: pointer;
      margin-bottom: 20px;
      padding: 15px;
      display: flex;
      gap: 0 15px;

      .data-img {
        height: 170px;
        width: 220px;
        border-radius: 10px;
      }

      .data-box {
        height: 170px;
        flex: 1;
        padding: 10px 20px;
        width: 0;

        .title {
          font-weight: 600;
          font-size: 18px;
          color: #333333;
        }

        .info {
          font-size: 14px;
          color: #666666;
          margin-top: 10px;
        }

        .time {
          font-size: 12px;
          color: #666666;
          margin-top: 10px;
        }
      }
    }
  }

  //分页
  .pagination-bos {
    width: 1200px;
    margin: 0 auto;
    padding-bottom: 60px;
    :deep(.el-select__wrapper) {
      background: #f4f4f4;
      box-shadow: 0 0 0 1px #e5e6eb inset;
      border-radius: 2px;
    }
    :deep(.el-select__placeholder) {
      color: #1d2129;
    }
    :deep(.el-input__wrapper) {
      background: #f4f4f4;
      box-shadow: 0 0 0 1px #e5e6eb inset;
      border-radius: 2px;
    }
    :deep(.el-input__inner) {
      color: #1d2129;
    }

    :deep(.btn-prev) {
      background: #f4f4f4;
      border: 1px solid #e5e6eb;
      margin-right: 8px;
    }
    :deep(.btn-next) {
      background: #f4f4f4;
      border: 1px solid #e5e6eb;
      margin-left: 8px;
    }
    :deep(.el-pager) {
      gap: 0 8px;
      li {
        background: #f4f4f4;
        border: 1px solid #e5e6eb;
        color: #1d2129;
      }
    }
  }
}
</style>
