<template>
  <view class="page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-btn" @click="goBack">
        <text class="nav-icon">←</text>
      </view>
      <text class="nav-title">会员中心</text>
      <view class="nav-btn" />
    </view>

    <!-- 权益说明 -->
    <view class="benefits-section" v-if="!loading">
      <text class="section-title">会员权益</text>
      <view class="benefit-item" v-for="(benefit, idx) in benefits" :key="idx">
        <text class="benefit-icon">✓</text>
        <text class="benefit-text">{{ benefit }}</text>
      </view>
    </view>
    
    <view v-else class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 会员卡片 -->
    <view class="cards-section">
      <view
        v-for="(level, idx) in memberLevels"
        :key="level.level"
        class="member-card"
        :class="{ active: selectedLevel === level.level, recommend: level.level === 1 }"
        @click="selectedLevel = level.level"
      >
        <view v-if="level.level === 1" class="recommend-badge">
          <text>推荐</text>
        </view>
        <text class="card-name">{{ level.name }}</text>
        <view class="card-price">
          <text class="price-symbol">¥</text>
          <text class="price-value">{{ level.price }}</text>
          <text class="price-unit">/{{ level.level === 2 ? '年' : '月' }}</text>
        </view>
        <view class="card-features">
          <text v-for="(feature, fIdx) in level.features" :key="fIdx" class="feature-item">
            {{ feature }}
          </text>
        </view>
      </view>
    </view>

    <!-- 开通按钮 -->
    <view class="bottom-section">
      <button class="subscribe-btn" @click="handleSubscribe">
        <text class="btn-text">立即开通 ¥{{ selectedPrice }}</text>
      </button>
      <text class="terms">开通即表示同意《会员服务协议》</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '../../store/user';
import { get, post } from '../../utils/request';

const userStore = useUserStore();

// 状态
const memberLevels = ref<any[]>([]);
const benefits = ref<string[]>([
  '无限次生成音频',
  '无字数限制',
  '10+ 优质音色',
  '优先处理队列',
  '专属客服支持',
]);
const selectedLevel = ref(1);
const loading = ref(false);

// 计算属性
const selectedPrice = computed(() => {
  const level = memberLevels.value.find(l => l.level === selectedLevel.value);
  return level?.price || 0;
});

// 初始化
onMounted(async () => {
  await fetchBenefits();
});

// 获取权益信息
async function fetchBenefits() {
  loading.value = true;
  try {
    const result = await get<{ levels: any[] }>('/member/benefits');
    // 保留所有等级，包括免费用户
    memberLevels.value = result.levels;
  } catch (error) {
    console.error('获取权益失败:', error);
    uni.showToast({ title: '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

// 返回
function goBack() {
  uni.navigateBack();
}

// 开通会员
async function handleSubscribe() {
  if (!userStore.isLoggedIn) {
    uni.navigateTo({ url: '/pages/login/index' });
    return;
  }

  const productType = selectedLevel.value === 2 ? 'yearly' : 'monthly';

  try {
    // 创建订单
    const orderResult = await post<{ orderNo: string; amount: number }>('/member/order', {
      productType,
    });

    // 判断环境：使用平台能力判断
    const platform = uni.getSystemInfoSync().platform;
    const isDev = process.env?.NODE_ENV === 'development';

    if (isDev || platform === 'devtools') {
      // 开发环境或开发者工具：模拟支付
      uni.showModal({
        title: '模拟支付',
        content: `确认支付 ¥${orderResult.amount}？\n（开发环境模拟支付）`,
        success: async (res) => {
          if (res.confirm) {
            await mockPay(orderResult.orderNo);
          }
        },
      });
    } else {
      // 生产环境：调用真实支付
      uni.showToast({ 
        title: '请使用真实支付', 
        icon: 'none',
        duration: 3000
      });
    }
  } catch (error: any) {
    console.error('创建订单失败:', error);
    uni.showToast({ 
      title: error.message || '创建订单失败', 
      icon: 'none' 
    });
  }
}

// 模拟支付
async function mockPay(orderNo: string) {
  try {
    uni.showLoading({ title: '支付中...' });
    await post('/member/pay/mock', { orderNo });
    uni.hideLoading();

    // 刷新会员状态
    await userStore.fetchMemberStatus();

    uni.showModal({
      title: '支付成功',
      content: '恭喜您成为会员！',
      showCancel: false,
      success: () => {
        uni.navigateBack();
      },
    });
  } catch (error) {
    uni.hideLoading();
    console.error('支付失败:', error);
  }
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(180deg, #f9fafb 0%, #ffffff 100%);
  padding-bottom: 200rpx;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 44rpx 32rpx 24rpx;
  background: #ffffff;
}

.nav-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-icon {
  font-size: 36rpx;
  color: #1f2937;
}

.nav-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #1f2937;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #9ca3af;
}

.benefits-section {
  margin: 32rpx;
  padding: 32rpx;
  background: #ffffff;
  border-radius: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 24rpx;
  display: block;
}

.benefit-item {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.benefit-icon {
  width: 40rpx;
  height: 40rpx;
  background: #10b981;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 24rpx;
  margin-right: 16rpx;
}

.benefit-text {
  font-size: 28rpx;
  color: #4b5563;
}

.cards-section {
  display: flex;
  gap: 24rpx;
  margin: 0 32rpx;
}

.member-card {
  flex: 1;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx 24rpx;
  border: 3rpx solid #e5e7eb;
  position: relative;
  transition: all 0.3s;
}

.member-card.active {
  border-color: #4f46e5;
  box-shadow: 0 8rpx 32rpx rgba(79, 70, 229, 0.2);
}

.member-card.recommend {
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-color: #fbbf24;
}

.recommend-badge {
  position: absolute;
  top: -12rpx;
  right: 24rpx;
  background: linear-gradient(135deg, #f97316 0%, #fb923c 100%);
  padding: 4rpx 16rpx;
  border-radius: 16rpx;
}

.recommend-badge text {
  font-size: 20rpx;
  color: #ffffff;
}

.card-name {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 16rpx;
}

.card-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 24rpx;
}

.price-symbol {
  font-size: 28rpx;
  color: #f97316;
}

.price-value {
  font-size: 56rpx;
  font-weight: 700;
  color: #f97316;
}

.price-unit {
  font-size: 24rpx;
  color: #6b7280;
  margin-left: 4rpx;
}

.card-features {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.feature-item {
  font-size: 22rpx;
  color: #6b7280;
}

.bottom-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  background: #ffffff;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
}

.subscribe-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  border-radius: 24rpx;
  border: none;
}

.subscribe-btn::after {
  border: none;
}

.btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}

.terms {
  display: block;
  text-align: center;
  font-size: 22rpx;
  color: #9ca3af;
  margin-top: 16rpx;
}
</style>