<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>制单授权（批量付款到户有密）</span>
      </div>
    </template>
    <el-form label-width="160px">
      <el-form-item>
        <el-button
          v-if="!isAuthed"
          v-hasPerm="['module_payment:account:authorize']"
          type="primary"
          :loading="applying"
          @click="handleApply"
        >
          {{ existingAuthing ? "重新生成授权链接" : "生成授权链接" }}
        </el-button>
        <el-button
          v-if="outBizNo"
          v-hasPerm="['module_payment:account:authorize']"
          size="small"
          style="margin-left: 12px"
          :loading="querying"
          @click="handleQuery"
        >
          刷新状态
        </el-button>
      </el-form-item>
      <el-form-item v-if="link" label="授权链接（PC 浏览器打开）">
        <div style="display: flex; align-items: flex-start; gap: 12px">
          <el-input :model-value="link" readonly style="width: 560px">
            <template #append>
              <el-button @click="handleCopyLink">复制</el-button>
            </template>
          </el-input>
          <div class="qrcode-wrapper">
            <canvas ref="qrcodeCanvas" class="qrcode-canvas"></canvas>
            <div class="form-item-tip">手机支付宝扫码打开</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="outBizNo" label="授权单号 / 状态">
        <span>{{ outBizNo }} / {{ statusText }}</span>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from "vue";
import BatchPayAPI from "@/api/module_payment/batch";
import { useEnterpriseStore } from "@/store";
import { ElMessage, ElMessageBox } from "element-plus";
import QRCode from "qrcode";

const enterpriseStore = useEnterpriseStore();
const enterpriseId = computed(() => enterpriseStore.getCurrentEnterprise?.enterprise_id);

const link = ref("");
const outBizNo = ref("");
const agreementNo = ref("");
const status = ref("");
/** 最新记录已 AUTHED（永久生效授权）→ 不再提供生成入口，仅展示状态 */
const isAuthed = ref(false);
const applying = ref(false);
const querying = ref(false);
const qrcodeCanvas = ref<HTMLCanvasElement>();

const AUTH_STATUS_TEXT: Record<string, string> = {
  AUTHING: "授权中",
  AUTHED: "已授权",
  // 存量兼容: 通知归一前落库的 NORMAL（支付宝生效状态）视同已授权
  NORMAL: "已授权",
  UNBIND: "已解绑",
};

const statusText = computed(() => {
  const s = AUTH_STATUS_TEXT[status.value] || status.value || "-";
  return agreementNo.value ? `${s}（协议号 ${agreementNo.value}）` : s;
});

const existingAuthing = computed(() => status.value === "AUTHING");

/** 进入页面时拉取该企业最新授权记录：AUTHING → 回溯展示链接，AUTHED → 展示已授权，UNBIND/无记录 → 初始空态 */
async function loadLatest() {
  if (!enterpriseId.value) return;
  try {
    const res = await BatchPayAPI.authorizeList({
      enterprise_id: enterpriseId.value,
      page_no: 1,
      page_size: 1,
    });
    const rows = (res.data.data?.items ?? res.data.data?.list) || [];
    const latest = rows[0];
    if (!latest) return;
    if (latest.status === "AUTHING") {
      link.value = latest.authorize_link || "";
      outBizNo.value = latest.out_biz_no;
      status.value = "AUTHING";
      agreementNo.value = "";
      if (link.value) nextTick(() => drawQRCode());
    } else if (latest.status === "AUTHED" || latest.status === "NORMAL") {
      // NORMAL 为通知归一前落库的支付宝生效状态，视同已授权
      outBizNo.value = latest.out_biz_no;
      status.value = latest.status;
      agreementNo.value = latest.agreement_no || "";
      isAuthed.value = true;
    }
    // UNBIND → 保持初始空态（可正常生成新链接）
  } catch (err) {
    console.error("加载授权记录失败:", err);
  }
}

onMounted(loadLatest);

async function handleApply() {
  if (!enterpriseId.value) {
    ElMessage.warning("请选择企业");
    return;
  }
  // 已有未完成授权申请：确认后作废旧链接重新生成（后端 /authorize/rebind）
  if (existingAuthing.value) {
    try {
      await ElMessageBox.confirm(
        "当前存在未完成的授权申请，重新生成将作废旧授权链接。是否继续？",
        "重新生成授权链接",
        { type: "warning", confirmButtonText: "重新生成", cancelButtonText: "取消" }
      );
    } catch {
      return;
    }
  }
  applying.value = true;
  try {
    const res = existingAuthing.value
      ? await BatchPayAPI.authorizeRebind(enterpriseId.value)
      : await BatchPayAPI.authorizeApply(enterpriseId.value);
    link.value = res.data.data.authorize_link;
    outBizNo.value = res.data.data.out_biz_no;
    status.value = res.data.data.status;
    agreementNo.value = "";
    isAuthed.value = false;
    nextTick(() => drawQRCode());
    ElMessage.success("授权链接已生成，请尽快完成授权");
  } finally {
    applying.value = false;
  }
}

/** 授权链接二维码（复用 InviteDialog 的 qrcode 库用法） */
async function drawQRCode() {
  if (!qrcodeCanvas.value || !link.value) return;
  try {
    await QRCode.toCanvas(qrcodeCanvas.value, link.value, { width: 160, margin: 1 });
  } catch (err) {
    console.error("授权链接二维码生成失败:", err);
  }
}

async function handleQuery() {
  if (!enterpriseId.value || !outBizNo.value) return;
  querying.value = true;
  try {
    const res = await BatchPayAPI.queryAuthorize(enterpriseId.value, outBizNo.value);
    status.value = res.data.data.status;
    agreementNo.value = res.data.data.agreement_no || "";
    if (status.value === "AUTHED" || status.value === "NORMAL") isAuthed.value = true;
  } finally {
    querying.value = false;
  }
}

async function handleCopyLink() {
  try {
    await navigator.clipboard.writeText(link.value);
    ElMessage.success("授权链接已复制");
  } catch {
    ElMessage.warning("复制失败，请手动复制");
  }
}
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.qrcode-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.qrcode-canvas {
  width: 160px;
  height: 160px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.form-item-tip {
  font-size: 12px;
  color: #909399;
}
</style>
