<script setup lang="ts">
// 页面效果查看
// https://ai.ccnetcore.com/pay-result?charset=UTF-8&out_trade_no=YI_20251015232040_3316&method=alipay.trade.page.pay.return&total_amount=215.90&sign=htfny1D%2B8wcLZzK7StevZG%2BD441RLXvksoAR%2BzOq%2B1WHMwfJdVkzyZF2bBmvbU%2FsHBB2HMl8TT3KoaHaf8UfWZgtDGbMoQC%2F1O%2BRcEw8jljlpW3XLMdKGx6dytqZkhq9lRD6tR3ofBiuviv2PmxVd1l%2Bcqs7nwNWwKJWonWI0c5UOE%2BYWgg3hjEJnMYVQjUb6FvrVLfANEU0YyTO%2Bi6vL55Gwug6GIXvGqUPZc3GbwXc%2FUHnu1qv4Yi6tc1dtUoLUNHVfTKrC2N55T84AALZteIK0m7suzrkvBPcKdpn4NGVDtv5cCBCHPjtD3COrNISrNUf3sQXpTvqJGw6dWag6g%3D%3D&trade_no=2025101522001438971445003566&auth_app_id=2021005182687851&version=1.0&app_id=2021005182687851&sign_type=RSA2&seller_id=2088870286599802&timestamp=2025-10-15+23%3A21%3A01

import { ElButton, ElDivider, ElMessage } from 'element-plus';
import { computed, onMounted, ref } from 'vue';

import { useRouter } from 'vue-router';

import { getUserInfo } from '@/api';
import {
  SSO_SEVER_URL,
} from '@/config/sso.ts';

import { useUserStore } from '@/stores';
import { useSessionStore } from '@/stores/modules/session.ts';

const userStore = useUserStore();
const router = useRouter();
const sessionStore = useSessionStore();
const innerVisibleContact = ref(false);
const showWechatFullscreen = ref(false);
const showWxGroupFullscreen = ref(false);

interface PayResult {
  out_trade_no: string;
  trade_no: string;
  total_amount: string;
  [key: string]: string;
}

const payResult = ref<PayResult>({
  out_trade_no: '',
  trade_no: '',
  total_amount: '',
});

function parseUrlParams() {
  const params = new URLSearchParams(window.location.search);
  const result: PayResult = {
    out_trade_no: params.get('out_trade_no') || '',
    trade_no: params.get('trade_no') || '',
    total_amount: params.get('total_amount') || '',
  };
  params.forEach((value, key) => {
    if (!(key in result))
      result[key] = value;
  });
  payResult.value = result;
}

onMounted(() => {
  parseUrlParams();
});
async function onReLogin() {
  // 在这里执行退出方法
  await userStore.logout();
  // 清空回话列表并回到默认页
  await sessionStore.requestSessionList(1, true);
  await sessionStore.createSessionBtn();
  ElMessage({
    type: 'success',
    message: '退出成功',
  });
  await router.replace('/');
}
function handleThirdPartyLogin(type: any) {
  const redirectUri = encodeURIComponent(`${window.location.origin}/chat`);
  const popup = window.open(
    `${SSO_SEVER_URL}/login?client_id=${type}&redirect_uri=${redirectUri}`,
    'SSOLogin',
    'width=1000,height=800',
  );

  // 使用标志位防止重复执行
  let isHandled = false;

  const messageHandler = async (event: any) => {
    if (event.origin === new URL(SSO_SEVER_URL).origin
      && event.data.type === 'SSO_LOGIN_SUCCESS'
      && !isHandled) {
      isHandled = true;
      try {
        // 清理监听
        window.removeEventListener('message', messageHandler);
        const { token, refreshToken } = event.data;
        userStore.setToken(token, refreshToken);
        const resUserInfo = await getUserInfo();
        userStore.setUserInfo(resUserInfo.data);
        // 关闭弹窗
        if (popup && !popup.closed) {
          popup.close();
        }

        // 后续逻辑
        ElMessage.success('登录成功');
        userStore.closeLoginDialog();
        await sessionStore.requestSessionList(1, true);
        await router.replace('/');
      }
      catch (error) {
        console.error('登录处理失败:', error);
        ElMessage.error('登录失败');
      }
    }
  };

  // 先移除旧监听，再添加新监听
  window.removeEventListener('message', messageHandler);
  window.addEventListener('message', messageHandler);

  // 超时自动清理
  // setTimeout(() => {
  //   if (!isHandled) {
  //     window.removeEventListener('message', messageHandler);
  //     if (popup && !popup.closed)
  //       popup.close();
  //     ElMessage.warning('登录超时');
  //   }
  // }, 60 * 1000); // 60分钟超时关闭
}

function toHome() {
  router.replace('/');
}

const wxSrc = computed(
  () => `${import.meta.env.VITE_WEB_BASE_API}/wwwroot/aihub/wx.png`,
);
const wxGroupQD = computed(
  () => `${import.meta.env.VITE_WEB_BASE_API}/wwwroot/aihub/jlq.png`,
);

// 显示微信二维码全屏
function showWechatFullscreenImage() {
  showWechatFullscreen.value = true;
}

// 显示微信群二维码全屏
function showWxGroupFullscreenImage() {
  showWxGroupFullscreen.value = true;
}

// 关闭全屏图片
function closeFullscreenImage() {
  showWechatFullscreen.value = false;
  showWxGroupFullscreen.value = false;
}

// 复制微信号
function copyWechatId() {
  navigator.clipboard.writeText('chengzilaoge520').then(() => {
    ElMessage({
      message: '微信号已复制到剪贴板',
      type: 'success',
      duration: 2000,
    });
  });
}

// 联系售后弹窗
function contactCustomerService() {
  innerVisibleContact.value = !innerVisibleContact.value;
}
</script>

<template>
  <div class="pay-result-container flex flex-col items-center justify-center p-6 min-h-screen bg-gray-50">
    <div class="card bg-white rounded-xl shadow-lg p-8 max-w-md w-full text-center">
      <!-- 成功提示 -->
      <h1 class="text-4xl font-extrabold mb-4 text-orange-500">
        🎉 恭喜！
      </h1>
      <p class="text-xl font-semibold mb-6">
        您已充值成功
        <!--        您已成为尊贵的 <span class="text-orange-500">YixinAI VIP</span> -->
      </p>

      <!-- 订单信息卡片 -->
      <div class="order-info bg-gray-100 p-4 rounded-lg mb-4 text-left">
        <p class="mb-2">
          <strong>商户订单号：</strong>{{ payResult.out_trade_no }}
        </p>
        <p class="mb-2">
          <strong>支付交易号：</strong>{{ payResult.trade_no }}
        </p>
        <p class="mb-0">
          <strong>支付金额：</strong><span class="text-red-500 font-bold">¥{{ payResult.total_amount }}</span>
        </p>
      </div>

      <!-- 更多信息提示 -->
      <div class="mb-6 text-gray-600 text-sm">
        更多订单信息和会员详情<br>请前往 <strong>控制台 → 充值记录</strong> 查看。<br>
        控制台在首页右上角个人头像点击下拉菜单。
      </div>

      <!-- 重新登录提示 -->
      <!--      绿色背景 -->
      <div class="mb-4 text-gray-600 ">
        开通 VIP 后，需要重新登录生效。<br>
      </div>
      <div v-if="false" class="order-info p-4 rounded-lg mb-4 bg-[#ffc406] mb-4 text-gray-600 ">
        加入售后群获得更多专业支持！
      </div>

      <ElDivider content-position="center">
        <span class="text-gray-400 text-sm">操作</span>
      </ElDivider>

      <!-- 按钮区域 -->
      <div class="flex ">
        <ElButton
          class="w-full py-3 text-lg font-medium"
          type="primary"
          size="large"
          @click="onReLogin()"
        >
          重新登录
        </ElButton>

        <ElButton
          class="w-full py-3 text-lg font-medium"
          type="default"
          size="large"
          @click="toHome()"
        >
          返回首页
        </ElButton>
      </div>

      <ElButton
        class="mt-6 w-full py-3 text-lg font-medium"
        type="default"
        size="large"
        @click="contactCustomerService()"
      >
        联系客服获取售后支持
      </ElButton>
    </div>
  </div>

  <el-dialog
    v-model="innerVisibleContact"
    width="500"
    title="售后支持"
    append-to-body
  >
    <h3 class="text-lg font-bold mb-3">
      请扫码加入微信交流群<br>
      备注ai获取专属客服支持
    </h3>
    <div class="py-10 flex items-center justify-center space-x-2">
      <span class="font-semibold">站长微信账号：</span>
      <span id="wechat-id" class="text-blue-600 font-mono select-text">chengzilaoge520</span>

      <span
        class="cursor-pointer"
        title="点击复制"
        @click="copyWechatId"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 opacity-70 hover:opacity-100" viewBox="0 0 24 24" fill="currentColor">
          <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v16h14c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 18H8V7h11v16z" />
        </svg>
      </span>
    </div>

    <div class="flex justify-center mb-4">
      <div class="px-4">
        <h4>站长微信(备注“AI”以便通过)</h4>
        <img
          :src="wxSrc"
          class="w-50 h-70 py-5  border border-gray-200 rounded-lg shadow-md cursor-pointer hover:shadow-lg transition-transform hover:scale-105"
          alt="微信二维码"
        >
      </div>
      <div class="px-4">
        <h4>微信交流群</h4>
        <img
          :src="wxGroupQD"
          class="w-50  py-5 h-70 border border-gray-200 rounded-lg shadow-md cursor-pointer hover:shadow-lg transition-transform hover:scale-105"
          alt="微信二维码"
        >
      </div>
    </div>

    <!-- 全屏放大二维码 -->
  </el-dialog>
</template>

<style scoped lang="scss">
.pay-result-container {
  .card {
    transition: transform 0.2s;
    &:hover {
      transform: translateY(-5px);
    }
  }
  .order-info p {
    font-size: 1rem;
  }
  .el-button {
    border-radius: 8px;
  }
  @media (max-width: 768px) {
    .card {
      padding: 6vw;
    }
    .order-info p {
      font-size: 0.95rem;
    }
    .el-button {
      font-size: 1rem;
    }
  }
}
</style>
