// src/views/Wallet/CashOut/CashOut.vue
<template>
  <div class="fullPage">
    <GeneralHeader
      :showLanguageList="true"
      :title="t('cash_out')"
      style="width: 100%"
      color="rgba(0, 0, 0, 0.80)"
    />

    <!-- 其余内容保持不变 -->
    <div style="padding: 16px">
      <!-- 信息部分 -->
      <div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
          "
        >
          <div style="font-weight: 600">{{ t('information') }}</div>
          <div style="display: flex; align-items: center" @click="lookDetails">
            <div style="color: rgba(0, 0, 0, 0.4)">{{ t('details') }}</div>
            <img
              v-smart-img
              class="flipImg"
              src="/src/assets/icon/arrow.png"
              alt=""
              style="width: 6vw"
            />
          </div>
        </div>
        <div
          style="
            background-color: white;
            padding: 16px;
            border-radius: 12px;
            margin-bottom: 12px;
            box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
          "
        >
          <span style="font-weight: 510; font-size: 0.8em">{{ t('available_salaries') }} </span>
          <span style="font-weight: 700; color: #333">{{
            currentAmount.availableAmount || 0
          }}</span>
        </div>
      </div>

      <!-- 银行帐号信息 -->
      <div>
        <!-- 标题 -->
        <div style="display: flex; align-items: center; margin-bottom: 10px">
          <div style="font-weight: 600">{{ t('kyc') }}</div>

          <!-- 申请状态 -->
          <div v-if="hasKYC" style="font-weight: 600; margin: 0 4px">:</div>

          <!-- 通过 -->
          <div
            v-if="bankCardInfo?.status === 'PASS'"
            style="
              font-weight: 510;
              font-size: 0.9em;
              background: linear-gradient(248deg, #75ff98 5.66%, #3dff54 42.49%);
              background-clip: text;
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
            "
          >
            {{ t('review_passed') }}
          </div>

          <!-- 未通过 -->
          <div
            v-if="bankCardInfo?.status === 'NOT_PASS'"
            style="
              font-weight: 510;
              font-size: 0.9em;
              background: linear-gradient(248deg, #ff7578 5.66%, #ff3d40 42.49%);
              background-clip: text;
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
            "
          >
            {{ t('review_failed') }}
          </div>

          <!-- 审核中 -->
          <div
            v-if="bankCardInfo?.status === 'PENDING'"
            style="
              font-weight: 510;
              font-size: 0.9em;
              background: linear-gradient(248deg, #ffe675 5.66%, #ffc53d 42.49%);
              background-clip: text;
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
            "
          >
            {{ t('awaiting_review') }}
          </div>
        </div>

        <!-- 资料内容 -->
        <div
          style="
            background-color: white;
            padding: 16px;
            border-radius: 12px;
            margin-bottom: 12px;
            box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
          "
        >
          <!-- 未上传 -->
          <div
            v-if="!hasKYC"
            style="display: flex; justify-content: space-between; align-items: center"
            @click="gotoKYC"
          >
            <span style="font-weight: 510; font-size: 1em">{{ t('complete_information') }}</span>
            <img
              v-smart-img
              src="/src/assets/icon/arrow.png"
              alt=""
              style="width: 6vw"
              class="flipImg"
            />
          </div>

          <!-- 获取到上传的资料 -->
          <div v-else style="width: 100%; display: flex; flex-direction: column; gap: 8px">
            <!-- 图片 -->
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span style="font-weight: 510; font-size: 1em">{{
                t('passport_id_card', { current: bankCardInfo.previewUrls.length })
              }}</span>
              <img
                v-smart-img
                src="/src/assets/icon/arrow.png"
                alt=""
                style="width: 6vw"
                @click="gotoKYC"
                class="flipImg"
              />
            </div>
            <div style="display: flex; align-items: center; gap: 4px">
              <img
                :src="imgUrl"
                alt=""
                v-for="imgUrl in bankCardInfo.previewUrls"
                style="width: 10vw; aspect-ratio: 1/1; border-radius: 4px"
              />
            </div>

            <!-- 卡号 -->
            <div style="font-weight: 500">{{ t('contact_number') }}:</div>
            <div style="color: rgba(0, 0, 0, 0.4); font-weight: 600; font-size: 0.8em">
              {{ bankCardInfo.contactNumber }}
            </div>

            <!-- 备注信息 -->
            <div style="font-weight: 500">{{ t('other_description') }}:</div>
            <div style="color: rgba(0, 0, 0, 0.4); font-weight: 600; font-size: 0.8em">
              {{ bankCardInfo.otherDescription }}
            </div>
          </div>
        </div>
      </div>

      <!-- 提现按钮 -->
      <div style="display: flex; justify-content: center; align-items: center">
        <div
          style="
            margin-top: 10px;
            width: 80%;
            border-radius: 32px;
            padding: 12px;
            color: #fff;
            font-weight: 590;
            text-align: center;
          "
          :style="{
            background:
              bankCardInfo?.status === 'PASS'
                ? 'linear-gradient(135deg, #BB92FF 2.82%, #8B45FF 99.15%), linear-gradient(135deg, #D1CED6 2.82%, #7C7882 99.15%)'
                : 'linear-gradient(135deg, #D1CED6 2.82%, #7C7882 99.15%)',
          }"
          @click="CashOut"
        >
          {{ t('cash_out') }}
        </div>
      </div>
    </div>

    <!-- 弹窗遮罩层 -->
    <maskLayer :maskLayerShow="maskLayerShow" @click="closedPopup">
      <!-- 资料不足提示弹窗 -->
      <div
        v-if="cashOutTipShow"
        style="
          width: 100vw;
          height: 100vh;
          display: flex;
          justify-content: center;
          align-items: center;
        "
        @click="closedPopup"
      >
        <div
          style="
            width: 80%;
            border-radius: 12px;
            background: #fff;
            padding: 12px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
          "
          @click.stop
        >
          <div style="color: rgba(0, 0, 0, 0.8); font-weight: 800">{{ t('tips') }}</div>
          <div style="color: rgba(0, 0, 0, 0.4); font-weight: 600; font-size: 0.8em">
            {{ t('fill_info_tips') }}
          </div>
          <div style="color: rgba(0, 0, 0, 0.4); font-weight: 600; font-size: 0.6em">
            {{ t('card_issue_tips') }}
          </div>
          <div
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              border-radius: 12px;
              background: linear-gradient(
                152deg,
                rgba(198, 112, 255, 0.8) 7.01%,
                rgba(119, 38, 255, 0.8) 92.99%
              );

              color: #fff;
              font-weight: 800;
              padding: 8px 12px;
              width: 50%;
            "
            @click="gotoKYC"
          >
            {{ t('receive') }}
          </div>
        </div>
      </div>

      <!-- 选择提现方式抽屉 -->
      <div
        v-if="cashOutTypeShow"
        style="position: fixed; bottom: 0; width: 100%"
        @click="closedPopup"
      >
        <div
          style="
            background: white;
            border-radius: 16px 16px 0 0;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            gap: 10px;
            padding: 20px;
          "
          @click.stop
        >
          <div style="display: flex; justify-content: center; align-items: center">
            <div style="margin: 0; font-size: 18px; font-weight: 600; color: #333">
              {{ t('cash_out') }}
            </div>
          </div>

          <!-- 选择支付方式 -->
          <div style="box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25); border-radius: 8px; padding: 12px">
            <div style="font-size: 0.9em; font-weight: 600; margin-bottom: 4px">
              {{ t('withdrawal_method') }}: {{ usedBankCard?.cardType || '' }}
            </div>
            <div v-if="usedBankCard" style="font-size: 0.9em; font-weight: 600; margin-bottom: 4px">
              {{ t('card_number') }}: {{ usedBankCard?.cardNo }}
            </div>
            <div
              style="display: flex; justify-content: space-between; align-items: center"
              @click="gotoselectBank"
            >
              <div v-if="usedBankCard" style="font-size: 0.9em; font-weight: 600">
                {{ t('change_withdrawal_method') }}
              </div>
              <div v-else style="font-size: 0.9em; font-weight: 600">
                {{ t('please_select_bank_card') }}
              </div>
              <img src="/src/assets/icon/arrow.png" alt="" style="width: 6vw" class="flipImg" />
            </div>
          </div>

          <!-- 输入提现金额 -->
          <div style="box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25); border-radius: 8px; padding: 12px">
            <input
              type="number"
              min="50"
              name=""
              id=""
              :placeholder="t('enter_cash_out_amount')"
              style="
                width: 100%;
                outline: none;
                border: none;
                background-color: transparent;
                color: black;
              "
              :value="cashOutAmount"
              @input="handleCashOutAmountInput"
            />
          </div>

          <div style="color: rgba(0, 0, 0, 0.4); font-weight: 600; font-size: 0.9em">
            {{ t('new_year_cash_out_minimum') }}
          </div>

          <div style="display: flex; justify-content: center; align-items: center">
            <div
              style="
                margin-top: 10px;
                width: 80%;
                border-radius: 32px;
                padding: 12px;
                color: #fff;
                font-weight: 590;
                text-align: center;
              "
              :style="{
                background: checkStatus
                  ? 'linear-gradient(135deg, #BB92FF 2.82%, #8B45FF 99.15%), linear-gradient(135deg, #D1CED6 2.82%, #7C7882 99.15%)'
                  : 'linear-gradient(135deg, #D1CED6 2.82%, #7C7882 99.15%)',
              }"
              @click="Receive"
            >
              {{ t('cash_out') }}
            </div>
          </div>
        </div>
      </div>

      <!-- 等待审核提示弹窗 -->
      <div
        v-if="cashOutShow"
        style="
          width: 100vw;
          height: 100vh;
          display: flex;
          justify-content: center;
          align-items: center;
        "
        @click="closedPopup"
      >
        <div
          style="
            width: 80%;
            border-radius: 12px;
            background: #fff;
            padding: 12px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
          "
          @click.stop
        >
          <div style="color: rgba(0, 0, 0, 0.8); font-weight: 800">{{ t('tips') }}</div>
          <div style="color: rgba(0, 0, 0, 0.4); font-weight: 600; font-size: 0.8em">
            {{ t('cash_withdrawal_tips') }}
          </div>
          <div
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              border-radius: 12px;
              background: linear-gradient(
                152deg,
                rgba(198, 112, 255, 0.8) 7.01%,
                rgba(119, 38, 255, 0.8) 92.99%
              );

              color: #fff;
              font-weight: 800;
              padding: 8px 12px;
              width: 50%;
            "
            @click="closedPopup"
          >
            {{ t('receive') }}
          </div>
        </div>
      </div>
    </maskLayer>
  </div>
</template>

<script setup>
import { useI18n } from 'vue-i18n'
import { setApplyInfo, getApplyInfo } from '@/utils/applyStore.js'
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { setDocumentDirection } from '@/locales/i18n'

import {
  withdrawableAmount, //获取可提现金额
  withdrawApply, //提交提现申请
} from '@/api/lottery'
import {
  getBankCardList, //获取正在使用的银行卡
  getWithdrawInfoList, //获取申请提现信息
} from '@/api/wallet.js'

import GeneralHeader from '@/components/GeneralHeader.vue'
import maskLayer from '@/components/MaskLayer.vue'

const { t, locale } = useI18n()
const router = useRouter()
const route = useRoute()

// 监听语言变化并设置文档方向
locale.value && setDocumentDirection(locale.value)

const cashOutTipShow = ref(false)
const cashOutTypeShow = ref(false)
const cashOutShow = ref(false)

const cashOutAmount = ref(null)

const maskLayerShow = computed(() => {
  return cashOutTipShow.value || cashOutShow.value || cashOutTypeShow.value
})

const usedBankCard = ref(null) //正在使用的银行卡

const closedPopup = () => {
  cashOutTipShow.value = false
  cashOutShow.value = false
  cashOutTypeShow.value = false
}

const activityId = route.query.activityId || ''

const currentAmount = ref(0) //可提现金额
const availableBalance = computed(() => {
  return currentAmount.value.availableAmount || 0
})

const bankCardInfo = ref(null)
const hasKYC = computed(() => {
  return bankCardInfo.value != null
})

// 查看历史提现信息
const lookDetails = () => {
  router.push({ path: '/cash-out-details', query: { activityId: activityId } })
}

// 查看历史提现信息
const gotoKYC = () => {
  router.push('/KYC')
}

// 提现按钮
const CashOut = () => {
  if (hasKYC.value && bankCardInfo.value?.status === 'PASS') {
    cashOutTypeShow.value = true
  } else if (!hasKYC.value) {
    cashOutTipShow.value = true
  }
}

// 是否可以提现
const checkStatus = computed(() => {
  return bankCardInfo.value?.status == 'PASS' && usedBankCard.value?.id && cashOutAmount.value >= 10
})

// 确认提现
const Receive = async () => {
  if (checkStatus.value) {
    try {
      const resApply = await withdrawApply({
        activityId: activityId,
        amount: cashOutAmount.value,
        contactNumber: bankCardInfo.value.contactNumber,
        cardImages: JSON.stringify(bankCardInfo.value.previewUrls),
        description: bankCardInfo.value.otherDescription,
      })
      if (resApply.status) {
        closedPopup()
        await withdrawableAmount(activityId) // 刷新银行余额
        cashOutShow.value = true
      }
    } catch (error) {
      closedPopup()
      console.log('提现失败:', error.response?.errorMsg)
      showError(t('something_went_wrong'))
    }
  }
}

//获取可提现金额
const getDrawableAmount = async () => {
  const resDrawableAmount = await withdrawableAmount(activityId)
  if (resDrawableAmount.status && resDrawableAmount.body) {
    currentAmount.value = resDrawableAmount.body
  } else {
    currentAmount.value = 0
  }
}

//处理提现金额输入
const handleCashOutAmountInput = (event) => {
  let value = parseFloat(event.target.value)

  if (value > availableBalance.value) {
    value = availableBalance.value
    event.target.value = value // 更新输入框的值
  }
  cashOutAmount.value = value // 更新 cashOutAmount 的值
}

// 获取提现信息列表
const getWithdrawInfoListData = async () => {
  try {
    const resWithdrawInfoList = await getWithdrawInfoList()
    console.log('提现信息列表:', resWithdrawInfoList)
    if (resWithdrawInfoList.status && resWithdrawInfoList.body?.length > 0) {
      let imgList = JSON.parse(resWithdrawInfoList.body[0].passportFrontUrl)
      let previewUrls = imgList.map((item) => item)
      bankCardInfo.value = { previewUrls, ...resWithdrawInfoList.body[0] }
    }
  } catch (error) {
    console.error('获取提现信息列表失败:', error)
    showError(error.response?.errorMsg)
  }
}

// 获取银行卡列表
const getBankCards = async () => {
  try {
    const resBankCards = await getBankCardList()
    console.log('银行卡列表:', resBankCards)
    if (resBankCards.status && resBankCards.body) {
      // 处理银行卡列表数据
      resBankCards.body.forEach((card) => {
        if (card.use) {
          usedBankCard.value = card
        }
      })
    }
  } catch (error) {
    console.error('获取银行卡列表失败:', error)
  }
}

onMounted(() => {
  getDrawableAmount() //获取可提现金额
  getWithdrawInfoListData() // 获取提现信息列表
  getBankCards() // 获取正在使用的银行卡
})

onUnmounted(() => {
  setApplyInfo()
})
</script>

<style lang="scss" scoped>
* {
  color: rgba(0, 0, 0, 0.8);
}

.fullPage {
  width: 100vw;
  min-height: 100vh;
  background-color: #fff;
  background-image: url(/src/assets/images/secondBg.png);
  background-size: 100% auto;
  background-repeat: no-repeat;
  position: relative;
}

@media screen and (max-width: 360px) {
  * {
    font-size: 10px;
  }
}

@media screen and (min-width: 360px) {
  * {
    font-size: 16px;
  }
}

@media screen and (min-width: 768px) {
  * {
    font-size: 24px;
  }
}

@media screen and (min-width: 1024px) {
  * {
    font-size: 32px;
  }
}

/* RTL支持 */
[dir='rtl'] .flipImg {
  transform: scaleX(-1);
}
</style>
