<script lang="ts" setup>
import { ref, onMounted } from "vue";
import MainLayout from "@/layouts/MainLayout.vue";
import {
  ElCard,
  ElRow,
  ElCol,
  ElPagination,
  ElImage,
  ElEmpty,
  ElSkeleton,
  ElBreadcrumb,
  ElBreadcrumbItem,
} from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  getProductList,
  getProductCategories,
  getProductSubCategories,
} from "@/apis/product";
import type { ProductListItem, ProductCategory } from "@/types/product";

// 商品列表相关
const productList = ref<ProductListItem[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

// 分类相关
const categories = ref<ProductCategory[]>([]);
const activeCategoryId = ref<number | null>(null);
const expandedCategories = ref<number[]>([]); // 展开的分类ID列表
const breadcrumbCategories = ref<ProductCategory[]>([]); // 面包屑分类路径
const subCategoriesMap = ref<{ [key: number]: ProductCategory[] }>({}); // 子分类映射

// 搜索关键词
const searchKeyword = ref("");

// 获取商品列表
const fetchProductList = async () => {
  loading.value = true;
  try {
    const response = await getProductList({
      page: currentPage.value,
      size: pageSize.value,
      categoryId: activeCategoryId.value || undefined,
      name: searchKeyword.value || undefined,
    });

    if (response.code === 200) {
      productList.value = response.data.list;
      total.value = response.data.total;
    } else {
      productList.value = [];
      total.value = 0;
    }
  } catch (err) {
    console.error("获取商品列表失败:", err);
    productList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取商品分类
const fetchCategories = async () => {
  try {
    const response = await getProductCategories();
    if (response.code === 200) {
      categories.value = response.data;
    }
  } catch (err) {
    console.error("获取商品分类失败:", err);
  }
};

// 获取子分类
const fetchSubCategories = async (parentId: number) => {
  // 如果已经获取过，直接返回
  if (subCategoriesMap.value[parentId]) {
    return;
  }

  try {
    const response = await getProductSubCategories(parentId);
    if (response.code === 200) {
      subCategoriesMap.value[parentId] = response.data;
    }
  } catch (err) {
    console.error("获取子分类失败:", err);
  }
};

// 切换分类展开/收起状态
const toggleCategory = async (category: ProductCategory) => {
  // 设置为当前激活的分类
  activeCategoryId.value = category.id;

  // 更新面包屑路径
  await updateBreadcrumb(category);

  // 检查并加载子分类
  const hasChildren = await checkAndLoadChildren(category.id);

  // 如果是顶级分类（parentId为0）
  if (category.parentId === 0) {
    if (hasChildren) {
      // 如果有子分类
      if (expandedCategories.value.includes(category.id)) {
        // 如果已经展开，则收起
        expandedCategories.value = expandedCategories.value.filter(
          (id) => id !== category.id,
        );
      } else {
        // 收起所有顶级分类的展开状态
        const topLevelCategoryIds = categories.value.map((cat) => cat.id);
        expandedCategories.value = expandedCategories.value.filter(
          (id) => !topLevelCategoryIds.includes(id),
        );
        // 展开当前分类
        expandedCategories.value = [...expandedCategories.value, category.id];
      }
    } else {
      // 如果没有子分类，收起所有已展开的分类
      expandedCategories.value = [];
    }
  } else {
    // 如果是非顶级分类，保持原有逻辑
    if (hasChildren) {
      if (expandedCategories.value.includes(category.id)) {
        // 如果已经展开，则收起
        expandedCategories.value = expandedCategories.value.filter(
          (id) => id !== category.id,
        );
      } else {
        // 如果未展开，则展开
        expandedCategories.value = [...expandedCategories.value, category.id];
      }
    }
  }

  // 重新加载商品列表
  currentPage.value = 1;
  fetchProductList();
};

// 检查并加载子分类
const checkAndLoadChildren = async (categoryId: number): Promise<boolean> => {
  // 如果还没有加载过该分类的子分类，则加载
  if (!subCategoriesMap.value[categoryId]) {
    await fetchSubCategories(categoryId);
  }

  // 返回是否有子分类
  return (
    subCategoriesMap.value[categoryId] &&
    subCategoriesMap.value[categoryId].length > 0
  );
};

// 更新面包屑路径
const updateBreadcrumb = async (category: ProductCategory) => {
  const path: ProductCategory[] = [category];
  let currentCategory = category;

  // 向上查找父级分类
  while (currentCategory.parentId !== 0) {
    // 查找父级分类
    const parentCategory = findCategoryById(currentCategory.parentId);
    if (parentCategory) {
      path.unshift(parentCategory);
      currentCategory = parentCategory;
    } else {
      // 如果找不到父级分类，则尝试从服务器获取
      break;
    }
  }

  breadcrumbCategories.value = path;
};

// 根据ID查找分类
const findCategoryById = (id: number): ProductCategory | null => {
  // 先在主分类中查找
  for (const category of categories.value) {
    if (category.id === id) {
      return category;
    }

    // 在已加载的子分类中查找
    for (const subCategories of Object.values(subCategoriesMap.value)) {
      const found = subCategories.find((cat) => cat.id === id);
      if (found) {
        return found;
      }
    }
  }

  return null;
};

// 获取指定分类的子分类
const getSubCategories = (parentId: number): ProductCategory[] => {
  return subCategoriesMap.value[parentId] || [];
};

// 处理面包屑点击
const handleBreadcrumbClick = (category: ProductCategory | null) => {
  if (category) {
    toggleCategory(category);
  } else {
    // 点击"全部商品"
    activeCategoryId.value = null;
    expandedCategories.value = [];
    breadcrumbCategories.value = [];
    currentPage.value = 1;
    fetchProductList();
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchProductList();
};

// 处理页面大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchProductList();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchProductList();
};

onMounted(() => {
  fetchProductList();
  fetchCategories();
});
</script>

<template>
  <MainLayout>
    <div class="product-page">
      <div class="container mx-auto px-4 py-8">
        <!-- 页面标题 -->
        <div class="page-header mb-8">
          <h1 class="text-3xl font-bold text-gray-800">商品列表</h1>
          <p class="text-gray-600 mt-2">发现你喜欢的商品</p>
        </div>

        <!-- 面包屑导航 -->
        <div class="breadcrumb mb-6">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>
              <a
                @click="handleBreadcrumbClick(null)"
                class="cursor-pointer hover:text-blue-600"
              >
                全部商品
              </a>
            </el-breadcrumb-item>
            <el-breadcrumb-item
              v-for="category in breadcrumbCategories"
              :key="category.id"
            >
              <a
                @click="handleBreadcrumbClick(category)"
                class="cursor-pointer hover:text-blue-600"
              >
                {{ category.name }}
              </a>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!-- 搜索栏 -->
        <div class="search-bar mb-8">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索商品..."
              class="flex-1"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
        </div>

        <!-- 商品分类 -->
        <div class="category-section mb-8">
          <el-card class="category-card">
            <template #header>
              <div class="flex justify-between items-center">
                <span class="font-bold">商品分类</span>
              </div>
            </template>
            <div class="category-container">
              <!-- 一级分类 -->
              <div class="category-level">
                <div
                  v-for="category in categories"
                  :key="category.id"
                  class="category-item"
                  :class="{ active: activeCategoryId === category.id }"
                  @click="toggleCategory(category)"
                >
                  <span>{{ category.name }}</span>
                  <i
                    v-if="getSubCategories(category.id).length > 0"
                    :class="[
                      'el-icon-arrow-down',
                      'transition-transform',
                      {
                        'rotate-180': expandedCategories.includes(category.id),
                      },
                    ]"
                  ></i>
                </div>
              </div>

              <!-- 二级分类 -->
              <template v-for="category in categories" :key="category.id">
                <div
                  v-if="
                    expandedCategories.includes(category.id) &&
                    getSubCategories(category.id).length > 0
                  "
                  class="category-level ml-4"
                >
                  <div
                    v-for="subCategory in getSubCategories(category.id)"
                    :key="subCategory.id"
                    class="category-item"
                    :class="{ active: activeCategoryId === subCategory.id }"
                    @click="toggleCategory(subCategory)"
                  >
                    <span>{{ subCategory.name }}</span>
                    <i
                      v-if="getSubCategories(subCategory.id).length > 0"
                      :class="[
                        'el-icon-arrow-down',
                        'transition-transform',
                        {
                          'rotate-180': expandedCategories.includes(
                            subCategory.id,
                          ),
                        },
                      ]"
                    ></i>
                  </div>

                  <!-- 三级分类 -->
                  <template
                    v-for="subCategory in getSubCategories(category.id)"
                    :key="subCategory.id"
                  >
                    <div
                      v-if="
                        expandedCategories.includes(subCategory.id) &&
                        getSubCategories(subCategory.id).length > 0
                      "
                      class="category-level ml-4"
                    >
                      <div
                        v-for="subSubCategory in getSubCategories(
                          subCategory.id,
                        )"
                        :key="subSubCategory.id"
                        class="category-item"
                        :class="{
                          active: activeCategoryId === subSubCategory.id,
                        }"
                        @click="toggleCategory(subSubCategory)"
                      >
                        <span>{{ subSubCategory.name }}</span>
                      </div>
                    </div>
                  </template>
                </div>
              </template>
            </div>
          </el-card>
        </div>

        <el-row :gutter="20">
          <!-- 右侧商品列表 -->
          <el-col :span="24">
            <!-- 商品列表 -->
            <div class="product-list">
              <el-row :gutter="20" style="row-gap: 24px;">
                <template v-if="loading">
                  <el-col v-for="n in pageSize" :key="n" :span="8">
                    <el-card class="product-card">
                      <el-skeleton :rows="3" animated />
                    </el-card>
                  </el-col>
                </template>
                <template v-else-if="productList.length > 0">
                  <el-col
                    v-for="product in productList"
                    :key="product.id"
                    :span="8"
                  >
                    <!-- 添加点击事件跳转到详情页 -->
                    <el-card
                      class="product-card h-full cursor-pointer"
                      shadow="hover"
                      @click="$router.push(`/product/detail/${product.id}`)"
                    >
                      <div class="product-image mb-3">
                        <el-image
                          :src="product.mainImage || '/placeholder.jpg'"
                          class="w-full h-48 object-cover rounded"
                          fit="cover"
                          lazy
                        >
                          <template #error>
                            <div class="image-slot">
                              <i
                                class="el-icon-picture-outline text-4xl text-gray-300"
                              ></i>
                            </div>
                          </template>
                        </el-image>
                      </div>
                      <div class="product-info">
                        <h3
                          class="product-title text-sm font-medium mb-2 line-clamp-2 h-12"
                          :title="product.name"
                        >
                          {{ product.name }}
                        </h3>
                        <div class="product-price text-red-600 font-bold mb-2">
                          ¥{{ product.price }}
                        </div>
                        <div class="product-sales text-gray-500 text-xs">
                          销量: {{ product.sales }}
                        </div>
                      </div>
                    </el-card>
                  </el-col>
                </template>
                <template v-else>
                  <el-col :span="24">
                    <el-empty description="暂无商品数据" />
                  </el-col>
                </template>
              </el-row>
            </div>

            <!-- 分页 -->
            <div class="pagination-container mt-8 flex justify-center">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[12, 24, 36, 48]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="handlePageChange"
                @size-change="handleSizeChange"
              />
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </MainLayout>
</template>

<style scoped>
.product-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-header {
  text-align: center;
  margin-bottom: 2rem;
}

.category-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.category-container {
  max-height: 500px;
  overflow-y: auto;
}

.category-level {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background-color: #f5f7fa;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.category-item:hover {
  background-color: #e1eaff;
}

.category-item.active {
  background-color: #409eff;
  color: white;
}

.category-item i {
  font-size: 12px;
  transition: transform 0.3s;
}

.product-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

:deep(.el-breadcrumb__inner a) {
  font-weight: normal;
}

/* 滚动条样式 */
.category-container::-webkit-scrollbar {
  width: 6px;
}

.category-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.category-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

.category-container::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
</style>
