<template>
  <view class="product-detail">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-icon" @click="handleBack"></view>
      <text class="header-title">商品详情</text>
      <view class="header-right"></view>
    </view>

    <!-- 商品图片 -->
    <view class="product-image-section">
      <image :src="product.imageUrl || '/static/default-product.png'" mode="aspectFit" class="product-image"></image>
    </view>

    <!-- 商品信息 -->
    <view class="product-info-section">
      <view class="product-name">{{ product.name }}</view>
      <view class="product-price">
        <text class="price-value">{{ product.pointsPrice }}</text>
        <text class="price-unit">积分</text>
      </view>
      <view class="product-stock">库存: {{ product.stock || 0 }} 件</view>
    </view>

    <!-- 商品描述 -->
    <view class="product-desc-section">
      <view class="section-title">商品描述</view>
      <view class="desc-content">{{ product.description || '暂无描述' }}</view>
    </view>

    <!-- 联系信息 -->
    <view class="receiver-section">
      <view class="section-title">联系信息</view>
      <view class="form-item">
        <text class="label">联系电话</text>
        <input class="input" v-model="contactPhone" placeholder="请输入联系电话" type="number" maxlength="11" />
      </view>
      <view class="tips">提交后将由后台审核，审核通过后会与您联系</view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="points-info">
        <text class="label">我的积分:</text>
        <text class="value">{{ userPoints }}</text>
      </view>
      <view class="exchange-btn" :class="{ disabled: !canExchange }" @click="handleExchange">
        立即兑换
      </view>
    </view>
  </view>
</template>

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

export default {
  name: 'product-detail',
  data() {
    return {
      productId: null,
      product: {},
      userPoints: 0,
      makerId: null,
      contactPhone: '',
      loading: false
    }
  },
  computed: {
    canExchange() {
      if (this.loading) return false
      if (!this.product.pointsPrice) return false
      if (this.userPoints < this.product.pointsPrice) return false
      if (this.product.stock <= 0) return false
      // 需要填写联系电话
      if (!this.contactPhone || this.contactPhone.length !== 11) {
        return false
      }
      return true
    }
  },
  onLoad(options) {
    if (options.id) {
      this.productId = options.id
    }
    this.initData()
  },
  methods: {
    async initData() {
      // 获取红娘ID
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo && userInfo.matchmakerId) {
        this.makerId = userInfo.matchmakerId
      } else if (userInfo && userInfo.userId) {
        this.makerId = userInfo.userId
      }
      
      await Promise.all([
        this.loadProduct(),
        this.loadBalance()
      ])
    },
    
    async loadProduct() {
      if (!this.productId) return
      try {
        const res = await api.pointsMall.getProductDetail(this.productId)
        this.product = res || {}
      } catch (e) {
        console.error('获取商品详情失败:', e)
        uni.showToast({ title: '获取商品详情失败', icon: 'none' })
      }
    },
    
    async loadBalance() {
      if (!this.makerId) return
      try {
        const res = await api.pointsMall.getBalance(this.makerId)
        this.userPoints = res.balance || 0
      } catch (e) {
        console.error('获取积分余额失败:', e)
      }
    },
    
    handleBack() {
      uni.navigateBack()
    },
    
    async handleExchange() {
      if (!this.canExchange) {
        if (this.userPoints < this.product.pointsPrice) {
          uni.showToast({ title: '积分不足', icon: 'none' })
        } else if (this.product.stock <= 0) {
          uni.showToast({ title: '库存不足', icon: 'none' })
        } else if (!this.contactPhone || this.contactPhone.length !== 11) {
          uni.showToast({ title: '请输入正确的11位手机号', icon: 'none' })
        }
        return
      }
      
      uni.showModal({
        title: '确认兑换',
        content: `确定使用 ${this.product.pointsPrice} 积分兑换「${this.product.name}」吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.doExchange()
          }
        }
      })
    },
    
    async doExchange() {
      this.loading = true
      try {
        const data = {
          makerId: this.makerId,
          productId: this.productId,
          quantity: 1,
          contactPhone: this.contactPhone
        }
        
        await api.pointsMall.exchange(data)
        
        uni.showToast({ title: '提交成功，等待审核', icon: 'success' })
        
        // 刷新积分余额
        await this.loadBalance()
        
        // 延迟返回
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (e) {
        console.error('兑换失败:', e)
        uni.showToast({ title: e.message || '兑换失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.product-detail {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 25rpx 30rpx;
  padding-top: calc(25rpx + env(safe-area-inset-top));
  background: #FFFFFF;
  
  .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: 36rpx;
    font-weight: bold;
    color: #333;
  }
  
  .header-right {
    width: 44rpx;
  }
}

.product-image-section {
  width: 100%;
  height: 600rpx;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .product-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}

.product-info-section {
  background: #FFFFFF;
  padding: 30rpx;
  margin-top: 20rpx;
  
  .product-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .product-price {
    display: flex;
    align-items: baseline;
    margin-bottom: 15rpx;
    
    .price-value {
      font-size: 48rpx;
      font-weight: bold;
      color: #9C27B0;
    }
    
    .price-unit {
      font-size: 28rpx;
      color: #9C27B0;
      margin-left: 10rpx;
    }
  }
  
  .product-stock {
    font-size: 26rpx;
    color: #999;
  }
}

.product-desc-section {
  background: #FFFFFF;
  padding: 30rpx;
  margin-top: 20rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .desc-content {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

.receiver-section {
  background: #FFFFFF;
  padding: 30rpx;
  margin-top: 20rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .label {
      width: 150rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    .input {
      flex: 1;
      height: 70rpx;
      background: #F5F5F5;
      border-radius: 10rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
    }
  }
  
  .tips {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
    padding: 15rpx;
    background: #FFF8E1;
    border-radius: 10rpx;
    line-height: 1.5;
  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .points-info {
    display: flex;
    align-items: center;
    
    .label {
      font-size: 26rpx;
      color: #666;
    }
    
    .value {
      font-size: 32rpx;
      font-weight: bold;
      color: #9C27B0;
      margin-left: 10rpx;
    }
  }
  
  .exchange-btn {
    padding: 20rpx 60rpx;
    background: linear-gradient(135deg, #9C27B0 0%, #E91E63 100%);
    color: #FFFFFF;
    font-size: 30rpx;
    font-weight: bold;
    border-radius: 50rpx;
    
    &.disabled {
      background: #CCCCCC;
    }
  }
}
</style>
