<template>
  <div class="form-item">
    <label>{{ $t('recharge.remainingCoins') }}</label>
    <div class="select-wrapper">
      <el-input
          type="text"
          readonly="readonly"
          v-model="useUserInfoStore.userInfo.coin_amount"
          class="w-full px-3 py-2 border rounded-md"
      >
        <template #append> <el-button class="recharge-btn" @click="openDialog()" v-log="{ describe: { action: '点击充值' } }">{{ $t('recharge.recharge') }}</el-button></template>
      </el-input>
    </div>
    <div class="fs-12 c-666">{{ $t('recharge.coinTip') }}</div>
  </div>

  <el-dialog v-model="showRechargeDialog"
             :title="$t('recharge.rechargeTitle')"
             width="700px"
             :height="630 + 'px'"
             @close="onClose"
             :destroy-on-close="true">
    <div v-if="loading" class="loading-text flex" style="width: 660px; height: 610px;" >{{ $t('recharge.loading') }}</div>
    <iframe v-show="!loading" :src="rechargeUrl" width="660" height="610" frameborder="0" @load="onIframeLoad"></iframe>
  </el-dialog>
</template>

<script setup lang="ts">
import { configs } from '@/utils/appconfig';
import { ref, onMounted, onUnmounted } from "vue";
import useUserInfo from "@/stores/modules/user";
const useUserInfoStore = useUserInfo();
import tokenInfo from '@/stores/modules/token';
const tokenInfoStore = tokenInfo();
import { getWebUrlrUrl } from '@/utils/appfun'

const showRechargeDialog = ref(false);
const rechargeUrl = ref(getWebUrlrUrl({
  url:'/other/recharge_gold_coin'
}));
const loading = ref(true);

const onIframeLoad = () => {
  loading.value = false;
};

const handleWindowMessage = async (event) => {
  const message = event.data;
  if (message.type === 'close') {
    showRechargeDialog.value = false;
    await useUserInfoStore.getInfo();
    loading.value = false;
  }
};

const onClose = async () => {
  await useUserInfoStore.getInfo();
  loading.value = false;
};

const openDialog = () => {
  showRechargeDialog.value = true;
  loading.value = false;
};

onMounted(() => {
  window.addEventListener('message', handleWindowMessage);
});

onUnmounted(() => {
  window.removeEventListener('message', handleWindowMessage);
});
</script>
<style scoped lang="scss">
.recharge-btn {
  background: linear-gradient( 180deg, #FFAF51 0%, #FF7272 100%);
  border-radius: 6px;
  color: #fff !important;
}
.select-wrapper {
  ::v-deep {
    .el-input-group__append{
    }
  }
}
</style>
