<script lang="ts" setup>
import {Agreement} from "@/constant/enums";
import {useUserStore} from "@/store";
import {debounce} from 'throttle-debounce'
import {
  appUserBankListPost,
  appUserWithdrawalApplyWithdrawalPost,
  appUserWithdrawalComputeAmountFeePost
} from "@/service";

const userStore = useUserStore()
const {t} = useI18n()

const amount = ref('');
// 是否同意协议
const isAgree = ref(false);

// 实时计算提现手续费
const feeData = ref({
  receiveAmount: 0,
  withdrawalFee: 0,
})
// 防抖后的手续费计算方法
const debouncedComputeAmountFee = debounce(500, () => {
  if (!amount.value) {
    feeData.value.withdrawalFee = 0
    return
  }
  appUserWithdrawalComputeAmountFeePost({
    body: {
      withdrawalAmount: amount.value,
    }
  }).then(res => {
    feeData.value = res.data
  })
})
// 监听输入金额，防抖计算手续费
watch(amount, () => {
  debouncedComputeAmountFee()
})

function navigateTo(url: string) {
  uni.navigateTo({url})
}

function navigateToBankList() {
  uni.navigateTo({
    url: '/pages-user/pages/income/bank-list',
    // 监听被打开页面触发的事件
    events: {
      // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
      refreshBankList: function (data) {
        console.log('重新选择的银行卡数据', data)
        currentCard.value = data
      },
    }
  })
}

// 获取用户银行卡列表
const userCard = ref<any>([])
const currentCard = ref(null)

function getUserCardList() {
  appUserBankListPost({
    params: {
      pageNum: 1,
      pageSize: 1,
    }
  }).then((res: any) => {
    console.log('用户默认提现卡信息', res)
    if (res.rows && res.rows.length > 0) {
      currentCard.value = res.rows[0]
    }
  })
}

onLoad(() => {
  getUserCardList()
})


const passwordInputRef = ref()

function handleSubmit() {
  if (amount.value <= 0) return
  if (!currentCard.value) {
    uni.showToast({
      title: t('pages-user.income.toast.pleaseSelectACard'),
      icon: 'none'
    })
    return;
  }
  if (!isAgree.value) {
    uni.showToast({
      title: `${t('common.prompt.please-carefully-read-and-agree')}${t('agreement.withdrawalAgreement')}`,
      icon: 'none'
    })
    return;
  }
  passwordInputRef.value?.showPasswordInput()
}

function payPawSuccess(value: string) {
  appUserWithdrawalApplyWithdrawalPost({
    body: {
      withdrawalAmount: amount.value,
      bankId: currentCard.value.id,
      withdrawalFee: feeData.value.withdrawalFee,
      pwd: value,
    }
  }).then(res => {
    console.log(res)
    uni.showToast({
      title: t('toast.submitSuccess'),
      icon: 'none',
    })
    uni.navigateBack()
  })
}
</script>

<template>
  <view>
    <navbar :title="t('pages-user.income.withdraw.title')"/>

    <view class="px-20rpx py-22rpx">
      <view class="bg-white rounded-12rpx px-28rpx pt-53rpx pb-38rpx">
        <view class="text-30rpx lh-30rpx text-#333 font-500 mb-30rpx">
          {{ t('pages-user.income.index.withdrawalAmountLabel') }}
        </view>
        <view class="flex items-center bg-#F7F7F7 h-108rpx rounded-12rpx pl-26rpx mb-40rpx">
          <wd-input
              v-model="amount"
              :focus-when-clear="false"
              :placeholder="t('common.placeholder.pleaseEnter')"
              clearable
              confirm-type="search"
              custom-class="!text-30rpx !bg-transparent flex-1"
              no-border
              placeholderStyle="font-size: 30rpx;color: #999;"
              type="number"
              use-prefix-slot
          >
          </wd-input>
        </view>
        <view class="flex items-center gap-60rpx text-26rpx lh-26rpx text-#333">
          <text>{{
              t('pages-user.income.index.availableWithdrawalAmount')
            }}${{ userStore.currenMerchantInfo?.balance || 0 }}
          </text>
          <text>{{ t('pages-user.income.index.withdrawalFee') }}${{ feeData.withdrawalFee || 0 }}</text>
        </view>
      </view>
      <view class="bg-white h-114rpx mt-16rpx rounded-12rpx px-28rpx flex-center-sb text-30rpx lh-30rpx text-#333"
            @click="navigateToBankList">
        <text class="font-500">{{ t('pages-user.income.index.accountToReceive') }}</text>
        <view class="flex items-center">
          <text v-if="currentCard">{{ currentCard.bankName }}({{ currentCard.card }})</text>
          <text v-else>{{ t('pages-user.income.index.addBankCard') }}</text>
          <image
              class="w-30rpx h-30rpx shrink-0 ml-14rpx mt-4rpx"
              src="@img/chef/153.png"
          ></image>
        </view>
      </view>

      <view class="px-116rpx flex items-center mt-104rpx" @click="isAgree = !isAgree">
        <image
            :src="
                  isAgree
                  ? '/static/images/chef/152.png'
                   : '/static/images/chef/134.png'
                  "
            class="w-28rpx h-28rpx shrink-0 mr-10rpx"
            mode="aspectFit"
        />
        <view class="text-28rpx lh-28rpx text-#333">
          {{ t('pages-login.continuing-agree') }}
          <text class="text-#00A76D"
                @click.stop="navigateTo('/pages/agreement/index?code=' + Agreement.CHEF_WITHDRAWAL_AGREEMENT)">
            《{{ t('agreement.withdrawalAgreement') }}》
          </text>
        </view>
      </view>
    </view>

    <fixed-bottom-large-btn
        :text="t('pages-user.income.withdraw.withdrawImmediately')"
        class="z-100"
        fixed
        @click="handleSubmit"
    />

    <password-container ref="passwordInputRef" @success="payPawSuccess"/>
  </view>
</template>

<style>
page {
  background-color: #F5F5F5;
}
</style>
<style lang="scss" scoped>
:deep(.wd-password-input__item) {
  border: solid 1px #999 !important;
}

:deep(.wd-input__clear) {
  background-color: transparent !important;
}

:deep(.wd-input__icon) {
  background-color: transparent !important;
}
</style>