<template>
  <z-paging
    ref="pagingRef"
    v-model="balanceLogList"
    :refresher-enabled="false"
    :paging-style="{'top': '0','background-color': '#f2f3f7'}"
    loading-more-no-more-text="没有更多了，看看别的吧"
    @query="onGetBalanceLogList"
  >
    <view class="Mall4j page-my-balance">
      <view class="balance-box">
        <view class="bg" />
        <view class="balance-card">
          <view class="number-box">
            <view class="text-box">
              <view class="text">
                我的余额(元)
              </view>
              <view class="number">
                {{ wxs.parsePrice(paySettlementType===1?userInfo.allinpayActualBalance:userInfo.actualBalance)[0] }}.{{ wxs.parsePrice(paySettlementType===1?userInfo.allinpayActualBalance:userInfo.actualBalance)[1] }}
              </view>
            </view>
            <view class="cumulative">
              累计余额：{{ wxs.parsePrice(paySettlementType===1?userInfo.allinpayBalance:userInfo.balance)[0] }}.{{ wxs.parsePrice(paySettlementType===1?userInfo.allinpayBalance:userInfo.balance)[1] }} 元
            </view>
          </view>
          <view class="btns">
            <view
              :class="['btn',{'allinpayRecharge':paySettlementType===1}]"
              @tap="onToRecharge"
            >
              充值
            </view>
            <view
              v-if="paySettlementType === 1"
              class="btn"
              @tap="onToWithdraw"
            >
              提现
            </view>
          </view>
        </view>
      </view>
      <view
        v-if="balanceLogList && balanceLogList.length>0"
        class="balance-det"
      >
        <view class="tit">
          余额明细
        </view>
        <view class="det-box">
          <view
            v-for="(balanceLogItem, index) in balanceLogList"
            :key="index"
            class="item"
          >
            <view class="text-box">
              <view class="text-box-title">
                <view class="text">
                  {{ ['','余额充值', '系统赠送','购物消费','退款返还','系统变更','购买会员','余额提现'][balanceLogItem.type] }}
                </view>
                <view class="time">
                  ({{ balanceLogItem.createTime }})
                </view>
              </view>
              <view class="orderIds">
                <view
                  v-for="(orderIdsItem, orderIdsIndex) in balanceLogItem.orderIds"
                  :key="orderIdsIndex"
                  style="margin-bottom:6rpx"
                >
                  订单号：{{ orderIdsItem }}
                </view>
              </view>
            </view>
            <view :class="['number', balanceLogItem.ioType===1? 'red': '']">
              {{ balanceLogItem.ioType===1?'+':'-' }}{{ wxs.parsePrice(balanceLogItem.changeBalance)[0] }}.{{ wxs.parsePrice(balanceLogItem.changeBalance)[1] }}
            </view>
          </view>
        </view>
        <!-- 确定弹窗 -->
        <confirm-pop
          :show-pop="showPop"
          :pop-content="popContent"
          @handle-pop-cancel="onPopCancel"
          @handle-pop-confirm="onPopConfirm"
        />
        <!-- 广告弹窗 -->
        <popup-ad
          v-model="popupadShow"
          :popup-info="popupInfo"
          :shop-id="0"
        />
      </view>
    </view>
  </z-paging>
</template>
<script setup>
import util from '@/utils/util.js'
const wxs = number()
const paySettlementType = ref(uni.getStorageSync('cloudPaySettlementType')) // 1通联支付
onShow(() => {
  // 获取用户信息
  onGetUserInfo()
  if (paySettlementType.value === 1) {
    // 开启了通联支付，则需要获取会员信息（通联支付），用于判断相应条件
    onGetMemberInfo()
  }
})
let isOptions = ''
onLoad((options) => {
  isOptions = options
  onGetPopupInfo()
})

// 获取弹窗广告信息
const popupadShow = ref(false)
const popupInfo = ref({})
const onGetPopupInfo = async () => {
  const info = await util.getPopupInfo({ pageType: 3, shopId: 0 })
  if (info) {
    popupInfo.value = info
    popupadShow.value = true
  }
}

/**
 * 获取余额记录
 */
const balanceLogList = ref([])
const pagingRef = ref(null)
const onGetBalanceLogList = (pageNum, pageSize) => {
  http.request({
    url: '/mall4cloud_user/user_balance_log/page',
    method: 'GET',
    data: {
      pageNum,
      pageSize
    }
  }).then(res => {
    pagingRef.value.complete(res.list)
  })
}

/**
 * 获取用户信息
 */
const userInfo = ref({})
const onGetUserInfo = () => {
  http.request({
    url: '/mall4cloud_user/user/user_info',
    method: 'GET'
  }).then(res => {
    userInfo.value = res
  })
}

// 去充值
let allinpayMemberInfo = {} // 通联支付会员信息
let isMemberInfoLoaded = false // 会员信息是否加载完毕
const showPop = ref(false) // 弹窗组件参数
const popContent = ref({})
let confirmType = -1 // 弹窗提示类型 0：未实名认证 1：未绑定手机号 2：未绑定银行卡 3：未签约提现协议
const onToRecharge = async () => {
  if (paySettlementType.value === 1) {
    if (!isMemberInfoLoaded) {
      // 未加载完成，不允许点击
      return
    }
    // 开启了通联支付，则需要获取会员信息（通联支付），判断相应条件
    if (!allinpayMemberInfo.isIdentityChecked) {
      // 未实名认证
      showPop.value = true
      popContent.value.content = '请先进行实名认证'
      confirmType = 0
      return
    }
    if (!allinpayMemberInfo.isPhoneChecked) {
      // 未绑定手机号
      showPop.value = true
      popContent.value.content = '请先绑定用于保障账户余额安全的手机号'
      confirmType = 1
      return
    }
  }
  uni.navigateTo({
    url: '/package-activities/pages/recharge/recharge'
  })
}
// 去提现
const onToWithdraw = async () => {
  if (!isMemberInfoLoaded) {
    // 未加载完成，不允许点击
    return
  }
  // 开启了通联支付，则需要获取会员信息（通联支付），判断相应条件
  if (!allinpayMemberInfo.isIdentityChecked) {
    // 未实名认证
    showPop.value = true
    popContent.value.content = '请先进行实名认证'
    confirmType = 0
    return
  }
  if (!allinpayMemberInfo.isPhoneChecked) {
    // 未绑定手机号
    showPop.value = true
    popContent.value.content = '请先绑定用于保障账户余额安全的手机号'
    confirmType = 1
    return
  }
  const bankCardNumber = await onGetBankCardNumber() // 获取用户已绑定的银行卡数量
  if (!bankCardNumber) {
    showPop.value = true
    popContent.value.content = '请绑定最少一张银行卡'
    confirmType = 2
    return
  }
  if (!allinpayMemberInfo.acctProtocolNo) {
    showPop.value = true
    popContent.value.content = '请先签约提现协议'
    confirmType = 3
    return
  }
  uni.navigateTo({
    url: '/package-activities/pages/allinpay-withdrawal/allinpay-withdrawal'
  })
}
const onGetMemberInfo = () => {
  uni.showLoading()
  isMemberInfoLoaded = false
  // 获取会员信息
  http.request({
    url: '/mall4cloud_payment/allinpay/member/get_user_info',
    method: 'GET'
  }).then(res => {
    uni.hideLoading()
    // #ifdef H5
    // 获取内存中的签约编号

    const acctProtocolNo = uni.getStorageSync('cloudAllinpayAcctProtocolNo')
    // 以下代码为H5页面签约成功执行, 小程序在App.vue的onShow中,App在单独的页面redirect.vue中
    // 如果本次签约和存储中的签约编号不一致，则需要提示签约成功并更新签约编号，否则不提示，避免重复提示签约成功
    if (Number(isOptions.isSignSuccess) === 1 && isOptions.bizContent && acctProtocolNo !== isOptions.bizContent.acctProtocolNo) {
      uni.showToast({
        title: '签约成功',
        icon: 'none',
        duration: 1500
      })
      // 上方已经重新获取通联会员信息，所以不用再次请求
      uni.setStorageSync('cloudAllinpayAcctProtocolNo', isOptions.bizContent.acctProtocolNo)
    } else if (Number(isOptions.isSignSuccess) === 0) {
      uni.showToast({
        title: '签约失败',
        icon: 'none',
        duration: 1500
      })
    }
    // #endif
    allinpayMemberInfo = res
    isMemberInfoLoaded = true
  }).catch(err => {
    uni.hideLoading()
    isMemberInfoLoaded = true
    uni.showToast({
      title: err.msg,
      icon: 'none'
    })
  })
}

// 获取用户已绑定的银行卡数量
const onGetBankCardNumber = () => {
  return new Promise((resolve, reject) => {
    http.request({
      url: '/mall4cloud_payment/allinpay/member/query_bank_card',
      method: 'GET',
      selfLoading: true
    }).then(res => {
      if (res) {
        resolve(res.length)
      } else {
        resolve(0)
      }
    }).catch((err) => {
      reject(err)
    })
  })
}

// 弹窗确认事件
const onPopConfirm = () => {
  showPop.value = false
  if (confirmType === 0) { // 未实名认证
    uni.navigateTo({
      url: '/package-user/pages/realname-verification/realname-verification'
    })
  } else if (confirmType === 1) { // 未绑定手机号
    uni.navigateTo({
      url: '/package-user/pages/bind-mobile/bind-mobile'
    })
  } else if (confirmType === 2) { // 未绑定银行卡
    uni.navigateTo({
      url: '/package-user/pages/bind-bank-card/bind-bank-card'
    })
  } else if (confirmType === 3) { // 未签约
    onToSignContract()
    return
  }
  onPopCancel() // 关闭弹窗
}

// 去签约
const onToSignContract = util.debounce(async function () {
  const data = {
    signAcctType: 1,
    jumpUrl: import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-activities/pages/my-balance/my-balance?isSignSuccess=1',
    noContractUrl: import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-activities/pages/my-balance/my-balance?isSignSuccess=0',
    jumpPageType: 1
  }
  // #ifdef APP-PLUS
  // 前往H5中转APP页面
  data.jumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/redirect/redirect?isSignSuccess=1'
  data.noContractUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/redirect/redirect?isSignSuccess=0'
  // #endif
  // #ifdef MP-WEIXIN
  data.jumpPageType = 2
  // #endif
  uni.showLoading()
  http.request({
    url: '/mall4cloud_payment/allinpay/member/sign_acct_protocol',
    method: 'POST',
    data
  }).then((res) => {
    uni.hideLoading()
    onPopCancel() // 关闭弹窗
    // #ifdef H5
    window.location.href = res
    // #endif
    // #ifdef MP-WEIXIN
    util.toAllinPay({
      targetUrl: res
    })
    // #endif
    // #ifdef APP-PLUS
    // eslint-disable-next-line no-undef
    plus.runtime.openURL(res)
    // #endif
  }).catch(() => {
    uni.hideLoading()
  })
})

// 弹窗取消事件
const onPopCancel = () => {
  showPop.value = false
  confirmType = -1
  popContent.value = {}
}

</script>

<style lang="scss" scoped>
@use "./my-balance.scss";
</style>
