<template>
  <div class="final-container">
    <div class="shop-header">
      <button @click="$router.go(-1)" class="back-btn"><</button>
      <el-input placeholder="请输入商品名称或种类" v-model="searchKeyword" clearable class="product-searcher">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <div class="product-container">
      <div class="product-header">

        <div class="product-filter">
          <div :class="['filter', { active: filter.active }]" v-for="(filter, index) in filters" :key="index" @click="switchFilter(index)">
            {{ filter.name }}
          </div>
        </div>

        <div class="style-btn">
          <img src="/imgs/shop/style-change.png" alt="改变" class="img-style" @click="changeStyle">
        </div>
      </div>

      <div class="coupon-announcer" @click="$router.push('/coupon')" v-if="couponExist">
        你有优惠券待领取
      </div>

      <div :class="{'product-list1': !isGridStyle, 'product-list2': isGridStyle}">
        <div v-for="product in products" :key="product.id" :class="{'product-item1': !isGridStyle, 'product-item2': isGridStyle}" @click="$router.push(`/productsummary/${product.id}`)">
          <img :src="product.image" :alt="product.name" :class="{'product-image1': !isGridStyle, 'product-image2': isGridStyle}">
          <div class="product-info">
            <div :class="{'product-content-name1': !isGridStyle, 'product-content-name2': isGridStyle}">
              {{ product.name }}
            </div>
            <div :class="{'price-info1': !isGridStyle, 'price-info2': isGridStyle}">
              <el-icon><Coin /></el-icon>
              <div class="product-content-price1">{{ product.points_price }}</div>
            </div>
            <div :class="{'price-info1': !isGridStyle, 'price-info2': isGridStyle}">
              <img src="/imgs/profile/rongdou.png" alt="融豆" :class="{'img-bean1': !isGridStyle, 'img-bean2': isGridStyle}">
              <div :class="{'product-content-price1': !isGridStyle, 'product-content-price2': isGridStyle}">{{ product.rongdou_price }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import { getImageUrl } from '@/config'
import { useUserStore } from '@/stores/user';


const userStore = useUserStore();
const route = useRoute()

// const secondCategory = ref(route.params.name)

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

const products = ref([])
// const filteredProducts = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const page = ref(1)
const hasMore = ref(true)
const selectedCategory = ref(route.params.name)

const couponExist = ref(false)

const isGridStyle = ref(false)

const filters = ref([{
  name: '默认',
  sort: 'null'
}, {
  name: '价格高到低',
  sort: 'price_desc'
}, {
  name: '价格低到高',
  sort: 'price_asc'
}, {
  name: '销量',
  sort: 'sales_desc'
}])

const switchFilter = (index) => {
  filters.value.forEach((filter, i) => {
    filter.active = i === index
  })

  const selectedFilter = filters.value[index]
  console.log(selectedFilter.sort)
  getProducts(false, selectedFilter.sort)
  // sortProducts(selectedFilter.sort)
}

// const sortProducts = (sortType) => {
//   switch (sortType) {
//     case 'null':
//       // filteredProducts.value = products.value
//       break
//     case 'price_desc':
//       // filteredProducts.value = products.value.sort((a, b) => b.points_price - a.points_price)
//       break
//     case 'price_asc':
//       // filteredProducts.value = products.value.sort((a, b) => a.points_price - b.points_price)
//       break
//     case 'sales_desc':
//       // filteredProducts.value = products.value.sort((a, b) => b.sales - a.sales)
//       break
//     default:
//       // filteredProducts.value = products.value
//       break
//   }
// }

const changeStyle = () => {
  isGridStyle.value = !isGridStyle.value
}

const getProducts = async (isLoadMore = false, sort) => {
  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 === 'all' ? '' : selectedCategory.value,
        search: searchKeyword.value,
        sort: sort
      }
    })
    
    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++
    // filteredProducts.value = products.value
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const isCouponExist = async () => {
  try {
    const {data} = await api.get(`/coupon`)
    console.log(data)
    couponExist.value = data.success
  } catch (error) {
    ElMessage.error('检查优惠券失败')
    console.error('检查优惠券失败:', error)
    couponExist.value = false
  }
}

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

onMounted(() => {
  isCouponExist()
  getProducts()
  filters.value[0].active = true
})
</script>

<style scoped>

.final-container {
  padding: 20px;
}

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

.back-btn {
  font-size: 15px;
  width: 26px;
  height: 26px;
  color: #000000;
  background: transparent;
  border: none;
  position: absolute;
  left: 0;
  margin-left: 0;
}

.product-searcher {
  width: 265px;
  height: 32px;
  align-self: center;
}

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

.product-header {
  display: flex;
  align-items: center;
}

.product-filter {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter {
  font-size: 12px;
  padding: 5px 10px;
  border-radius: 20px;
}

.filter.active {
  color: #305DEF;
}

.filter:hover {
  color: #305DEF;
}

.style-btn {
  margin-left: auto;
}

.img-style {
  width: 12px;
  height: 12px;
}

.coupon-announcer {
  width: 100%;
  text-align: center;
  background: #E5FFE2;
  font-size: 16px;
  font-weight: bold;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 5px;
  padding-left: 10px;
}

.product-list1 {
  display: flex;
  flex-wrap: wrap;
}

.product-item1 {
  width: 200px;
  margin: 10px;
  display: flex;
  align-items: flex-start;
  gap: 10px;
  min-width: 100%;
  max-height: 110px;
}

.product-image1 {
  width: 110px;
  height: 110px;
  flex-shrink: 0;
}

.price-info1 {
  display: flex;
  align-items: flex-start;
  gap: 4px;
  margin-top: auto;
  padding: 0 10px;
  flex: 1;
}

.product-content-name1 {
  font-size: 16px;
  padding: 0 10px;
}

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

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

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

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

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

.product-content-name2 {
  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-info2 {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: auto;
  padding: 0 10px;
  padding-bottom: 5px;
}

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

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

</style>
