<template>
  <div class="box">
    <!-- 实名认证通知 -->
    <div v-if="showAuthNotification" class="auth-notification-container">
      <!-- 展开状态：完整提示窗口 -->
      <div v-show="isNotificationExpanded" class="notification-card">
        <div class="notification-header">
          <div class="notification-title">
            <i class="notification-icon el-icon-warning"></i>
            <span>实名认证提示</span>
          </div>
          <button class="collapse-btn" @click="toggleNotification" aria-label="收起提示">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
        <div class="notification-content">
          <p>您当前还没有完成实名认证，部分功能可能受限。请先完成<span class="link-text" @click="goToAuth">实名认证</span>，以确保正常使用所有服务。</p>
        </div>
      </div>

      <!-- 收起状态：简化按钮 -->
      <div v-show="!isNotificationExpanded" class="notification-minimized" @click="toggleNotification">
        <div class="minimized-content">
          <i class="minimized-icon el-icon-warning"></i>
          <span>实名认证</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 添加全屏加载效果 -->
    <div v-loading="loading" class="loading-container">
      <iframe v-if="url" :src="url" frameborder="0" class="baidu-style">
      </iframe>

    </div>
  </div>
</template>

<script>
import { baiducloudAPI } from '@/api/BaiDuTokenapi'
import { reqBaiduJudgePrice, reqConfirmBtn } from '@/api/baidu'
import { reqIsReallyPeople } from '@/api/baidu' // 引入实名认证检查API

export default {
  name: 'baiduProductShow',
  data() {
    return {
      userToken: '',
      url: '',
      loading: true,
      userid: '',
      showAuthNotification: false, // 控制是否显示实名认证通知
      isNotificationExpanded: true, // 控制通知是展开还是收起状态
    }
  },
  async created() {
    await this.checkRealNameAuth();
    await this.getToken();
  },
  mounted() {
    window.addEventListener('message', this.receiveMessage, false);
  },
  beforeDestroy() {
    window.removeEventListener('message', this.receiveMessage, false);
  },
  methods: {
    // 检查实名认证状态
    async checkRealNameAuth() {
      try {
        this.userid = sessionStorage.getItem('userId');
        if (!this.userid) {
          console.warn('未获取到用户ID，无法检查实名认证状态');
          return;
        }

        const response = await reqIsReallyPeople({user_id: this.userid});
        // 假设API返回res.status为true表示已实名认证，false表示未实名认证
        this.showAuthNotification = !response.status;

        if (!response.status) {
          console.log('用户未完成实名认证，显示通知');
        }
      } catch (error) {
        console.error('检查实名认证状态失败:', error);
        // 出错时默认不显示通知，避免干扰用户体验
      }
    },

    // 跳转到实名认证页面
    goToAuth() {
      window.open('https://console.vcp.baidu.com/qualify/#/qualify/index', '_blank');
    },

    // 切换通知展开/收起状态
    toggleNotification() {
      this.isNotificationExpanded = !this.isNotificationExpanded;
    },

    // 获取百度云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);
          
        }
      } catch (error) {
        console.error('获取百度云Token失败:', 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('退订成功');
              // 刷新浏览器
              window.location.reload();
            } 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: calc(100vh - 100px);
  position: relative;
}

.loading-container {
  width: 100%;
  height: calc(100vh - 100px);
  position: relative;
}

.login-prompt {
  height: calc(100vh - 100px);
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.prompt-content {
  max-width: 300px;
  padding: 30px;
  border-radius: 8px;
  background: #f8f9fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.prompt-icon {
  font-size: 48px;
  color: #ffc107;
  margin-bottom: 16px;
}

.prompt-content p {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
}

.retry-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;

  &:hover {
    background: #40a9ff;
  }
}

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

/* 实名认证通知容器 */
.auth-notification-container {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  max-width: 380px;
}

/* 通知卡片样式 */
.notification-card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
  border: 1px solid #e8e8e8;
  overflow: hidden;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 通知头部 */
.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px 12px;
  border-bottom: 1px solid #f0f0f0;
}

.notification-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.notification-icon {
  color: #FFBA00;
  margin-right: 8px;
  font-size: 18px;
}

.collapse-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background-color: #f5f5f5;
    color: #666;
  }
}

/* 通知内容 */
.notification-content {
  padding: 16px 20px 20px;

  p {
    margin: 0;
    line-height: 1.6;
    color: #666;
    font-size: 14px;
  }
}

.link-text {
  color: #1890ff;
  cursor: pointer;
  text-decoration: none;
  margin: 0 4px;
  font-weight: 500;
  transition: color 0.2s;

  &:hover {
    color: #40a9ff;
    text-decoration: underline;
  }
}

/* 收起状态样式 */
.notification-minimized {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e8e8;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
}

.minimized-content {
  display: flex;
  align-items: center;
  padding: 10px 14px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.minimized-icon {
  color: #FFBA00;
  margin-right: 8px;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-notification-container {
    top: 10px;
    right: 10px;
    left: 10px;
    max-width: none;
  }

  .notification-card {
    border-radius: 8px;
  }

  .notification-header {
    padding: 12px 16px 8px;
  }

  .notification-content {
    padding: 12px 16px 16px;
  }
}
</style>
