<template>
  <view class="withdraw-record-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar" :style="{paddingTop: statusBarHeight + 'px'}">
      <view class="back" @tap="goBack">
        <uni-icons type="left" size="20"></uni-icons>
      </view>
      <text class="title">提现记录</text>
    </view>
    
    <view class="main-content">
      <view class="record-list-card">
        <!-- 记录列表 -->
        <view class="record-item" v-for="(item, index) in recordList" :key="index">
          <view class="record-info">
            <text class="record-title">{{ item.title || '提现记录' }}</text>
            <text class="record-date">{{ formatDate(item.createTime) }}</text>
          </view>
          <view class="record-right">
            <text class="record-amount">¥{{ item.money || '0.00' }}</text>
            <template v-if="item.state === 0">
              <button class="withdraw-btn" @tap="requestWechatTransfer(item, index)">
                提现
              </button>
            </template>
            <template v-else-if="item.state === 1">
              <text class="status-text received">已到账</text>
            </template>
            <template v-else>
              <text class="status-text cancelled">已取消</text>
            </template>
          </view>
        </view>
        
        <!-- 初始加载状态 -->
        <view v-if="loading && !isInitialized" class="loading-state">
          <text>数据加载中...</text>
        </view>
        
        <!-- 空状态 -->
        <view v-if="recordList.length === 0 && !loading && isInitialized" class="empty-state">
          <text>暂无提现记录</text>
        </view>
      </view>
      
      <!-- 加载更多状态 -->
      <view v-if="loadingMore" class="loading-more">
        <text>加载更多中...</text>
      </view>
      
      <!-- 没有更多 -->
      <view v-if="noMore && recordList.length > 0" class="no-more">
        <text>没有更多了</text>
      </view>
    </view>
  </view>
</template>

<script>
import pullRefreshMixin from '@/pages/mixins/pullRefreshMixin.js'
import api from '@/api/api.js'
import config from '@/config.js'

export default {
  mixins: [pullRefreshMixin],
  data() {
    return {
      statusBarHeight: 0,
      recordList: [],
      pageNum: 1,
      pageSize: 20,
      loading: false,
      loadingMore: false,
      noMore: false,
      refreshing: false,
      isInitialized: false
    }
  },
  onLoad() {
    this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
    this.initData()
  },
  onPullDownRefresh() {
    this.onRefresh()
  },
  onReachBottom() {
    this.loadMore()
  },
  methods: {
    async initData() {
      await this.loadRecords()
    },

    async loadRecords(isRefresh = false) {
      if (this.loading) return
      this.loading = true

      // 如果是刷新，重置分页状态
      if (isRefresh) {
        this.pageNum = 1
        this.noMore = false
        this.recordList = []
      }

      try {
        // 获取提现记录 (status=1 表示提现记录)
        const res = await api('getMyMoneyLogPage', {
          status: 1,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        
        if (res.code === 200 && res.result) {
          const records = res.result.records || []
          
          if (isRefresh) {
            this.recordList = records
          } else {
            this.recordList = [...this.recordList, ...records]
          }
          
          if (records.length < this.pageSize) {
            this.noMore = true
          }
        } else {
          this.recordList = []
        }
      } catch (error) {
        console.error('获取提现记录失败:', error)
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.isInitialized = true
      }
    },

    async loadMore() {
      if (this.noMore || this.loadingMore) return
      this.loadingMore = true
      this.pageNum++
      try {
        const res = await api('getMyMoneyLogPage', {
          status: 1,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        
        if (res.code === 200 && res.result) {
          const records = res.result.records || []
          
          this.recordList = [...this.recordList, ...records]
          if (records.length < this.pageSize) {
            this.noMore = true
          }
        }
      } catch (error) {
        console.error('加载更多记录失败:', error)
        this.pageNum-- // 失败时回退页码
        uni.showToast({
          title: '加载更多数据失败',
          icon: 'none'
        })
      } finally {
        this.loadingMore = false
      }
    },

    async onRefresh() {
      this.refreshing = true
      try {
        await this.loadRecords(true)
      } finally {
        this.refreshing = false
        uni.stopPullRefresh()
      }
    },

    formatDate(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${month}-${day}`
    },

    goBack() {
      uni.navigateBack()
    },

    // 微信商户转账
    async requestWechatTransfer(payData, index) {
      try {
        uni.showLoading({
          title: '处理中...'
        })

        // 调用微信商户转账API
        const transferResult = await new Promise((resolve, reject) => {
          // 拉起微信收款确认页面
          if (!wx.canIUse('requestMerchantTransfer')) {
            wx.showModal({
              content: '你的微信版本过低，请更新至最新版本。',
              showCancel: false,
            })
            return
          }
          
          // 在真机环境中，调用API
          wx.requestMerchantTransfer({
            mchId: config.mchId,
            appId: wx.getAccountInfoSync().miniProgram.appId,
            package: payData.packageInfo,
            success: (res) => {
              resolve(res)
            },
            fail: (res) => {
              reject(res)
            },
            complete: (res) => {
            }
          })
        })

        // 转账成功后调用成功接口
        await api('withdrawSUccess', { id: payData.id }, '确认提现中...')
        
        // 刷新列表
        this.pageNum = 1
        this.noMore = false
        this.recordList = []
        this.isInitialized = false
        await this.loadRecords()
        
        uni.showToast({
          title: '提现成功',
          icon: 'success'
        })

      } catch (error) {
        console.error('微信转账失败:', error)
        uni.showToast({
          title: '提现失败，请重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.withdraw-record-container {
  min-height: 100vh;
  background: #f7f7f7;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: calc(150rpx + var(--status-bar-height));
  padding: 0 32rpx;
  background: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  box-sizing: border-box;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
  
  .back {
    padding: 20rpx;
    margin-left: -20rpx;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: 500;
    color: #222;
  }
}

.main-content {
  margin-top: calc(150rpx + var(--status-bar-height));
  margin-bottom: 40rpx;
}

.record-list-card {
  background: #fff;
  border-radius: 40rpx;
  margin: 0 32rpx 32rpx 32rpx;
  padding: 0;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
}

.record-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 38rpx 36rpx;
  border-bottom: 2rpx solid #f3f3f3;
  
  &:last-child {
    border-bottom: none;
  }
}

.record-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.record-title {
  font-size: 30rpx;
  color: #222;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.record-date {
  font-size: 26rpx;
  color: #b3b3b3;
  font-weight: 400;
}

.record-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
}

.record-amount {
  font-size: 32rpx;
  color: #222;
  font-weight: 500;
}

.withdraw-btn {
  width: 120rpx;
  height: 50rpx;
  background: #FFB74D;
  color: #fff;
  font-size: 24rpx;
  border-radius: 25rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  padding: 0;
  line-height: 1;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  
  &::after {
    border: none;
  }
}

.status-text {
  font-size: 24rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  
  &.received {
    color: #52C41A;
    background: #f6ffed;
  }
  
  &.cancelled {
    color: #ff4d4f;
    background: #fff2f0;
  }
}

.loading-state {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

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

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 28rpx;
}

.no-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>
 