<template>
  <div class="page-container">
    <div class="page-header">
      <PageTitle title="我的足迹" />
      <el-button type="danger" link @click="handleClearAll"
        ><el-icon><Delete /></el-icon>删除足迹</el-button
      >
    </div>
    <!-- 按日期分组的足迹列表 -->
    <div class="footprint-list">
      <div v-for="(group, groupIndex) in footprintGroups" :key="groupIndex" class="footprint-group">
        <div class="group-header">
          <span class="group-date">{{ group.date }} {{ group.label }}</span>
        </div>
        <div class="product-grid">
          <ProductCard v-for="(item, itemIndex) in group.products" :key="itemIndex" :product="item" v-model="item.checked" show-checkbox />
        </div>
      </div>
    </div>
    <el-empty v-if="footprintGroups.length === 0" description="暂无浏览足迹" />
<!--    <TablePagination-->
<!--      v-if="footprintGroups.length > 0"-->
<!--      v-model:page="queryParams.pageNum"-->
<!--      v-model:page-size="queryParams.pageSize"-->
<!--      :total="total"-->
<!--      @change="handleQuery"-->
<!--    />-->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PageTitle, ProductCard, TablePagination } from '@/components';
import { browsingHistoryList, deleteProductBrowsingHistory } from '@/api/goods/index';

const queryParams = reactive({ pageNum: 1, pageSize: 20 });
const total = ref(0);
const loading = ref(false);
const footprintGroups = ref<any[]>([]);

/** 根据日期生成标签（今天/昨天/空） */
const getDateLabel = (dateStr: string) => {
  const today = new Date();
  const target = new Date(dateStr);
  today.setHours(0, 0, 0, 0);
  target.setHours(0, 0, 0, 0);
  const diff = today.getTime() - target.getTime();
  const oneDay = 24 * 60 * 60 * 1000;
  if (diff === 0) return '今天';
  if (diff === oneDay) return '昨天';
  return '';
};

/** 格式化日期为 MM月DD日 */
const formatDate = (dateStr: string) => {
  const d = new Date(dateStr);
  return `${d.getMonth() + 1}月${String(d.getDate()).padStart(2, '0')}日`;
};

/** 获取浏览记录列表 */
const getFootprintList = () => {
  loading.value = true;
  browsingHistoryList({ })
    .then((res: any) => {
      if (res.code == 200) {
        // 后端返回的是 Map<String, List<PcProductVo>>，key 是日期字符串（yyyy-MM-dd）
        const dataMap = res.data || {};
        const groups: any[] = [];

        // 按日期降序排序（最新的在前面）
        const sortedDates = Object.keys(dataMap).sort((a, b) => b.localeCompare(a));

        sortedDates.forEach((dateKey: string) => {
          const products = (dataMap[dateKey] || []).map((item: any) => ({
            ...item,
            name: item.itemName || item.productName || item.name || '',
            image: item.productImage || item.image || '',
            price: item.price || item.memberPrice || item.minSellingPrice || '',
            originalPrice: item.marketPrice || item.originalPrice || '',
            tag: item.tag || '',
            checked: false
          }));

          groups.push({
            dateKey, // 保留原始日期 key，用于删除操作
            date: formatDate(dateKey),
            label: getDateLabel(dateKey),
            products
          });
        });

        footprintGroups.value = groups;
        total.value = groups.reduce((sum, group) => sum + group.products.length, 0);
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleQuery = () => {
  getFootprintList();
};

/** 获取所有选中的商品 */
const getSelectedItems = () => {
  const selected: any[] = [];
  footprintGroups.value.forEach((group) => {
    group.products.forEach((item: any) => {
      if (item.checked) selected.push(item);
    });
  });
  return selected;
};

const handleClearAll = () => {
  const selectedItems = getSelectedItems();
  if (selectedItems.length === 0) {
    ElMessageBox.confirm('确定要清空所有浏览足迹吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
      const allIds = footprintGroups.value.flatMap((group) => group.products.map((item: any) => item.id)).join(',');
      if (!allIds) return;
      deleteProductBrowsingHistory(allIds).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success('已清空所有足迹');
          getFootprintList();
        }
      });
    });
  } else {
    ElMessageBox.confirm(`确定要删除选中的${selectedItems.length}条足迹吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const ids = selectedItems.map((item) => item.id).join(',');
      deleteProductBrowsingHistory(ids).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success('删除成功');
          getFootprintList();
        }
      });
    });
  }
};

onMounted(() => {
  getFootprintList();
});
</script>

<style scoped lang="scss">
.page-container {
  width: 100%;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  :deep(.page-title) {
    margin-bottom: 0;
  }
}
.footprint-list {
  .footprint-group {
    margin-bottom: 25px;
    .group-header {
      margin-bottom: 15px;
      .group-date {
        font-size: 14px;
        color: #666;
        &::before {
          content: '•';
          margin-right: 8px;
          color: #999;
        }
      }
    }
    .product-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 15px;
    }
  }
}
</style>
