<template>
  <div>
    <div v-if="!hasToken" class="text-center">
      <el-button type="primary" :loading="loading" @click="handleGetToken">获取令牌</el-button>
    </div>
    <div v-else>
      <el-form label-width="100px" label-position="left">
        <el-form-item label="余额：">
          <div>{{ balance }}</div>
        </el-form-item>
        <el-form-item label="API Key：">
          <el-tooltip effect="dark" :content="apiKey" placement="top">
            <span class="secret-text">{{ maskedKey }}</span>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="服务地址：">
          <el-tooltip effect="dark" :content="baseUrl" placement="top">
            <span class="secret-text">{{ baseUrl }}</span>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <el-form :model="rechargeForm" label-width="100px" label-position="left">
        <el-form-item label="充值金额：">
          <el-input-number v-model="rechargeForm.amount" :min="0" :precision="2" />
          <el-button type="primary" @click="handleRecharge" :loading="rechargeLoading" class="ml20">充值</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 支付二维码弹窗 -->
    <el-dialog
        :title="qrCode.title"
        v-model="qrCode.visible"
        width="385px"
        append-to-body
        :align-center="true"
        :close-on-click-modal="false"
        @closed="clearQueryInterval"
    >
      <div class="text-center">
        <p>充值金额：¥{{ rechargeForm.amount }}</p>
        <p style="color: #999; font-size: 12px;">请使用微信或支付宝扫码支付</p>
        <div v-if="qrCode.url" style="width: 200px; height: 200px; margin: 10px auto;">
          <img :src="qrCode.url" style="width: 100%; height: 100%;" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getTokenInfo, getToken, createRecharge, getRecharge } from "@/api/console";
import { ElMessage, ElMessageBox } from "element-plus";
import QRCode from "qrcode";

const { proxy } = getCurrentInstance();

const loading = ref(false);
const hasToken = ref(false);
const balance = ref("0.00");
const apiKey = ref("");
const maskedKey = ref("");
const baseUrl = ref("");
const rechargeLoading = ref(false);

// 轮询相关
const queryInterval = ref(undefined);
const currentRechargeId = ref(undefined);

const rechargeForm = reactive({
  amount: 0
});

const qrCode = ref({
  url: '',
  title: '请使用微信或支付宝扫码支付',
  visible: false
});

function maskKey(key) {
  if (!key || key.length < 12) return key;
  return key.substring(0, 6) + "****" + key.substring(key.length - 6);
}

function loadTokenInfo() {
  getTokenInfo().then(response => {
    if (response && response.apiKey && response.hasToken) {
      hasToken.value = true;
      apiKey.value = response.apiKey;
      maskedKey.value = maskKey(response.apiKey);
      // 显示真实 New API 余额
      if (response.balance) {
        balance.value = response.balance;
      }
      // 显示 New API 服务地址
      if (response.baseUrl) {
        baseUrl.value = response.baseUrl;
      }
    }
  }).catch(() => {
    // 忽略错误，保持当前状态
  });
}

function handleGetToken() {
  loading.value = true;
  getToken().then(response => {
    if (response && response.success && response.apiKey) {
      hasToken.value = true;
      apiKey.value = response.apiKey;
      maskedKey.value = maskKey(response.apiKey);
      proxy.$modal.msgSuccess("获取令牌成功");
    } else {
      proxy.$modal.msgError(response?.message || "获取令牌失败");
    }
    loading.value = false;
  }).catch(error => {
    loading.value = false;
    proxy.$modal.msgError("获取令牌失败: " + (error.message || "未知错误"));
  });
}

function handleRecharge() {
  if (rechargeForm.amount <= 0) {
    proxy.$modal.msgError("请输入正确的充值金额");
    return;
  }

  rechargeLoading.value = true;
  qrCode.value.url = "";

  createRecharge(rechargeForm.amount).then(response => {
    if (response && response.data && response.data.id) {
      // 保存当前充值ID用于轮询
      currentRechargeId.value = response.data.id;

      // 生成二维码
      if (response.data.qrCodeUrl) {
        QRCode.toDataURL(response.data.qrCodeUrl, { errorCorrectionLevel: 'L', margin: 2, width: 200 }, (err, url) => {
          if (err) {
            proxy.$modal.msgError("生成二维码失败");
            rechargeLoading.value = false;
            return;
          }
          qrCode.value.url = url;
          qrCode.value.visible = true;
          // 开始轮询
          createQueryInterval(currentRechargeId.value);
        });
      } else {
        proxy.$modal.msgError("获取支付链接失败");
      }
      proxy.$modal.msgSuccess("充值订单已创建");
    } else {
      proxy.$modal.msgError("创建充值订单失败");
    }
    rechargeLoading.value = false;
  }).catch(error => {
    rechargeLoading.value = false;
    proxy.$modal.msgError("充值失败: " + (error.message || "未知错误"));
  });
}

// 轮询查询充值状态
const createQueryInterval = (rechargeId) => {
  if (queryInterval.value) {
    return;
  }
  queryInterval.value = setInterval(async () => {
    try {
      const res = await getRecharge(rechargeId);
      console.log('充值轮询结果:', res);

      // 已支付
      if (res.data && res.data.payStatus === 1) {
        clearQueryInterval();
        ElMessageBox.confirm(
            '支付成功',
            '提示',
            {
              confirmButtonText: '确认',
              showCancelButton: false,
              type: 'success'
            }
        ).then(() => {
          qrCode.value.visible = false;
          loadTokenInfo()
        });
      }

      // 支付失败
      if (res.data && res.data.payStatus === -1) {
        clearQueryInterval();
        ElMessage.error('支付失败！');
        qrCode.value.visible = false;
      }
    } catch (e) {
      // 静默捕获轮询异常
    }
  }, 1000 * 2); // 每2秒轮询一次
};

// 清除轮询和弹窗
const clearQueryInterval = () => {
  qrCode.value.visible = false;
  qrCode.value.url = '';
  qrCode.value.title = '请使用微信或支付宝扫码支付';
  // 清除轮询任务
  if (queryInterval.value) {
    clearInterval(queryInterval.value);
    queryInterval.value = undefined;
  }
  currentRechargeId.value = undefined;
};

onMounted(() => {
  loadTokenInfo();
});

onUnmounted(() => {
  // 组件销毁时清除轮询
  try {
    clearQueryInterval();
  } catch (e) {}
});
</script>

<style scoped lang="scss">
.secret-text {
  font-family: monospace;
  font-size: 12px;
  cursor: pointer;
}
</style>
