<template>
  <div class="category-container">
    <div class="header">
      <button @click="$router.go(-1)" class="back-btn"><</button>
      <span @click="$router.go(-1)" class="back-text">返回</span>
      <el-input placeholder="请输入商品名称" v-model="searchKeyword" clearable class="product-searcher">
        <template #prefix>
           <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <button class="search-button" @click="searchProducts">搜索</button>
    </div>

    <div class="bar">
      <div v-for="(item, index) in barItems" :key="index" class="bar-item" :style="{ color: index === categoryChoice ? '#2938e0' : '' }" @click="selectCategory(index)">
        {{ item.name }}
      </div>
    </div>
    <div class="relative-bar">
      <div v-for="(item, index) in barItems[categoryChoice].relative" :key="index" class="relative-item" @click="$router.push(`/productCategoryFinal/${item.name}`)">
        <img :src="getImageUrl(item.img)" :alt="item.name" class="relative-img">
        <span class="relative-name">{{ item.name }}</span>
      </div>
    </div>

    <div class="shop-content-wrapper">
      <div class="shop-content-title">商品</div>
      <div class="shop-content">
        <div class="product-content" v-for="item in products" :key="item.id" @click="$router.push(`/productsummary/${item.id}`)">
          <img :src="getImageUrl(item.img)" :alt="item.name" class="product-content-img">
          <span class="product-content-name">{{ item.name }}</span>
          <div class="price-info">
            <el-icon><Coin /></el-icon>
            <div class="product-content-price">{{ item.points_price }}</div>
          </div>
          <div class="price-info">
            <img src="/imgs/profile/rongdou.png" alt="融豆" class="img-bean">
            <div class="product-content-price">{{ item.rongdou_price }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Search, Coin } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getImageUrl } from '@/config'
import { ref, onMounted, watch } from 'vue'
import api from '@/utils/api'

const categoryChoice = ref(0)

const barItems = ref([
  {
    name: '',
    relative: [{
      name: '',
      img: ''
    }]
  }
])

const products = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const page = ref(1)
const hasMore = ref(true)
// const selectedCategory = ref(barItems.value[0].name)
const selectedCategory = ref('')

const searchKeyword = ref('')
const sortBy = ref('')

const getCategory = async () => {
  try {
    const {data} = await api.get('/category')
    barItems.value = data.data
    selectedCategory.value = barItems.value[0].name
    getProducts(false)
  } catch (error) {
    ElMessage.error('获取分类失败')
    console.error('获取分类失败:', error)
  }
}

const selectCategory = (index) => {
  searchKeyword.value = ''
  categoryChoice.value = index
  selectedCategory.value = barItems.value[index].name
  getProducts(false)
}

const getProducts = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true
      page.value = 1
    } else {
      loadingMore.value = true
    }
    
    const {data} = await api.get('/products', {
      params: {
        page: page.value,
        limit: 20,
        category: selectedCategory.value,
        search: searchKeyword.value,
        sort: sortBy.value
      }
    })
    
    if (isLoadMore) {
      const newProducts = data.data.products
      // 处理新加载商品图片路径
      newProducts.forEach(product => {
        if (product.image) {
          product.image = getImageUrl(product.image)
        }
      })
      products.value.push(...newProducts)
    } else {
      products.value = data.data.products
      // 处理商品图片路径
      products.value.forEach(product => {
        if (product.image) {
          product.image = getImageUrl(product.image)
        }
      })
    }
    
    hasMore.value = data.data.hasMore
    page.value++
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const searchProducts = () => {
  getProducts(false)
}

watch(searchKeyword, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    getProducts(false)
  }
})

onMounted(() => {
  getCategory()
})
</script>

<style scoped>
.category-container {
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  background: #b9d5ff;
  margin-bottom: -100px;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding-left: 20px;
}

.back-btn {
  font-size: 15px;
  width: 26px;
  height: 26px;
  color: #ffffff;
  background: transparent;
  border: none;
  margin-left: -20px;
}

.back-text {
  font-size: 15px;
  text-align: center;
  line-height: 26px;
  width: 36px;
  height: 26px;
  color: #ffffff;
}

.search-button {
  width: 64px;
  height: 28px;
  border-radius: 400px;
  margin-left: 15px;
  color: #fff;
  background: linear-gradient(to right, #7b99ff, #002cc2);
  border: none;
}

.product-searcher {
  margin-left: 25px;
  width: 180px;
  height: 32px;
}

.product-searcher :deep(.el-input__wrapper) {
  border-radius: 400px;
}

.product-searcher :deep(.el-input__inner) {
  font-size: 12px;
}

.product-searcher :deep(.el-input__inner::placeholder) {
  font-size: 12px;
}

.bar {
  display: flex;
  align-items: center;
  overflow-x: auto;
  white-space: nowrap;
  height: 40px;
  width: 100%;
  align-self: center;
}

.bar::-webkit-scrollbar {
  display: none;
}

.bar-item {
  font-size: 16px;
  height: 16px;
  color: #ffffff;
  margin: 4px 8px;
  margin-top: 12px;
}

.relative-bar {
  display: grid;
  grid-template-columns: repeat(5, 45px);
  grid-template-rows: repeat(2, 66px);
  gap: 30px;
  margin-top: 5px;
  justify-content: center;
  background: #F5F8FF;
  width: 100%;
  top: 132px;
  padding-top: 10px;
  padding-right: 20px;
  padding-bottom: 20px;
  padding-left: 20px;
  gap: 30px;
  transform: rotate(0deg);
  opacity: 1;
}

.relative-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.relative-img {
  width: 40px;
  height: 40px;
  margin-bottom: 8px;
}

.relative-name {
  text-align: center;
  font-size: 10px;
  line-height: 1.2;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  width: 100%;
}

.shop-content-wrapper {
  width: 100%;
  background: #b9d5ff;
  display: flex;
  flex-direction: column;
  padding: 0 20px;
  box-sizing: border-box;
  margin-top: -10px;
  z-index: 1;
  border-radius: 10px;
}

.shop-content-title {
  width: 100%;
  text-align: left;
  color: #ffffff;
  font-size: 16px;
  font-weight: bold;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 5px;
  padding-left: 10px;

}

.shop-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  column-gap: 26px;
  row-gap: 14px;
  justify-content: center;
}

.product-content {
  width: 100%;
  height: 240px;
  border-radius: 5px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-self: center;
}

.product-content-img {
  width: 100%;
  height: 153px;
  border-radius: 5px 5px 0 0;
  flex-shrink: 0;
}

.product-bottom {
  flex: 1;
  padding: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-content-name {
  font-size: 12px;
  text-align: left;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
  min-height: 2.8em;
  padding: 3px 10px;
}

.price-info {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: auto;
  padding: 0 10px;
  padding-bottom: 5px;
}

.product-content-price {
  font-size: 12px;
  color: #ff6b00;
}

.img-bean {
  width: 16px;
  height: 16px;
}

</style>
