<template>
  <div class="box">
    <!-- 添加全屏加载效果 -->
    <div v-loading="loading" class="loading-container">
      <iframe v-if="url" :src="url" frameborder="0" class="baidu-style">
      </iframe>
      <div v-else class="login-prompt">
        <p>请先登录百度云账号</p>
        <button @click="getToken">重试</button>
      </div>
    </div>
  </div>
</template>

<script>
import { baiducloudAPI } from '@/api/BaiDuTokenapi'
import { reqBaiduJudgePrice, reqConfirmBtn } from '@/api/baidu'

export default {
  name: 'baiduProductShow',
  data() {
    return {
      userToken: '',
      url: '',
      loading: true,
      userid: '',
    }
  },
  async created() {
    await this.getToken();
  },
  mounted() {
    window.addEventListener('message', this.receiveMessage, false);
  },
  beforeDestroy() {
    window.removeEventListener('message', this.receiveMessage, false);
  },
  methods: {
    // 获取百度云token
    async getToken() {
      try {
        this.loading = true;
        const response = await baiducloudAPI();
        this.userToken = response.data;
        if (this.userToken) {
          const baseUrl = 'https://console.vcp.baidu.com/api/loginvcp/login/securitytoken';
          const redirectUrl = encodeURIComponent('https://console.vcp.baidu.com/billing/#/refund/list');
          const token = encodeURIComponent(this.userToken);
          this.url = `${baseUrl}?redirectUrl=${redirectUrl}&signinSecurityToken=${token}`;
        } else {
          console.error('未能从API响应中获取到token:', response);
          this.$message.error('获取登录信息失败，请重试');
        }
      } catch (error) {
        console.error('获取百度云Token失败:', error);
        this.$message.error('网络错误，获取登录信息失败');
      } finally {
        this.loading = false;
      }
    },

    receiveMessage(event) {
      console.log('接收到消息:', event);
      const data = event.data;
      console.log('接收到的 data 是:', data);

      // 2. 检查是否存在 refundInfo 和 uuidList
      if (data && data.refundInfo && Array.isArray(data.refundInfo.uuidList) && data.refundInfo.uuidList.length > 0) {
        const uuidListArray = data.refundInfo.uuidList; // 这是一个数组

        console.log('提取到的订单ID:', uuidListArray);

        // 4. 获取用户ID
        this.userid = sessionStorage.getItem('userId');
        if (!this.userid) {
          console.error('未获取到用户ID (sessionStorage 中缺少 userId)');
          this.$message.error('用户信息获取失败，请重新登录');
          return;
        }

        // 5. 构造请求参数
        const payload = {
          order_id: uuidListArray,
          userid: this.userid
        };

        // 6. 显示加载状态
        this.loading = true;

        // 7. 调用退订API
        reqConfirmBtn(payload)
          .then((res) => {
            console.log("调用 reqBaiduJudgePrice 接口返回:", res);
            if (res.status) { // 假设 status 为 true 表示成功
              this.$message.success('退订成功');
              // 修复页面跳转 - 使用 path 而不是 url
              this.$router.push({
                path: '/customer/unsubscribe/BaiduNetdisk',
              });
            } else {
              // 显示后端返回的错误信息
              this.$message.error(res.msg || '退订失败，请稍后重试');
            }
          })
          .catch((error) => {
            // 捕获网络错误或请求异常 (如超时、连接失败)
            console.error("调用退订接口 reqBaiduJudgePrice 失败 (网络/请求错误):", error);
            this.$message.error('网络请求失败或服务异常，请检查网络连接后重试');
          })
          .finally(() => {
            // 无论成功或失败，都结束加载状态
            this.loading = false;
          });
      } else {
        console.log('接收到的消息不包含有效的退款信息或 uuidList 为空');
      }
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  padding: 10px;
  height: 100%;
}

.loading-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.login-prompt {
  text-align: center;
  padding: 50px;
}

.baidu-style {
  width: 100%;
  height: calc(100vh - 100px);
}
</style>
