<script lang="ts" setup>
import type { PersonnelQualificationModel } from '#/api';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { ChevronLeft, ChevronRight } from '@vben/icons';

import { Spin, Tabs } from 'ant-design-vue';

import { getPersonnelQualificationMethod } from '#/api';
import { QUALIFICATION_STATUS_LABELS } from '#/api/method/personnel-qualification';

const loading = ref(false);
const detail = ref<PersonnelQualificationModel.Personnel>(
  {} as PersonnelQualificationModel.Personnel,
);
const activeCertId = ref('');
const activeAttachmentIndex = ref(0);

const activeCertificate = computed(() =>
  detail.value.certificates?.find((item) => item.id === activeCertId.value),
);

const activeAttachments = computed(
  () => activeCertificate.value?.attachments ?? [],
);

const currentAttachment = computed(
  () => activeAttachments.value[activeAttachmentIndex.value],
);

function getTabLabel(cert: PersonnelQualificationModel.Certificate) {
  const label = cert.name;
  if (cert.status === 'expiring') {
    return `${label}（即将过期）`;
  }
  if (cert.status === 'expired') {
    return `${label}（过期）`;
  }
  return label;
}

function isTabWarning(cert: PersonnelQualificationModel.Certificate) {
  return cert.status === 'expiring' || cert.status === 'expired';
}

function onTabChange(key: string | number) {
  activeCertId.value = String(key);
  activeAttachmentIndex.value = 0;
}

function showPrevAttachment() {
  if (!activeAttachments.value.length) return;
  activeAttachmentIndex.value =
    (activeAttachmentIndex.value - 1 + activeAttachments.value.length) %
    activeAttachments.value.length;
}

function showNextAttachment() {
  if (!activeAttachments.value.length) return;
  activeAttachmentIndex.value =
    (activeAttachmentIndex.value + 1) % activeAttachments.value.length;
}

const [Modal, modalApi] = useVbenModal({
  class: 'certificate-view-modal !w-[calc(100%-120px)] !max-w-[960px]',
  showConfirmButton: false,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      detail.value = {} as PersonnelQualificationModel.Personnel;
      activeCertId.value = '';
      activeAttachmentIndex.value = 0;
      return;
    }

    const data = modalApi.getData<PersonnelQualificationModel.Personnel>();
    if (!data?.id) return;

    loading.value = true;
    try {
      detail.value = await getPersonnelQualificationMethod(data.id);
      activeCertId.value = detail.value.certificates?.[0]?.id ?? '';
      activeAttachmentIndex.value = 0;
    } finally {
      loading.value = false;
    }
  },
});
</script>
<template>
  <Modal :title="`${detail.name || ''} - 资质证书`">
    <Spin :spinning="loading">
      <div v-if="detail.certificates?.length" class="certificate-view">
        <Tabs
          :active-key="activeCertId"
          class="certificate-tabs"
          @change="onTabChange"
        >
          <Tabs.TabPane v-for="cert in detail.certificates" :key="cert.id">
            <template #tab>
              <span :class="{ 'tab-warning': isTabWarning(cert) }">
                {{ getTabLabel(cert) }}
              </span>
            </template>
          </Tabs.TabPane>
        </Tabs>

        <div v-if="activeCertificate" class="certificate-meta">
          <div class="meta-item">
            <span class="meta-label">资质编号：</span>
            <span>{{ activeCertificate.number || '-' }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">资质到期日期：</span>
            <span>{{
              activeCertificate.longTerm
                ? '长期'
                : activeCertificate.expiryDate || '-'
            }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">证书类型：</span>
            <span>{{ activeCertificate.type || '-' }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">资质附件：</span>
            <span>共{{ activeAttachments.length }}份</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">资质状态：</span>
            <span
              :class="{
                'status-warning':
                  activeCertificate.status === 'expiring' ||
                  activeCertificate.status === 'expired',
              }"
            >
              {{ QUALIFICATION_STATUS_LABELS[activeCertificate.status] || '-' }}
            </span>
          </div>
        </div>

        <div class="attachment-viewer">
          <button
            class="nav-btn"
            type="button"
            @click="showPrevAttachment"
          >
            <ChevronLeft class="size-5" />
          </button>
          <div class="attachment-content">
            <template v-if="currentAttachment">
              <iframe
                v-if="currentAttachment.type === 'pdf' && currentAttachment.url"
                referrerpolicy="no-referrer"
                :src="currentAttachment.url"
                class="attachment-pdf"
                title="PDF预览"
              />
              <div
                v-else-if="currentAttachment.type === 'pdf'"
                class="attachment-placeholder"
              >
                <span class="placeholder-icon">PDF</span>
                <span>{{ currentAttachment.name }}</span>
              </div>
              <img
                v-else-if="currentAttachment.url"
                :alt="currentAttachment.name"
                :src="currentAttachment.url"
                class="attachment-image"
              />
              <div v-else class="attachment-placeholder">
                <span class="placeholder-icon">X</span>
                <span>{{ currentAttachment.name }}</span>
              </div>
            </template>
            <div v-else class="attachment-placeholder">
              <span>暂无附件</span>
            </div>
          </div>
          <button
            class="nav-btn"
            type="button"
            @click="showNextAttachment"
          >
            <ChevronRight class="size-5" />
          </button>
        </div>
      </div>
      <div v-else class="empty-text">暂无证书信息</div>
    </Spin>
  </Modal>
</template>
<style scoped>
.certificate-view {
  padding: 8px 16px 16px;
}

.certificate-tabs :deep(.tab-warning) {
  color: #ff4d4f;
}

.certificate-meta {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px 24px;
  margin: 16px 0 24px;
}

.meta-item {
  line-height: 1.6;
  word-break: break-all;
}

.meta-label {
  color: rgb(0 0 0 / 65%);
}

.status-warning {
  color: #ff4d4f;
}

.attachment-viewer {
  display: flex;
  gap: 16px;
  align-items: center;
  min-height: 360px;
}

.nav-btn {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  color: rgb(0 0 0 / 45%);
  font-size: 18px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
}

.nav-btn:hover {
  color: #1677ff;
  border-color: #1677ff;
}

.attachment-content {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  min-height: 360px;
  background: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
}

.attachment-image {
  max-width: 100%;
  max-height: 340px;
  object-fit: contain;
}

.attachment-pdf {
  width: 100%;
  height: 390px;
  border: 0;
}

.attachment-placeholder {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
  justify-content: center;
  color: rgb(0 0 0 / 45%);
}

.placeholder-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
  font-size: 48px;
  background: #fff;
  border: 1px solid #d9d9d9;
}

.empty-text {
  padding: 48px 0;
  color: rgb(0 0 0 / 45%);
  text-align: center;
}
</style>
