<template>
  <div class="admin-info-page">
    <h1 class="page-title">超级管理员</h1>

    <section class="form-block">
      <h2 class="section-head">
        <span class="section-bar" aria-hidden="true" />
        超级管理员信息
      </h2>
      <p class="section-intro">
        超级管理员将接收开户信息及完成签约，并可进行商户号日常重要管理及资金操作。请确定超级管理员为商户法定代表人或经办人。
      </p>

      <el-form
        ref="formRef"
        class="admin-form"
        :model="form"
        :rules="rules"
        label-width="140px"
        require-asterisk-position="right"
        label-position="right"
      >
        <el-form-item label="超管身份" prop="managerIdentity">
          <el-radio-group v-model="form.managerIdentity" class="identity-radio">
            <el-radio value="LEGAL"> 法定代表人/经营者 </el-radio>
            <el-radio value="SUPER"> 经办人 </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="超管姓名" prop="managerName">
          <el-input v-model="form.managerName" placeholder="请输入超管姓名" clearable style="max-width: 420px" />
        </el-form-item>

        <el-form-item label="超管资料类型" prop="managerDocType">
          <el-select v-model="form.managerDocType" placeholder="请选择" clearable style="max-width: 420px">
            <el-option label="身份证" value="IDENTIFICATION_TYPE_IDCARD" />
            <el-option label="护照" value="IDENTIFICATION_TYPE_OVERSEA_PASSPORT" />
            <el-option label="香港居民来往内地通行证" value="IDENTIFICATION_TYPE_HONGKONG_PASSPORT" />
            <el-option label="台湾居民来往大陆通行证" value="IDENTIFICATION_TYPE_TAIWAN_PASSPORT" />
          </el-select>
        </el-form-item>

        <el-form-item label="证件号码" prop="managerDocNo">
          <el-input v-model="form.managerDocNo" placeholder="请输入证件号码" clearable style="max-width: 420px" />
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <div class="field-stack">
            <el-input v-model="form.mobile" placeholder="请输入手机号" clearable maxlength="11" style="max-width: 420px" />
            <p class="field-tip">用于接收微信支付的重要管理信息及日常操作验证码，超管签约时可自助修改手机号，并进行短信验证</p>
          </div>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <div class="field-stack">
            <el-input v-model="form.email" placeholder="请输入邮箱" clearable style="max-width: 420px" />
            <p class="field-tip">用于接收微信支付的开户邮件及日常业务通知</p>
          </div>
        </el-form-item>
      </el-form>
    </section>

    <div class="footer-actions">
      <el-button @click="onBack"> 返回 </el-button>
      <el-button type="danger" class="btn-next" :loading="submitLoading" @click="onSubmit"> 提交 </el-button>
    </div>

    <el-dialog
      v-model="signDialogVisible"
      title="签约链接"
      width="480px"
      align-center
      destroy-on-close
      @closed="onSignDialogClosed"
    >
      <div class="sign-dialog">
        <div v-if="signQrImageUrl && !signQrError" class="sign-dialog__qr-wrap">
          <img class="sign-dialog__qr" :src="signQrImageUrl" alt="签约二维码" @error="signQrError = true" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { localGet, localSet } from "@/utils/index";
import { applyment, getPaymentApplyment } from "@/api/modules/businessInfo";

const BUSINESS_DATA_CACHE_KEY = "businessData";
const GEEKER_USER_KEY = "geeker-user";

function resolveApplymentStoreId(): string | number | null {
  const geeker = localGet(GEEKER_USER_KEY) as { userInfo?: { storeId?: string | number | null } } | null | undefined;
  const sid = geeker?.userInfo?.storeId ?? localGet("createdId");
  if (sid === undefined || sid === null || sid === "") return null;
  return sid;
}

const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const signDialogVisible = ref(false);
const signUrlText = ref("");
const signQrError = ref(false);
const route = useRoute();
const router = useRouter();

const signQrImageUrl = computed(() => {
  const u = signUrlText.value.trim();
  if (!/^https?:\/\//i.test(u)) return "";
  return `https://api.qrserver.com/v1/create-qr-code/?size=280x280&data=${encodeURIComponent(u)}`;
});

function pickApplymentIdFromApplymentResponse(res: unknown): string {
  const r = res as Record<string, unknown> | null | undefined;
  const top = r?.data !== undefined ? r.data : r;
  if (!top || typeof top !== "object" || Array.isArray(top)) return "";
  const t = top as Record<string, unknown>;
  const inner =
    t.data !== undefined && t.data !== null && typeof t.data === "object" && !Array.isArray(t.data)
      ? (t.data as Record<string, unknown>)
      : t;
  const id = inner.applyment_id ?? inner.applymentId;
  return String(id ?? "").trim();
}

function pickSignUrlFromPaymentApplymentResponse(res: unknown): string {
  const r = res as Record<string, unknown> | null | undefined;
  const top = r?.data !== undefined ? r.data : r;
  if (!top || typeof top !== "object" || Array.isArray(top)) return "";
  const t = top as Record<string, unknown>;
  const inner =
    t.data !== undefined && t.data !== null && typeof t.data === "object" && !Array.isArray(t.data)
      ? (t.data as Record<string, unknown>)
      : t;
  const url = inner.sign_url ?? inner.signUrl;
  return String(url ?? "").trim();
}

function onSignDialogClosed() {
  signUrlText.value = "";
  signQrError.value = false;
}

async function copySignUrl() {
  const u = signUrlText.value.trim();
  if (!u) return;
  try {
    await navigator.clipboard.writeText(u);
    ElMessage.success("链接已复制");
  } catch {
    ElMessage.warning("复制失败，请手动选中复制");
  }
}

const form = reactive({
  managerIdentity: "LEGAL" as "SUPER" | "LEGAL",
  managerName: "",
  managerDocType: "",
  managerDocNo: "",
  mobile: "",
  email: ""
});

const rules: FormRules = {
  managerIdentity: [{ required: true, message: "请选择超管身份", trigger: "change" }],
  managerName: [{ required: true, message: "请输入超管姓名", trigger: "blur" }],
  managerDocType: [{ required: true, message: "请选择超管资料类型", trigger: "change" }],
  managerDocNo: [{ required: true, message: "请输入证件号码", trigger: "blur" }],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: ["blur", "change"] }
  ]
};

function openMobileGuide() {
  ElMessage.info("超管修改手机号指引（可对接文档）");
}

function onBack() {
  router.push({ path: "/businessInfo/accountInfo", query: { ...route.query } });
}

function onSaveDraft() {
  ElMessage.success("草稿已保存（可对接接口）");
}

/** 与 mergeContactInfoIntoBusinessDataCache 字段互逆；并从未填写的 subject_info 补全超管姓名/证件/类型 */
function hydrateAdminFormFromBusinessDataCache() {
  const raw = localGet(BUSINESS_DATA_CACHE_KEY) as Record<string, unknown> | null | undefined;
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;

  const ci = raw.contact_info as Record<string, unknown> | undefined;
  if (ci && typeof ci === "object" && !Array.isArray(ci)) {
    const ct = String(ci.contact_type ?? "").trim();
    if (ct === "LEGAL" || ct === "SUPER") {
      form.managerIdentity = ct;
    }
    form.managerName = String(ci.contact_name ?? "").trim();
    form.managerDocType = String(ci.contact_id_doc_type ?? "").trim();
    form.managerDocNo = String(ci.contact_id_number ?? "").trim();
    form.mobile = String(ci.mobile_phone ?? "").trim();
    form.email = String(ci.contact_email ?? "").trim();
  }

  const hadContactTypeFromCi = !!(
    ci &&
    typeof ci === "object" &&
    !Array.isArray(ci) &&
    ["LEGAL", "SUPER"].includes(String(ci.contact_type ?? "").trim())
  );

  const si = raw.subject_info as Record<string, unknown> | undefined;
  if (!si || typeof si !== "object" || Array.isArray(si)) {
    return;
  }

  if (!hadContactTypeFromCi) {
    const ctSi = String(si.contact_type ?? "").trim();
    if (ctSi === "LEGAL" || ctSi === "SUPER") {
      form.managerIdentity = ctSi;
    }
  }

  const ii = si.identity_info as Record<string, unknown> | undefined;
  const docType = ii && typeof ii === "object" && !Array.isArray(ii) ? String(ii.id_doc_type ?? "").trim() : "";
  const ici =
    ii && typeof ii === "object" && !Array.isArray(ii) ? (ii.id_card_info as Record<string, unknown> | undefined) : undefined;
  const idNum = ici && typeof ici === "object" && !Array.isArray(ici) ? String(ici.id_card_number ?? "").trim() : "";
  const idName = ici && typeof ici === "object" && !Array.isArray(ici) ? String(ici.id_card_name ?? "").trim() : "";

  const bli = si.business_license_info as Record<string, unknown> | undefined;
  const legalPerson = bli && typeof bli === "object" && !Array.isArray(bli) ? String(bli.legal_person ?? "").trim() : "";

  if (!String(form.managerName || "").trim()) {
    form.managerName = idName || legalPerson;
  }
  if (!String(form.managerDocNo || "").trim()) {
    form.managerDocNo = idNum;
  }
  if (!String(form.managerDocType || "").trim()) {
    form.managerDocType = docType || (idNum ? "IDENTIFICATION_TYPE_IDCARD" : "");
  }
}

onMounted(() => {
  hydrateAdminFormFromBusinessDataCache();
  nextTick(() => formRef.value?.clearValidate());
});

function mergeContactInfoIntoBusinessDataCache() {
  const prev = localGet(BUSINESS_DATA_CACHE_KEY);
  const base = prev && typeof prev === "object" && !Array.isArray(prev) ? { ...(prev as Record<string, unknown>) } : {};
  const prevCi =
    base.contact_info && typeof base.contact_info === "object" && !Array.isArray(base.contact_info)
      ? { ...(base.contact_info as Record<string, unknown>) }
      : {};

  base.contact_info = {
    ...prevCi,
    contact_type: form.managerIdentity,
    contact_name: String(form.managerName || "").trim(),
    contact_id_doc_type: String(form.managerDocType || "").trim(),
    contact_id_number: String(form.managerDocNo || "").trim(),
    mobile_phone: String(form.mobile || "").trim(),
    contact_email: String(form.email || "").trim()
  };
  localSet(BUSINESS_DATA_CACHE_KEY, base);
}

async function onSubmit() {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch {
    ElMessage.warning("请完善必填信息");
    return;
  }

  submitLoading.value = true;
  try {
    mergeContactInfoIntoBusinessDataCache();
    const businessData = localGet(BUSINESS_DATA_CACHE_KEY);
    if (!businessData || typeof businessData !== "object" || Array.isArray(businessData)) {
      ElMessage.warning("未找到进件数据，请重新填写");
      return;
    }
    const storeIdRaw = resolveApplymentStoreId();
    if (storeIdRaw === null) {
      ElMessage.warning("未获取到门店 storeId，请重新登录");
      return;
    }
    const n = Number(storeIdRaw);
    const storeId = Number.isNaN(n) ? storeIdRaw : n;
    const payload = { ...(businessData as Record<string, unknown>) };
    const res: unknown = await applyment(payload, storeId);
    const r = res as Record<string, unknown> | undefined;
    if (r?.code === 200 || r?.code === "200") {
      const applymentId = pickApplymentIdFromApplymentResponse(res);
      if (applymentId) {
        try {
          const detailRes: unknown = await getPaymentApplyment(applymentId);
          const dr = detailRes as Record<string, unknown> | undefined;
          const nested = dr?.data as Record<string, unknown> | undefined;
          const dCode = dr?.code ?? nested?.code;
          if (dCode === 200 || dCode === "200") {
            const signUrl = pickSignUrlFromPaymentApplymentResponse(detailRes);
            if (/^https?:\/\//i.test(signUrl)) {
              signUrlText.value = signUrl;
              signQrError.value = false;
              signDialogVisible.value = true;
            }
          }
        } catch (e) {
          console.warn("[adminInfo] getPaymentApplyment", e);
        }
      }
      ElMessage.success((r?.msg as string) || "提交成功");
    } else {
      ElMessage.warning((r?.msg as string) || "提交失败，请稍后重试");
    }
  } catch {
    ElMessage.error("提交失败，请稍后重试");
  } finally {
    submitLoading.value = false;
  }
}
</script>

<style scoped lang="scss">
$wechat-green: #07c160;
.admin-info-page {
  box-sizing: border-box;
  min-height: 100%;
  padding: 24px 32px 40px;
  margin: 0 auto;
  background: #ffffff;
}
.page-title {
  margin: 0 0 24px;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}
.form-block {
  margin-bottom: 24px;
}
.section-head {
  display: flex;
  align-items: center;
  margin: 0 0 12px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.section-bar {
  display: inline-block;
  flex-shrink: 0;
  width: 4px;
  height: 16px;
  margin-right: 8px;
  background: $wechat-green;
  border-radius: 2px;
}
.section-intro {
  margin: 0 0 20px;
  font-size: 12px;
  line-height: 1.65;
  color: #909399;
}
.admin-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
}
.identity-radio {
  :deep(.el-radio__input.is-checked .el-radio__inner) {
    background: $wechat-green;
    border-color: $wechat-green;
  }
  :deep(.el-radio__input.is-checked + .el-radio__label) {
    color: #303133;
  }
}
.tip-icon {
  margin-left: 4px;
  color: #c0c4cc;
}
.field-stack {
  width: 100%;
}
.field-tip {
  margin: 8px 0 0;
  font-size: 12px;
  line-height: 1.65;
  color: #909399;
}
.footer-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 24px;
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
}
.footer-center {
  display: flex;
  flex: 1;
  justify-content: center;
}
.btn-next {
  min-width: 100px;
  background: $wechat-green;
  border-color: $wechat-green;
  &:hover {
    background: #06ad56;
    border-color: #06ad56;
  }
}
.sign-dialog {
  padding: 0 4px 8px;
}
.sign-dialog__qr-wrap {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}
.sign-dialog__qr {
  width: 240px;
  height: 240px;
  object-fit: contain;
  background: #fafafa;
}
.sign-dialog__fail {
  margin: 0 0 12px;
  font-size: 13px;
  line-height: 1.6;
  color: #909399;
}
.sign-dialog__hint {
  margin: 0 0 12px;
  font-size: 14px;
  color: #606266;
  text-align: center;
}
.sign-dialog__url {
  margin-bottom: 16px;
}
.sign-dialog__actions {
  display: flex;
  justify-content: center;
}
</style>
