<template>
  <div class="grid gap-6 lg:grid-cols-[1fr_0.9fr]">
    <section class="panel p-5">
      <p class="text-sm font-semibold text-brand-700">实名认证</p>
      <h2 class="mt-2 text-xl font-bold text-slate-950">提交认证资料</h2>
      <p class="mt-2 text-sm leading-7 text-slate-500">
        部分操作可能要求先完成认证，例如下单、白名单新增或动态出口生成。
      </p>

      <form class="mt-6 grid gap-4" @submit.prevent="submit">
        <label class="grid gap-2 text-sm font-medium text-slate-700">
          真实姓名
          <input v-model="form.realName" class="input-field" placeholder="请输入真实姓名" />
        </label>
        <label class="grid gap-2 text-sm font-medium text-slate-700">
          证件号码
          <input v-model="form.idCardNo" class="input-field" placeholder="请输入证件号码" />
        </label>
        <label class="grid gap-2 text-sm font-medium text-slate-700">
          用途说明
          <textarea v-model="form.purpose" class="min-h-28 rounded-md border border-slate-200 p-3 text-sm outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100" placeholder="请说明业务用途"></textarea>
        </label>
        <p v-if="message" class="rounded-md bg-brand-50 px-3 py-2 text-sm text-brand-700">{{ message }}</p>
        <button class="btn-primary w-full" :disabled="submitting">{{ submitting ? "提交中..." : "提交认证" }}</button>
      </form>
    </section>

    <section class="panel p-5">
      <h3 class="text-lg font-bold text-slate-950">当前认证状态</h3>
      <div class="mt-5 rounded-lg bg-slate-50 p-4">
        <pre class="whitespace-pre-wrap break-words text-xs leading-6 text-slate-600">{{ currentText }}</pre>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { MemberAPI } from "@/api/member";

const current = ref<unknown>(null);
const message = ref("");
const submitting = ref(false);
const form = reactive({
  realName: "",
  idCardNo: "",
  purpose: "",
});

const currentText = computed(() => current.value ? JSON.stringify(current.value, null, 2) : "暂未提交认证资料");

onMounted(async () => {
  try {
    current.value = await MemberAPI.verifyCurrent();
  } catch {
    current.value = null;
  }
});

async function submit() {
  if (!form.realName || !form.idCardNo) {
    message.value = "请填写姓名和证件号码";
    return;
  }
  submitting.value = true;
  message.value = "";
  try {
    current.value = await MemberAPI.submitVerify({ ...form });
    message.value = "认证资料已提交，请等待审核";
  } catch (error) {
    message.value = error instanceof Error ? error.message : "提交失败";
  } finally {
    submitting.value = false;
  }
}
</script>

