<template>
  <div class="invoice-page">
    <!-- 顶部导航 -->
    <van-nav-bar title="自然人开票" fixed placeholder />

    <div class="page-content">
      <!-- 骨架屏：加载中显示 -->
      <template v-if="loading">
        <div class="card" v-for="i in 4" :key="i">
          <div class="card-header">
            <div class="dot-skeleton"></div>
            <div class="title-skeleton"></div>
          </div>

          <div class="card-body">
            <div class="info-skeleton" v-for="j in 3" :key="j">
              <div class="label-skeleton"></div>
              <div class="value-skeleton"></div>
            </div>
          </div>
        </div>
      </template>

      <!-- 加载完成后显示真实内容 -->
      <template v-else>
        <div class="card">
          <StepProgress :activeStep="activeStep" />
        </div>

        <!-- 卡片：申请人信息 -->
        <div class="card">
          <div class="card-header">
            <span class="dot"></span>
            <span class="title">申请人信息</span>
          </div>
          <div class="card-body">
            <div class="info-item">
              <span class="label">姓名</span>
              <span class="value">{{ invoiceInfo?.sellerName }}</span>
            </div>
            <div class="info-item">
              <span class="label">身份证号</span>
              <span class="value">{{ invoiceInfo?.sellerId }}</span>
            </div>
          </div>
        </div>

        <!-- 发票抬头 -->
        <div class="card">
          <div class="card-header">
            <span class="dot"></span>
            <span class="title">发票抬头</span>
          </div>
          <div class="card-body">
            <div class="info-item">
              <span class="label">公司名称</span>
              <span class="value">{{ invoiceInfo?.buyerName }}</span>
            </div>
            <div class="info-item">
              <span class="label">统一信用代码</span>
              <span class="value">{{ invoiceInfo?.buyerId }}</span>
            </div>
          </div>
        </div>

        <!-- 发票信息 -->
        <div class="card">
          <div class="card-header">
            <span class="dot"></span>
            <span class="title">发票信息</span>
          </div>
          <div class="card-body">
            <div class="info-item">
              <span class="label">应税发生地</span>
              <span class="value">{{
                [invoiceInfo?.province, invoiceInfo?.city, invoiceInfo?.district]
                  .filter(Boolean)
                  .join(' ')
              }}</span>
            </div>
            <div class="info-item">
              <span class="label">发票类别</span>
              <span class="value">{{ invoiceInfo?.category }}</span>
            </div>
            <div class="info-item">
              <span class="label">税前金额</span>
              <span class="value highlight">{{ invoiceInfo?.amount }}</span>
            </div>
          </div>
        </div>

        <!-- 缴税信息 -->
        <div class="card">
          <div class="card-header">
            <span class="dot"></span>
            <span class="title">缴税信息</span>
          </div>
          <div class="card-body">
            <div class="info-item">
              <span class="label">应缴税信息</span>
              <span class="value link" @click="toDetail">查看详情 ></span>
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-bar">
      <van-button
        type="primary"
        block
        round
        color="linear-gradient(90deg, #ff7a00, #ffa94d)"
        class="next-btn"
        @click="handleNext"
      >
        下一步
      </van-button>
    </div>

    <!-- ✅ 弹窗（放在最外层，不要嵌套第二个 template） -->
    <van-dialog
      v-model:show="showDialog"
      :show-cancel-button="false"
      :show-confirm-button="false"
      class="modern-dialog"
      close-on-click-overlay
    >
      <div class="dialog-content">
        <div class="dialog-title">申请成功</div>
        <div class="dialog-message">
          您的开票信息已提交至税务部门审核，审核通过后通知您缴纳税款，请关注缴税信息。
        </div>
        <van-button
          type="primary"
          block
          round
          class="dialog-btn"
          color="linear-gradient(90deg, #ff7a00, #ffa94d)"
          @click="onConfirm"
        >
          我知道了
        </van-button>
      </div>
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useDebounceFn } from '@/utils/util'
import {
  getConfirmInvoiceInfoApi,
  getStatusApi,
  submitInvoiceApplyApi,
} from '@/services/modules/invoiceInformation'
import type { PushRecordIdRequest } from '@/services/modules/invoiceInformation/type.d.ts'
import { reactive, onMounted, ref } from 'vue'
import StepProgress from '@/components/StepProgress.vue'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/modules/user'

const userStore = useUserStore()

const router = useRouter()
const loading = ref(true)
const invoiceInfo = ref<any>({})

const params = reactive<PushRecordIdRequest>({
  pushRecordId: userStore.pushRecordId,
})

const getConfirmInvoiceInfo = async () => {
  try {
    loading.value = true
    const res = await getConfirmInvoiceInfoApi(params)
    if (res.code === 0) {
      invoiceInfo.value = res.data
    }
  } catch (err) {
    console.error('获取发票信息失败', err)
  } finally {
    loading.value = false
  }
}

const handleNext = useDebounceFn(async () => {
  const res = await getStatusApi(params)
  if (res.code === 0) {
    if (!res.data.eventStatus) {
      return router.push({
        path: '/face-recognition',
      })
    }
    // 当前账户没有身份照片，跳转上传证件页面
    if (!res.data.isIdImgReady) {
      router.push({
        path: '/identity-upload',
      })
    }
  }
}, 1000)

const showDialog = ref(false)
const submitInvoiceApply = async () => {
  try {
    const res = await submitInvoiceApplyApi(params)
    if (res.code === 0 && res.data) {
      showDialog.value = true
    }
  } catch (err) {
    console.error('提交失败', err)
    showToast('提交失败，请稍后重试')
  }
}

const activeStep = ref(1)
const onConfirm = () => {
  showDialog.value = false
}

const toDetail = () => {
  router.push({
    path: '/invoice-information/detail',
  })
}
onMounted(() => {
  getConfirmInvoiceInfo()
  const authFlag = sessionStorage.getItem('FACE_AUTH_DONE')
  if (authFlag === '1') {
    activeStep.value = 3
    sessionStorage.removeItem('FACE_AUTH_DONE') // 清除标记
    submitInvoiceApply()
  } else {
    activeStep.value = 1
  }
})
</script>

<style scoped lang="scss">
.invoice-page {
  background: #f5f6f8;
  min-height: 100vh;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Helvetica Neue', 'PingFang SC', 'Microsoft YaHei',
    sans-serif;
  font-size: 3.8vw;

  .page-content {
    padding: 4vw 3.5vw;
    padding-bottom: 15vw;

    /* ---------- 卡片通用样式 ---------- */
    .card {
      background: #fff;
      border-radius: 14px;
      margin-bottom: 5vw;
      padding: 4vw 3.5vw;
      box-shadow:
        0 4px 12px rgba(0, 0, 0, 0.06),
        0 1px 3px rgba(0, 0, 0, 0.04);
      transition: all 0.3s ease;

      /* ---------- 骨架屏 Header ---------- */
      .card-header {
        display: flex;
        align-items: center;
        margin-bottom: 3vw;

        .dot {
          width: 6px;
          height: 28px;
          background: #ff7a00;
          border-radius: 4px;
          margin-right: 2vw;
        }

        .dot-skeleton {
          width: 6px;
          height: 28px;
          border-radius: 4px;
          margin-right: 2vw;
          background: linear-gradient(90deg, #f2f2f2 25%, #e4e4e4 50%, #f2f2f2 75%);
          background-size: 200% 100%;
          animation: skeleton-loading 1.2s ease-in-out infinite;
        }

        .title {
          font-size: 4vw;
          font-weight: 600;
          color: #333;
        }

        .title-skeleton {
          flex: 1;
          height: 22px;
          border-radius: 6px;
          background: linear-gradient(90deg, #f2f2f2 25%, #e4e4e4 50%, #f2f2f2 75%);
          background-size: 200% 100%;
          animation: skeleton-loading 1.2s ease-in-out infinite;
        }
      }

      /* ---------- 骨架屏 Body ---------- */
      .card-body {
        display: flex;
        flex-direction: column;
        gap: 3vw; // 🟢 关键间距：解决挤在一起的问题

        .info-skeleton {
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 4vw;

          .label-skeleton {
            flex: 0 0 30%;
            height: 18px;
            border-radius: 6px;
            background: linear-gradient(90deg, #f2f2f2 25%, #e4e4e4 50%, #f2f2f2 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.2s ease-in-out infinite;
          }

          .value-skeleton {
            flex: 1;
            height: 18px;
            border-radius: 6px;
            background: linear-gradient(90deg, #f2f2f2 25%, #e4e4e4 50%, #f2f2f2 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.2s ease-in-out infinite;
          }
        }

        /* 真实内容样式 */
        .info-item {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          font-size: 3.8vw;
          color: #555;
          line-height: 1.6;

          .label {
            flex: 0 0 28vw;
            color: #888;
          }

          .value {
            flex: 1;
            text-align: right;
            color: #222;
            word-break: break-all;
          }

          .highlight {
            color: #ff7a00;
            font-weight: 600;
          }

          .link {
            color: #ff7a00;
            cursor: pointer;
            font-weight: 500;
          }
        }
      }
    }
  }

  /* ---------- 底部按钮 ---------- */
  .bottom-bar {
    position: fixed;
    bottom: 4vw;
    left: 0;
    right: 0;
    width: 100%;

    .next-btn {
      font-size: 4.2vw;
      width: 90%;
      margin: 0 auto;
      height: 12vw;
      box-shadow: 0 4px 10px rgba(255, 128, 54, 0.25);
    }
  }

  /* ---------- 骨架屏动画 ---------- */
  @keyframes skeleton-loading {
    0% {
      background-position: 200% 0;
    }
    100% {
      background-position: -200% 0;
    }
  }
}

/* 修正版：留白 + 按钮不被挤压 */
.modern-dialog {
  width: 80vw;
  border-radius: 5vw !important;
  background: #fff;
  box-shadow: 0 8px 28px rgba(0, 0, 0, 0.15);
  padding: 0; /* 外层不再加内边距，改到内容区 */
  overflow: visible; /* 允许按钮投影外扩 */
  text-align: center;
  animation: dialogPop 0.28s ease-out;
  box-sizing: border-box;

  .dialog-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 6vw 5vw 5vw; /* ✅ 内容留白在这里 */
    gap: 5vw; /* 内容与按钮的竖向间距 */
  }

  .dialog-title {
    font-size: 4.4vw;
    font-weight: 700;
    color: #222;
  }

  .dialog-message {
    font-size: 3.6vw;
    line-height: 1.7;
    color: #555;
    word-break: break-word;
  }

  /* ✅ 独立按钮：有左右边距与圆角，不会被挤压 */
  .dialog-btn {
    width: calc(100% - 10vw); /* 等同左右各 5vw 的边距 */
    margin: 0 auto 2.5vw; /* 底部也留点气口 */
    height: 12vw;
    border-radius: 3vw;
    font-size: 4vw;
    font-weight: 600;
    display: inline-flex; /* 避免被拉伸成整块底边 */
    align-items: center;
    justify-content: center;
    border: none;
    box-shadow: 0 4px 12px rgba(255, 128, 54, 0.25);
    letter-spacing: 0.2vw;
  }
}

/* 蒙层与动画（可保留） */
:deep(.van-overlay) {
  backdrop-filter: blur(8px);
  background: rgba(0, 0, 0, 0.25);
  animation: fadeIn 0.3s ease;
}
@keyframes dialogPop {
  from {
    transform: translateY(4vw) scale(0.9);
    opacity: 0;
  }
  to {
    transform: translateY(0) scale(1);
    opacity: 1;
  }
}
</style>
