<template>
  <view class="app-container">
    <HeaderBar title="提现" text-align="center" enable-back/>

    <!-- 余额展示 -->
    <view class="balance-section">
      <text class="balance-label">可提现积分</text>
      <text class="balance-value">{{ userInfo.balance | fix2 | dv }}</text>
      <text class="balance-tip">10积分=1元</text>
    </view>

    <!-- 提现金额选项 -->
    <view class="amount-section">
      <text class="section-title">提现金额</text>
      <view class="amount-list">
        <view
          v-for="(item, index) in amountList"
          :key="index"
          class="amount-item"
          :class="{ active: selectedAmount === item.amount }"
          @tap="handleSelectAmount(item.amount)"
        >
          <text class="amount">¥{{ item.amount }}</text>
        </view>
      </view>
    </view>

    <!-- 提现按钮 -->
    <view class="action-section">
      <button class="withdraw-btn" @tap="handleWithdraw">确认提现</button>
    </view>

    <!-- 提现记录列表 -->
    <view class="record-section">
      <text class="section-title">提现记录</text>
      <view class="record-list">
        <view v-for="(item, index) in recordList" :key="item.id" class="record-item">
          <view class="record-info">
            <text class="record-amount">¥{{ item.amount | fix2 | dv}}</text>
            <text class="record-status" :style="[{ color: WithdrawStatus.parseColor(item.status) }]">{{ WithdrawStatus.parseName(item.status) }}</text>
          </view>
          <text class="record-time">{{ item.createTime }}</text>
        </view>
      </view>
      <uni-load-more :status="loadStatus(loading, recordList.length, total)" />
    </view>
  </view>
</template>

<script>
import HeaderBar from '@/components/HeaderBar.vue'
import { getUserProfile } from '@/api/system/user'
import { listAllWithdrawAmount } from '@/api/app/withdrawAmount'
import { getWithdrawList, applyWithdraw, cancelWithdraw, refreshWithdrawResult } from '@/api/app/withdraw'
import { $loadList } from '@/utils/mixins'
import config from '@/config'
import { WithdrawStatus } from '@/utils/enums'

export default {
  mixins: [$loadList],
  components: {
    HeaderBar
  },
  data() {
    return {
      WithdrawStatus,
      userInfo: {},
      amountList: [],
      selectedAmount: null,
      recordList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'createTime',
        isAsc: 'desc'
      },
      loading: false,
      total: null,
    }
  },
  onLoad() {
    this.getUserInfo()
    this.getAmountList()
    this.getRecordList()
  },
  onReachBottom() {
    this.loadMoreRecord();
  },
  methods: {
    // 获取用户信息
    getUserInfo() {
      getUserProfile().then(res => {
        this.userInfo = res.data
      })
    },
    // 获取提现金额列表
    getAmountList() {
      listAllWithdrawAmount().then(res => {
        this.amountList = res.data
      })
    },
    // 选择提现金额
    handleSelectAmount(amount) {
      this.selectedAmount = amount
    },
    // 确认提现
    handleWithdraw() {
      if (!this.selectedAmount) {
        uni.showToast({
          title: '请选择提现金额',
          icon: 'none'
        })
        return
      }
      applyWithdraw({
        amount: this.selectedAmount,
        appId: config.appId
      }).then(res => {
        let no = res.data.withdraw.no;

        if (wx.canIUse('requestMerchantTransfer')) {
          wx.requestMerchantTransfer({
            mchId: res.data.withdraw.mchId,
            appId: wx.getAccountInfoSync().miniProgram.appId,
            package: res.data.transfer.packageInfo,
            success: (res) => {
              // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
              console.log('success:', res);
              refreshWithdrawResult(no).finally(() => {
                this.getUserInfo();
                this.getRecordList();
              })
            },
            fail: (res) => {
              console.log('fail:', res);
              cancelWithdraw(no).then(res => {
                uni.showToast({
                  title: '提现失败，请稍后重试',
                  icon: 'none'
                })
                this.getUserInfo();
                this.getRecordList();
              })
            },
          });
        } else {
          wx.showModal({
            content: '你的微信版本过低，请更新至最新版本。',
            showCancel: false,
          });
        }
        this.getUserInfo();
        this.getRecordList();
      })
    },
    // 获取提现记录
    getRecordList() {
      this.queryParams.pageNum = 0;
      this.queryParams.pageSize = 20;
      this.total = null;
      this.recordList = [];
      this.loadMoreRecord();
    },
    loadMoreRecord() {
      this.loadMore(() => {
        this.loading = true;
        this.queryParams.pageNum ++;
        getWithdrawList(this.queryParams).then(res => {
          this.recordList.push(...res.rows);
          this.total = res.total;
        })
        this.loading = false;
      }, this.loadStatus(this.loading, this.recordList.length, this.total))
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 30rpx;
}

.balance-section {
  margin: 0 24rpx;
  background-color: #fff;
  padding: 40rpx 30rpx;
  text-align: center;
  margin-bottom: 20rpx;

  .balance-label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    display: block;
  }

  .balance-value {
    font-size: 48rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 16rpx;
    display: block;
  }

  .balance-tip {
    font-size: 24rpx;
    color: #999;
    display: block;
  }
}

.amount-section {
  margin: 0 24rpx;
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 30rpx;
    display: block;
  }

  .amount-list {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10rpx;
  }

  .amount-item {
    width: calc(33.33% - 20rpx);
    margin: 10rpx;
    height: 100rpx;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;

    &.active {
      background-color: #007AFF;
      .amount {
        color: #fff;
      }
    }

    .amount {
      font-size: 32rpx;
      color: #333;
    }
  }
}

.action-section {
  padding: 30rpx;
  margin-bottom: 20rpx;

  .withdraw-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background-color: #007AFF;
    color: #fff;
    font-size: 32rpx;
    border-radius: 44rpx;
  }
}

.record-section {
  margin: 0 24rpx;
  background-color: #fff;
  padding: 30rpx;

  .section-title {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 30rpx;
    display: block;
  }

  .record-item {
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    &:last-child {
      border-bottom: none;
    }

    .record-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;
    }

    .record-amount {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }

    .record-status {
      font-size: 28rpx;

    }

    .record-time {
      font-size: 24rpx;
      color: #999;
    }
  }
}
</style>