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

    <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" plain round class="reject-btn btn" @click="rejectAndReturn">
        拒绝并退回
      </van-button>

      <van-button
        type="primary"
        :disabled="btnDisabled"
        round
        class="next-btn btn"
        @click="handleNextDebounced"
      >
        下一步
      </van-button>
    </div>

    <!-- 拒绝并退回 -->
    <ModernDialog
      v-model:show="rejectAndReturnDialog"
      title="提示"
      message="确认拒绝后，信息会同步给项目执行人员"
      cancelText="返回开票页"
      @cancel="rejectAndReturnDialog = false"
      confirmText="确认拒绝"
      @confirm="rejectAndReturnDialogConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'

import { showToast, showSuccessToast } from 'vant'
import { useRouter } from 'vue-router'
import { useDebounceFn } from '@/utils/util'
import StepProgress from '@/components/StepProgress.vue'
import {
  getConfirmInvoiceInfoApi,
  invoiceRecordInvalidateApi,
} from '@/services/modules/invoiceInformation'
import type { PushRecordIdRequest } from '@/services/modules/invoiceInformation/type.d.ts'
import { useUserStore } from '@/stores/modules/user'
import ModernDialog from '@/components/ModernDialog.vue'

// ✅ 使用封装好的 Hook
import { useInvoice } from '@/hooks/useInvoice'
// --- 初始化 Hooks ---
const { getStatus, submitInvoiceApply, getFaceAuthResult, btnDisabled, statusMap, faceAuthResult } =
  useInvoice()

// --- 其余本页面独有逻辑 ---
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const invoiceInfo = ref<any>({})
const activeStep = ref(1)

// 请求参数
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: any) {
    const { message } = err
    showToast(message)
  } finally {
    loading.value = false
  }
}

/**
 * 下一步逻辑
 * 使用 hooks 提供的状态进行判断
 */
const handleNext = async () => {
  // 未上传身份证，跳转上传页
  if (!statusMap.value.isIdImgReady) {
    return router.push({ path: '/identity-upload' })
  }

  // 已处理状态，跳转人脸识别
  if (userStore.needFaceId && !faceAuthResult.value) {
    return router.push({ path: '/face-recognition' })
  }

  // 其他情况，直接提交
  await submitInvoiceApply()
}

const rejectAndReturnDialog = ref(false)
// 拒绝并退回
const rejectAndReturn = () => {
  rejectAndReturnDialog.value = true
}

const rejectAndReturnDialogConfirm = async () => {
  const res = await invoiceRecordInvalidateApi(params)
  if (res.code === 0 && res.data) {
    showSuccessToast('提交成功')
    setTimeout(() => {
      router.replace({
        path: '/login',
        query: {
          pushRecordId: userStore.pushRecordId,
        },
      })
      userStore.LogOut()
    }, 1500)
  }
}
/** 防抖包装 */
const handleNextDebounced = useDebounceFn(handleNext, 1000)

/** 跳转缴税详情页 */
const toDetail = () => {
  router.push({ path: '/invoice-information/detail' })
}

/** 生命周期 */
onMounted(async () => {
  await Promise.all([getStatus(), getConfirmInvoiceInfo(), getFaceAuthResult()])
})
</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: #0072f8;
          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: #0072f8;
            font-weight: 600;
          }

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

  /* ---------- 底部按钮 ---------- */

  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1000;

    padding: 3vw 4vw 4vw;
    background: #f7f9fc;
    box-shadow: 0 -2vw 6vw rgba(0, 0, 0, 0.08);

    display: flex;
    gap: 3vw;

    /* ---------- 通用按钮 ---------- */
    .btn {
      flex: 1;
      min-width: 0; // ⭐ 关键：防止被挤出
      height: 12vw;
      font-size: 4.2vw;
      border-radius: 6vw;

      white-space: normal; // 覆盖 van-button 默认 nowrap
    }

    /* ---------- 左侧按钮（次操作） ---------- */
    .reject-btn {
      background: #ffffff;
      color: #3a7afe;
      border: 1px solid #3a7afe;
    }

    /* ---------- 右侧按钮（主操作） ---------- */
    .next-btn {
      color: #fff;
      background: linear-gradient(90deg, #0072f8 0%, #3a9fff 100%);
      border: none;
    }

    /* ---------- 禁用态兜底（Vant） ---------- */
    :deep(.van-button--disabled) {
      opacity: 0.6;
    }
  }

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