<template>
  <view class="promote-page">

    <uv-status-bar></uv-status-bar>
    <!-- 主要内容区域 -->
    <view class="content">
      <!-- 推广官图片 -->
      <view class="promote-image-container">
        <uv-icon name="arrow-left" size="20" color="black"  @click="goBack"></uv-icon>
        <view :style="{flex: 1, justifyContent: 'center', display: 'flex'}">
          <image 
            class="promote-image" 
            src="/static/promoter.png" 
            mode="widthFix"
          ></image>
        </view>
      </view>

      <!-- 推广标语图片 -->
      <view class="slogan-container">
        <image 
          class="slogan-image" 
          src="/static/promotion-slogan.png" 
          mode="widthFix"
        ></image>
      </view>


    </view>

    <!-- 外部大容器 -->
    <view class="main-container">
      <!-- 个人信息容器 -->
      <view class="profile-container">
        <image class="profile-avatar" :src="userInfo.avatar" mode="aspectFill"></image>
        <view class="profile-info">
          <text class="profile-name">{{ userInfo.name }}</text>
          <!-- <text class="profile-id">ID: {{ userInfo.id }}</text> -->
        </view>
        <view class="profile-stats">
          <view class="stat-item">
            <text class="stat-number">{{ num }}</text>
            <text class="stat-label">推广人数</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ userInfo.price || 0 }}</text>
            <text class="stat-label">总佣金</text>
          </view>
        </view>
      </view>
      
      <!-- 功能按钮区域 -->
      <view class="function-buttons">
        <view class="function-item" @click="goTeam">
          <image class="function-icon" src="/static/team-icon.png" mode="aspectFit"></image>
          <text class="function-text">我的团队</text>
        </view>
        <view class="function-item" @click="goQrcode">
          <image class="function-icon" src="/static/qrcode-icon.png" mode="aspectFit"></image>
          <text class="function-text">推广二维码</text>
        </view>
        <view class="function-item" @click="goCash">
          <image class="function-icon" src="/static/withdraw-icon.png" mode="aspectFit"></image>
          <text class="function-text">提现</text>
        </view>
      </view>
      
      <!-- 余额显示 -->
      <view class="balance-section">
        <text class="balance-label">余额</text>
        <text class="balance-amount">¥{{ userInfo.commission || 0 }}</text>
        <!-- <uv-icon name="arrow-right" size="16" color="#999"></uv-icon> -->
      </view>
      
      <!-- 转账记录容器 -->
      <view class="record-container">
        <view class="record-list">
          <view v-if="hasMore && !list.length">
            <uv-loading-icon text="加载中" ></uv-loading-icon>
          </view>
          <view v-else-if="!list.length">
            <uv-empty ></uv-empty>
          </view>
          <view v-else class="record-item" v-for="(item, index) in list" :key="index">
            <view class="record-avatar">
              <image class="avatar" :src="item.userInfo.avatar" mode="aspectFill"></image>
              <text class="avatar-name">{{ item.user_dictText }}</text>
            </view>
            <view class="record-info">
              <text class="record-title">{{ item.title }}</text>
              <text class="record-date">{{ item.createTime }}</text>
            </view>
            <view class="record-amount">
              <text class="amount">{{ item.type === '1' ? '+' + item.money : '-' + item.money }}</text>

              <!-- 领取按钮 - 当status=1且为微信提现时显示 -->
              <uv-button 
                v-if="item.withdrawal && item.withdrawal.status === '1' && item.withdrawal.withdrawStatus === '0' && item.withdrawal.method === '0'"
                :custom-style="{
                  height: '60rpx',
                  borderRadius: '30rpx',
                  background: '#06DADC',
                  border: '1rpx solid #06DADC',
                  lineHeight: '60rpx',
                  fontSize: '24rpx',
                  padding: '0 20rpx'
                }" 
                type="primary" 
                size="mini"
                @click="requestMerchantTransfer(item.withdrawal)">
                领取
              </uv-button>

              <text class="status" 
              :class="item.withdrawal.status === '1' 
              && item.withdrawal.withdrawStatus === '0' ? 'status-available' : 'status-received'" 
              v-else-if="item.withdrawal ">{{ getText(item.withdrawal) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
     
     <!-- 底部固定按钮 -->
    <view class="bottom-button-container">
      <uv-button :custom-style="{
        
        height: '82rpx',
        borderRadius: '198rpx',
        background: '#06DADC',
        border: '2rpx solid #06DADC',
        lineHeight: '82rpx',
        fontSize: '36rpx'
        }" type="primary" @click="goQrcode">分享</uv-button>
        <uv-safe-bottom></uv-safe-bottom>
    </view>
  </view>
</template>

<script>
import MixinList from '@/mixins/list'
import uvLoadingIcon from '../../uni_modules/uv-loading-icon/components/uv-loading-icon/uv-loading-icon.vue'
export default {
  components: { uvLoadingIcon },
  mixins: [MixinList],
  data() {
    return {
      mixinListApi: 'promotion.water',
      num: 0,
      userInfo: {},
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    goTeam() {
      uni.navigateTo({
        url: '/subPages/user/team'
      })
    },
    goCash() {
      uni.navigateTo({
        url: '/subPages/user/cash'
      })
    },

    getText(widhdraw) {
      // 如果已经领取了
      if (widhdraw.withdrawStatus !== '0') {
        return '已领取,' + (widhdraw.method === '0' ? '微信打款' : '线下付款')
      }else if (widhdraw.status === '0') {
        return '提现待审核中'
      }else if(widhdraw.status === '2'){
        return '审核失败！'
      }
    },
    // 获取推广统计
    async getStatistics() {
      const res = await this.$api.promotion.statistics()
      if (res.code === 200) {
        this.num = res.result.num
      }
    },
    // 获取用户信息
    async getUserInfo() {
      const res = await this.$api.login.getUserInfo()
      if (res.code === 200) {
        this.userInfo = res.result
      }
    },
    // 提现接口
    requestMerchantTransfer(item) {
      if (!wx.canIUse('requestMerchantTransfer')) {
        wx.showModal({
          content: '你的微信版本过低，请更新至最新版本。',
          showCancel: false,
        });
        return
      }
      // 提现
      
      // #ifdef H5
        // H5环境下检查微信环境
        if (!this.isInWechat()) {
          uni.showToast({
            title: '请在微信中打开',
            icon: 'none'
          })
          return
        }
        
        // H5环境下使用专门的H5提现方法
        this.requestMerchantTransferH5(item.packageInfo, async () => {
          const withdrawRes = await this.$api.promotion.withdrawSuccess({
            id : item.id
          })
          if (withdrawRes.code === 200) {
            uni.showToast({
              title: '提现成功',
              icon: 'success'
            })
          }
        })
        return
      // #endif

      // #ifdef MP-WEIXIN
      wx.requestMerchantTransfer({
        mchId: '1724993508',//
        appId: wx.getAccountInfoSync().miniProgram.appId,
        package: item.packageInfo,
        success: async (res) => {
          // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表提款成功
          console.log('success:', res);
          // this.getData()
          
          const withdrawRes = await this.$api.promotion.withdrawSuccess({
            id : item.id
          })
          if (withdrawRes.code === 200) {
            uni.showToast({
              title: '提现成功',
              icon: 'success'
            })
          }
        },
        fail: (res) => {
          console.log('fail:', res);
          // this.getData()
        },
      });
      // #endif
    },

    // #ifdef H5
    // H5环境下的微信收款确认
    requestMerchantTransferH5(packageInfo, callback) {
      // 使用Vue原型上的jWeixin
      const jWeixin = this.$jWeixin
      if (!jWeixin) {
        console.error('jWeixin未初始化')
        uni.showToast({
          title: '微信环境异常',
          icon: 'none'
        })
        return
      }

      jWeixin.ready(() => {
        jWeixin.checkJsApi({
          jsApiList: ['requestMerchantTransfer'],
          success: (res) => {
            if (res.checkResult['requestMerchantTransfer']) {
              // H5环境下使用WeixinJSBridge
              if (typeof WeixinJSBridge !== 'undefined') {
                WeixinJSBridge.invoke('requestMerchantTransfer', {
                  mchId: '1724993508',
                  appId: wx.getAccountInfoSync().miniProgram.appId,
                  package: packageInfo,
                }, (res) => {
                  if (res.err_msg === 'requestMerchantTransfer:ok') {
                   
                    callback && callback()
                  } else {
                    console.log('提现失败:', res)
                    uni.showToast({
                      title: '提现失败，请稍后再试',
                      icon: 'none'
                    })
                  }
                })
              } else {
                console.error('WeixinJSBridge未找到')
                uni.showToast({
                  title: '请在微信中打开',
                  icon: 'none'
                })
              }
            } else {
              uni.showToast({
                title: '你的微信版本过低，请更新至最新版本',
                icon: 'none'
              })
            }
          },
          fail: (error) => {
            console.error('checkJsApi失败:', error)
            uni.showToast({
              title: '微信接口检查失败',
              icon: 'none'
            })
          }
        })
      })

      jWeixin.error((res) => {
        console.error('微信配置失败:', res)
        uni.showToast({
          title: '微信配置失败',
          icon: 'none'
        })
      })
    },
    // #endif

    // 去二维码
    goQrcode() {
      uni.navigateTo({
        url: '/subPages/user/share'
      })
    },
  },
  async onShow() {
    Promise.all([
      this.getUserInfo(),
      this.getStatistics()
    ])
  },
  
}
</script>

<style lang="scss" scoped>
.promote-page {
  min-height: 100vh;
  background: linear-gradient(124deg, #22F2EB 0%, #24B0F6 30%);
  // background: linear-gradient(124deg, #22F2EB 0%, #24B0F6 100%);

}

.content {
  padding: 0rpx 40rpx 0;
  
  .promote-image-container {
    display: flex;
    justify-content: center;
    margin-bottom: 30rpx;
    align-items: center;
    
    .promote-image {
      margin: 0 auto;
      width: 168rpx;
    }
  }
  
  .slogan-container {
    display: flex;
    justify-content: center;
    margin-bottom: 80rpx;
    
    .slogan-image {
      width: 670rpx;
    }
  }
}

// 外部大容器
.main-container {
  width: 100%;
border-radius: 48rpx;
border: 2rpx solid #06DADC12;
box-sizing: border-box;
padding: 40rpx;
padding-bottom: 200rpx;
background: linear-gradient(180deg, #DEFFFF 0%, #FBFEFF 22.65%, #F0FBFF 100%);

  // 个人信息容器
  .profile-container {
    background: #fff;
    margin-bottom: 30rpx;
    display: flex;
    align-items: center;
    

    border-radius: 48rpx;
    border-width: 2rpx;
    justify-content: space-between;
    background: linear-gradient(180deg, #DEFFFF 0%, #FBFEFF 22.65%, #F0FBFF 100%);
    // background: red;
    border: 2rpx solid #06DADC12;
    // padding-top: 32rpx;
    padding-right: 40rpx;
    // padding-bottom: 32rpx;
    // padding-left: 40rpx;
    height: 200rpx;
    .profile-avatar {
      width: 128rpx;
      height: 128rpx;
      border-radius: 50%;
      margin-right: 24rpx;
    }
    
    .profile-info {
      flex: 1;
      
      .profile-name {
        display: block;
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .profile-id {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .profile-stats {
      display: flex;
      
      .stat-item {
        text-align: center;
        margin-left: 100rpx;
        
        .stat-number {
          display: block;
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .stat-label {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
  
  // 功能按钮区域
  .function-buttons {
    
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 48rpx;
    
    .function-item {
      display: flex;
      // flex-direction: column;
      align-items: center;
      
      gap: 16rpx;
      border-right: 1px solid #06DADC;
      padding-right: 30rpx;
      &:nth-child(3) {
        border-right: none;
      }
      .function-icon {
        width: 46rpx;
        height: 46rpx;
        // margin-bottom: 16rpx;
      }
      
      .function-text {
        font-size: 24rpx;
        color: #181818;
      }
    }
  }
  
  // 余额显示
  .balance-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 40rpx;
    
    .balance-label {
      font-size: 32rpx;
      color: #191919;
      font-weight: 500;
    }
    
    .balance-amount {
      font-size: 32rpx;
      font-weight: 500;
      color: #191919;
      flex: 1;
      margin-left: 20rpx;
    }
  }
  
  // 转账记录容器
  .record-container {
    .record-list {
      min-height: 40vh;
      border: 1px solid #F0F0F0;
      border-radius: 24rpx;

      // background: red;
      .record-item {
        height: 116rpx;
        background: #fff;
        // border-radius: 16rpx;
        padding: 16rpx 32rpx;
        // margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        border-bottom: 2rpx solid #F1F1F1 ;
        // margin-right: 24rpx;
        // box-sizing: border-box;
        
        .record-avatar{
          display: flex;
          align-items: center;
          flex-direction: column;
          gap: 12rpx;
          .avatar-name {
            font-size: 24rpx;
            color: #999;
          }
          .avatar {
            width: 50rpx;
            height: 50rpx;
            border-radius: 50%;
            // margin-right: 24rpx;
          }
        }
        
        .record-info {
          flex: 3;
          text-align: center;
          .record-title {
            display: block;
            font-size: 28rpx;
            color: #333;
            margin-bottom: 8rpx;
          }
          
          .record-date {
            font-size: 26rpx;
            color: #A3A3A3;
          }
        }
        
        .record-amount {
          flex: 2;
          text-align: center;
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 8rpx;
          
          .amount {
            display: block;
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
          }
          
          .status {
            font-size: 26rpx;
            // padding: 8rpx 16rpx;
            border-radius: 20rpx;
            
            &.status-received {
              // background: #f0f0f0;
              color: #A3A3A3;
            }
            
            &.status-available {
              // background: #22F2EB;
                          padding: 3rpx 16rpx;

              color: $primary-color;
              border: 2rpx solid  $primary-color;
            }
          }
        }
      }
    }
  }
}

// 底部固定按钮
.bottom-button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx 40rpx;
  background: rgba(255, 255, 255, 0.95);
  border-top: 1px solid #F1F1F1;
  // height: 143rpx;
  // backdrop-filter: blur(10rpx);
  
}
</style>