<template>
<!--
  <div class="flex left fs-14 line-40 mar-top-10" style="margin-left: 100px">
    剩余金币：{{ useUserInfoStore.userInfo.coin_amount }}
    <el-button class="mar-left-10" @click="openDialog()" v-log="{ describe: { action: '点击充值金币' } }">充值金币</el-button>
  </div>
-->


  <div class="form-item">
    <label>剩余金币：</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: '点击充值' } }">充值</el-button></template>
      </el-input>
    </div>
    <div class="fs-12 c-666">（用户视频生成，需单独金币支付）</div>
  </div>

  <!-- 新增：充值金币弹窗 -->
  <el-dialog v-model="showRechargeDialog"
             title="充值金币"
             width="700px"
             :height="630 + 'px'"
             @close="onClose"
             :destroy-on-close="true">
    <!-- 显示 loading 提示 -->
    <div v-if="loading" class="loading-text flex" style="width: 660px; height: 610px;" >加载中，请稍候...</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); // 新增 loading 状态

// iframe 加载完成回调
const onIframeLoad = () => {
  loading.value = false;
};

// 消息监听函数
const handleWindowMessage = async (event) => {
  // 可选：验证 event.origin 来确保消息来源可信
  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>
