<template>
  <view class="points-mall">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-icon" @click="handleBack"></view>
      <text class="header-title">积分商城</text>
      <view class="header-right">
        <view class="search-icon"></view>
        <view class="cart-icon">
          <text class="cart-badge">{{ cartCount }}</text>
        </view>
      </view>
    </view>

    <!-- 积分显示区域 -->
    <view class="points-section">
      <view class="points-header">
        <text class="points-label">我的积分</text>
        <text class="points-value">{{ userPoints }}</text>
        <text class="points-icon">💰</text>
      </view>
      <view class="points-actions">
        <view class="action-btn" @click="handlePointsDetail">积分明细</view>
        <view class="action-btn" @click="handleEarnPoints">赚取积分</view>
      </view>
    </view>

    <!-- 分类标签 -->
    <view class="category-tabs">
      <view 
        v-for="(category, index) in categories" 
        :key="index"
        class="category-tab"
        :class="{ active: activeCategory === index }"
        @click="activeCategory = index"
      >
        {{ category }}
      </view>
    </view>

    <!-- 商品区域 -->
    <scroll-view scroll-y class="products-container">
      <!-- 商品标题 -->
      <view class="section-header">
        <text class="section-title">{{ activeCategory === 0 ? '全部商品' : categories[activeCategory] }}</text>
        <text class="product-count">共 {{ displayProducts.length }} 件</text>
      </view>

      <!-- 空状态 -->
      <view v-if="displayProducts.length === 0 && !loading" class="empty-state">
        <text>暂无商品</text>
      </view>

      <!-- 商品网格 -->
      <view class="products-grid">
        <view 
          v-for="(product, index) in displayProducts" 
          :key="product.id"
          class="product-card"
          @click="handleProductClick(product)"
        >
          <view class="product-image">
            <image :src="product.image || defaultImage" mode="aspectFit" @error="handleImageError($event, index)"></image>
          </view>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <view class="product-price">
              <text class="price-value">{{ product.points }}</text>
              <text class="price-unit">💰</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部空白 -->
      <view class="bottom-spacer"></view>
    </scroll-view>
  </view>
</template>

<script>
import api from '@/utils/api.js'

export default {
  name: 'points-mall',
  data() {
    return {
      userPoints: 0,
      cartCount: 0,
      activeCategory: 0,
      categories: ['全部', '实物商品', '虚拟商品'],
      recommendedProducts: [],
      allProducts: [],
      makerId: null,
      loading: false,
      defaultImage: 'https://img.zcool.cn/community/01b8d95d3f8a8fa801211d53e8c6b0.jpg@1280w_1l_2o_100sh.jpg'
    }
  },
  computed: {
    // 根据分类筛选商品
    displayProducts() {
      if (this.activeCategory === 0) {
        return this.allProducts
      }
      return this.allProducts.filter(p => p.category === this.activeCategory)
    }
  },
  onLoad() {
    this.initData()
  },
  onShow() {
    // 每次显示页面时刷新积分余额
    if (this.makerId) {
      this.loadBalance()
    }
  },
  methods: {
    // 初始化数据
    async initData() {
      // 获取红娘ID
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo && userInfo.matchmakerId) {
        this.makerId = userInfo.matchmakerId
      } else if (userInfo && userInfo.userId) {
        // 如果没有matchmakerId，通过API获取
        try {
          const res = await api.matchmaker.getByUserId(userInfo.userId)
          let matchmaker = res
          if (res && res.data) {
            matchmaker = res.data
          }
          if (matchmaker && (matchmaker.matchmakerId || matchmaker.matchmaker_id)) {
            this.makerId = matchmaker.matchmakerId || matchmaker.matchmaker_id
            // 保存到userInfo中
            userInfo.matchmakerId = this.makerId
            uni.setStorageSync('userInfo', userInfo)
          }
        } catch (e) {
        
        }
      }
      
      await Promise.all([
        this.loadBalance(),
        this.loadProducts(),
        this.loadRecommendProducts()
      ])
    },
    
    // 加载积分余额
    async loadBalance() {
      if (!this.makerId) return
      try {
        const res = await api.pointsMall.getBalance(this.makerId)
        this.userPoints = res.balance || 0
      } catch (e) {
      
      }
    },
    
    // 加载商品列表
    async loadProducts() {
      this.loading = true
      try {
        const res = await api.pointsMall.getProducts({ pageNum: 1, pageSize: 50 })
        this.allProducts = (res.list || []).map(item => ({
          id: item.id,
          name: item.name,
          points: item.pointsPrice,
          image: item.imageUrl || this.defaultImage,
          category: item.category,
          stock: item.stock,
          description: item.description
        }))
      } catch (e) {
       
      } finally {
        this.loading = false
      }
    },
    
    // 加载推荐商品
    async loadRecommendProducts() {
      try {
        const res = await api.pointsMall.getRecommendProducts(10)
        this.recommendedProducts = (res || []).map(item => ({
          id: item.id,
          name: item.name,
          points: item.pointsPrice,
          image: item.imageUrl || this.defaultImage,
          category: item.category,
          stock: item.stock
        }))
      } catch (e) {
       
      }
    },
    
    // 返回上一页
    handleBack() {
      uni.navigateBack()
    },
    
    // 查看积分明细
    handlePointsDetail() {
      uni.navigateTo({
        url: '/pages/matchmaker-workbench/points-detail'
      })
    },
    
    // 赚取积分
    handleEarnPoints() {
      uni.navigateTo({
        url: '/pages/matchmaker-workbench/earn-points'
      })
    },
    
    // 查看更多
    handleViewMore() {
      // 切换到全部分类
      this.activeCategory = 0
    },
    
    // 商品点击 - 跳转到商品详情
    handleProductClick(product) {
      uni.navigateTo({
        url: `/pages/matchmaker-workbench/product-detail?id=${product.id}`
      })
    },
    
    // 图片加载失败处理
    handleImageError(e, index) {
      if (this.recommendedProducts[index]) {
        this.$set(this.recommendedProducts[index], 'image', this.defaultImage)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.points-mall {
  min-height: 100vh;
  background: #FFF9F9;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 25rpx 30rpx;
  padding-top: calc(25rpx + env(safe-area-inset-top));
  background: #FFF9F9;
  border-bottom: 1rpx solid #F0F0F0;

  .back-icon {
    width: 44rpx;
    height: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #333;

    &::before {
      content: '‹';
    }
  }

  .header-title {
    font-size: 38rpx;
    font-weight: bold;
    color: #333;
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .search-icon {
      width: 44rpx;
      height: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #999;

      &::before {
        content: '🔍';
      }
    }

    .cart-icon {
      width: 44rpx;
      height: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #999;
      position: relative;

      &::before {
        content: '🛒';
      }

      .cart-badge {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        width: 32rpx;
        height: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #FF4444;
        color: #FFFFFF;
        font-size: 20rpx;
        font-weight: bold;
        border-radius: 50%;
      }
    }
  }
}

/* 积分显示区域 */
.points-section {
  background: linear-gradient(135deg, #FCE4EC 0%, #F8BBD0 100%);
  padding: 40rpx 30rpx;
  border-radius: 0 0 30rpx 30rpx;

  .points-header {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20rpx;
    margin-bottom: 30rpx;

    .points-label {
      font-size: 28rpx;
      color: #666666;
    }

    .points-value {
      font-size: 64rpx;
      font-weight: bold;
      color: #333333;
    }

    .points-icon {
      font-size: 48rpx;
    }
  }

  .points-actions {
    display: flex;
    justify-content: space-around;

    .action-btn {
      padding: 15rpx 40rpx;
      background-color: rgba(255, 255, 255, 0.8);
      color: #9C27B0;
      border-radius: 30rpx;
      font-size: 28rpx;
      font-weight: bold;
      transition: all 0.3s;

      &:active {
        background-color: rgba(255, 255, 255, 1);
      }
    }
  }
}

/* 分类标签 */
.category-tabs {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  background: #FFFFFF;
  overflow-x: auto;
  white-space: nowrap;

  .category-tab {
    padding: 12rpx 24rpx;
    background: #F5F5F5;
    color: #666;
    border-radius: 20rpx;
    font-size: 26rpx;
    white-space: nowrap;
    transition: all 0.3s;

    &.active {
      background: #9C27B0;
      color: #FFFFFF;
      font-weight: bold;
    }
  }
}

/* 商品容器 */
.products-container {
  flex: 1;
  background: #FFFFFF;
  padding: 20rpx 30rpx;
}

/* 分类标题 */
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .product-count {
    font-size: 24rpx;
    color: #999;
  }

  .view-more {
    display: flex;
    align-items: center;
    gap: 5rpx;

    .view-more-text {
      font-size: 24rpx;
      color: #9C27B0;
    }

    .arrow {
      font-size: 28rpx;
      color: #9C27B0;
    }
  }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

/* 废弃的view-more样式 */
.view-more-deprecated {
  display: flex;
  align-items: center;
  gap: 5rpx;

  .view-more-text {
    font-size: 24rpx;
    color: #9C27B0;
  }

  .arrow {
    font-size: 28rpx;
    color: #9C27B0;
  }
}

/* 商品网格 */
.products-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-bottom: 20rpx;

  .product-card {
    background: #FFFFFF;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
    transition: all 0.3s;

    &:active {
      transform: translateY(-4rpx);
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.12);
    }

    .product-image {
      width: 100%;
      height: 300rpx;
      background: #F5F5F5;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .product-info {
      padding: 15rpx;

      .product-name {
        display: block;
        font-size: 24rpx;
        color: #333;
        margin-bottom: 10rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .product-price {
        display: flex;
        align-items: center;
        gap: 5rpx;

        .price-value {
          font-size: 28rpx;
          font-weight: bold;
          color: #9C27B0;
        }

        .price-unit {
          font-size: 24rpx;
        }
      }
    }
  }
}

/* 底部空白 */
.bottom-spacer {
  height: 40rpx;
}
</style>