<template>
  <view class="user" :class="$store.state.AppStyle" style="background-color: #f6f6f6;">
    <!-- 顶部导航栏 -->
    <view class="header" :style="[{height:CustomBar + 'px'}]">
      <view class="cu-bar bg-white" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}">
        <view class="action" @tap="back">
          <text class="cuIcon-back"></text>
        </view>
        <view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
          勋章馆
        </view>
        <view class="action" @tap="goToMyMedals">
          <text class="text-primary">我的勋章</text>
        </view>
      </view>
    </view>
    <view :style="[{padding:(NavBar+5) + 'px 10px 0px 10px'}]"></view>

    <!-- 内容区域 -->
    <view class="medal-content" v-if="pageReady">
      <!-- 空状态 -->
      <view class="empty-state" v-if="displayMedals.length === 0">
        <image class="empty-icon" src="/static/images/empty-medals.png" mode="aspectFit"></image>
        <text class="empty-text">暂无可申请的勋章</text>
      </view>
      
      <!-- 勋章网格 -->
      <view class="medal-grid" v-else>
        <view 
          class="medal-card" 
          v-for="medal in displayMedals" 
          :key="medal.id"
          :class="{'applying': applying}"
        >
          <view class="medal-content">
            <image 
              :src="medal.icon_url" 
              class="medal-icon" 
              mode="aspectFit"
              :style="{ opacity: applying ? 0.5 : 1 }"
            ></image>
            <view class="medal-info">
              <text class="medal-name">{{ medal.name }}</text>
              <text class="medal-desc">{{ medal.description }}</text>
            </view>
          </view>
          <button 
            class="apply-btn"
            :class="{'disabled': applying}"
            @tap="applyMedal(medal)"
            :disabled="applying"
          >
            <text class="btn-text">{{ applying ? '申请中...' : '申请' }}</text>
          </button>
        </view>
      </view>

      <!-- 分页控制器 -->
      <view class="pagination" v-if="allMedals.length > pageSize">
        <view class="page-btn" 
          :class="{ disabled: currentPage === 1 }"
          @tap="prevPage"
        >
          <text class="icon">←</text>
        </view>
        
        <view class="page-info">
          <text>{{ currentPage }}/{{ totalPages }}</text>
        </view>
        
        <view class="page-btn"
          :class="{ disabled: !hasMore }"
          @tap="nextPage"
        >
          <text class="icon">→</text>
        </view>
      </view>
    </view>
    <view v-else class="loading-container">
      <u-loading mode="circle" size="36"></u-loading>
    </view>
  </view>
</template>

<script>
import { localStorage } from '../../../js_sdk/mp-storage/mp-storage/index.js'

export default {
  data() {
    return {
      StatusBar: this.StatusBar,
      CustomBar: this.CustomBar,
      NavBar: this.StatusBar + this.CustomBar,
      AppStyle: this.$store.state.AppStyle,
      medals: [],
      pageSize: 6,
      currentPage: 1,
      allMedals: [],
      applying: false,
      loading: false,
      isLoggedIn: false,
      userInfo: null,
      pageReady: false,
      pendingApplications: new Set(), // 记录正在申请中的勋章ID
      token: '',
      isLogin: false,
      submitStatus: false, // 防止重复提交
      applyDebounce: {} // 用于存储每个勋章的防抖状态
    }
  },

  computed: {
    displayMedals() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.allMedals.slice(start, end);
    },
    
    hasMore() {
      return this.currentPage * this.pageSize < this.allMedals.length
    },
    
    totalPages() {
      return Math.ceil(this.allMedals.length / this.pageSize)
    }
  },

  async mounted() {
    try {
      await this.checkLoginStatus()
      await this.loadMedals()
    } finally {
      this.pageReady = true
    }
  },

  created() {
    // 获取token
    this.token = localStorage.getItem('token') || '';
    this.isLogin = !!this.token;
  },

  methods: {
    async checkLoginStatus() {
      const userInfo = uni.getStorageSync('userinfo') || localStorage.getItem('userinfo')
      if (userInfo) {
        this.userInfo = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
        this.isLoggedIn = true
      } else {
        this.isLoggedIn = false
      }
    },

    async loadMedals() {
      if (this.loading) return
      this.loading = true
      
      // 检查是否已登录
      const token = uni.getStorageSync('token')
      if (!token) {
        console.log('用户未登录')
        this.medals = []
        this.loading = false
        return
      }

      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        const requestUrl = this.$API.PluginLoad('xqy_medal')
        await new Promise((resolve, reject) => {
          const requestData = {
            action: 'getMedals',
            plugin: 'xqy_medal',
            type: 'all',
            token: token
          }
          //console.log('请求数据:', requestData)
          
          uni.request({
            url: requestUrl,
            data: requestData,
            method: 'GET',
            dataType: 'json',
            success: (res) => {
              //console.log('请求响应:', res)
              if (res.data && res.data.code === 200) {
                this.allMedals = res.data.data.medals
                resolve()
              } else {
                reject(new Error(res.data?.msg || '加载失败'))
              }
            },
            fail: (err) => {
              console.error('请求失败:', err)
              reject(new Error('请求失败'))
            }
          })
        })
      } catch (error) {
        console.error('加载失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
        this.loading = false
      }
    },

    async applyMedal(medal) {
      if(!this.isLogin) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      if(this.submitStatus) {
        uni.showToast({
          title: '请勿重复提交',
          icon: 'none'
        });
        return;
      }
      
      // 检查该勋章是否在防抖期
      if (this.applyDebounce[medal.id]) {
        return;
      }
      
      this.submitStatus = true;
      // 设置防抖状态
      this.applyDebounce[medal.id] = true;

      // 显示加载提示
      uni.showLoading({
        title: '提交申请中...',
        mask: true // 添加遮罩防止重复点击
      });

      try {
        const res = await uni.request({
          url: this.$API.PluginLoad('xqy_medal'),
          method: 'POST',
          data: {
            plugin: 'xqy_medal',
            action: 'applyMedal',
            medal_id: medal.id,
            token: this.token
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });

        if (!res[1].data) {
          throw new Error('请求失败');
        }
        
        if(res[1].data.code === 200) {
          // 先隐藏loading
          uni.hideLoading();
          // 等待一小段时间再显示成功提示
          await new Promise(resolve => setTimeout(resolve, 100));
          // 再显示成功提示
          uni.showToast({
            title: res[1].data.msg,
            icon: 'success',
            duration: 3000, // 延长显示时间
            mask: true
          });
          // 等待 toast 显示完成后再刷新
          await new Promise(resolve => setTimeout(resolve, 1000));
          await this.loadMedals();
        } else {
          // 先隐藏loading
          uni.hideLoading();
          // 等待一小段时间再显示错误提示
          await new Promise(resolve => setTimeout(resolve, 100));
          // 其他错误
          uni.showToast({
            title: res[1].data.msg,
            icon: 'none',
            duration: 3000, // 延长显示时间
            mask: true
          });
        }
      } catch (err) {
        console.error('申请失败:', err);
        // 先隐藏loading
        uni.hideLoading();
        // 等待一小段时间再显示错误提示
        await new Promise(resolve => setTimeout(resolve, 100));
        uni.showToast({
          title: err.message || '请求失败',
          icon: 'none',
          duration: 3000, // 延长显示时间
          mask: true
        });
      } finally {
        setTimeout(() => {
          this.submitStatus = false;
          this.applyDebounce[medal.id] = false;
        }, 3000);
      }
    },

    goToMyMedals() {
      uni.navigateTo({
        url: '/pages/plugins/xqy_medal/myMedals'
      })
    },

    back() {
      uni.navigateBack()
    },

    async nextPage() {
      if (!this.hasMore || this.loading) return
      this.currentPage++
      await this.loadMedals()
    },

    async prevPage() {
      if (this.currentPage <= 1 || this.loading) return
      this.currentPage--
      await this.loadMedals()
    },

    async refresh() {
      this.currentPage = 1
      this.allMedals = []
      await this.loadMedals()
    },

    onShow() {
      this.checkLoginStatus()
    }
  }
}
</script>

<style lang="scss" scoped>
.medal-content {
  padding: 16rpx;
}

// 空状态
.empty-state {
  padding: 64px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .empty-icon {
    width: 120px;
    height: 120px;
    margin-bottom: 16px;
    opacity: 0.5;
  }
  
  .empty-text {
    color: #8e8e93;
    font-size: 15px;
  }
}

// 勋章网格
.medal-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding-bottom: 32px;
  width: 100%;
  box-sizing: border-box;
}

// 勋章卡片
.medal-card {
  width: calc((100% - 24px) / 3);
  background: #fff;
  border-radius: 16px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  transition: transform 0.2s;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  
  &:active {
    transform: scale(0.98);
  }
  
  &.applying {
    opacity: 0.7;
  }
}

.medal-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 8px;
}

.medal-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 12px;
  transition: opacity 0.2s;
}

.medal-info {
  text-align: center;
}

.medal-name {
  font-size: 14px;
  font-weight: 600;
  color: #000;
  margin-bottom: 4px;
}

.medal-desc {
  font-size: 12px;
  color: #8e8e93;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

// 申请按钮
.apply-btn {
  width: 100%;
  height: 28px;
  border-radius: 14px;
  background: #007AFF;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  
  &:active {
    background: darken(#007AFF, 10%);
  }
  
  &.disabled {
    background: #c7c7cc;
  }
  
  .btn-text {
    color: #fff;
    font-size: 12px;
    font-weight: 500;
  }
}

// 分页控制器
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  gap: 16px;

  .page-btn {
    width: 36px;
    height: 36px;
    border-radius: 18px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    transition: all 0.2s;
    
    &:active {
      transform: scale(0.95);
      background: #f5f5f5;
    }
    
    &.disabled {
      opacity: 0.5;
      pointer-events: none;
    }
    
    .icon {
      font-size: 18px;
      color: #007AFF;
    }
  }
  
  .page-info {
    font-size: 15px;
    color: #8e8e93;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
}
</style>
