<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="http://phslgld.hnluchuan.com:3000/" placement="top">
            <span class="secret-text">http://phslgld.hnluchuan.com:3000/</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="安全使用承诺"
        v-model="safetyDialog.visible"
        width="500px"
        append-to-body
        :align-center="true"
        :close-on-click-modal="false"
    >
      <div class="safety-content">
        <h4>合规使用告知</h4>
        <div class="safety-text">
          <p>1. 本平台仅提供大模型API调用服务，不得用于任何违法违规用途。</p>
          <p>2. 使用本服务即表示您承诺遵守当地法律法规，不得利用本服务从事违规违法活动。</p>
          <p>3. 您承诺不会使用本服务进行网络攻击、恶意爬虫、欺诈或其他有害行为。</p>
          <p>4. 如发现违规使用行为，平台有权立即终止服务并追究相关责任。</p>
          <p>5. 请妥善保管您的API Key，因个人保管不当导致的损失由用户自行承担。</p>
        </div>
        <el-checkbox v-model="safetyDialog.checked" class="safety-checkbox">
          我已阅读并同意以上安全使用条款，承诺合规使用
        </el-checkbox>
      </div>
      <template #footer>
        <el-button @click="safetyDialog.visible = false">取消</el-button>
        <el-button type="primary" :disabled="!safetyDialog.checked" @click="confirmRecharge">确认充值</el-button>
      </template>
    </el-dialog>

    <!-- 支付二维码弹窗 -->
    <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
});

const STORAGE_KEY_SAFETY_AGREED = 'safety_agreement_agreed';

const safetyDialog = ref({
  visible: false,
  checked: false
});

// 检查是否已同意过安全承诺
function hasSafetyAgreement() {
  return localStorage.getItem(STORAGE_KEY_SAFETY_AGREED) === 'true';
}

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("获取令牌成功");
      loadTokenInfo()
    } 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;
  }

  // 若用户已同意过安全承诺，直接充值
  if (hasSafetyAgreement()) {
    doRecharge();
    return;
  }

  // 重置勾选状态并弹出安全承诺弹窗
  safetyDialog.value.checked = false;
  safetyDialog.value.visible = true;
}

// 确认充值
function confirmRecharge() {
  if (!safetyDialog.value.checked) {
    proxy.$modal.msgError("请先勾选同意安全使用条款");
    return;
  }

  // 记录用户已同意安全承诺
  localStorage.setItem(STORAGE_KEY_SAFETY_AGREED, 'true');

  safetyDialog.value.visible = false;
  doRecharge();
}

function doRecharge() {
  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;
}

.safety-content {
  h4 {
    margin: 0 0 12px 0;
    color: #303133;
  }
}

.safety-text {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;

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

.safety-checkbox {
  font-weight: 500;
}
</style>
