<template>
  <div class="identity-page">
    <van-nav-bar
      title="自然人开票"
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
      safe-area-inset-top
    />

    <!-- 上传区域 -->
    <div class="upload-section">
      <div class="upload-item" v-for="(item, index) in uploadList" :key="item.field">
        <van-uploader
          v-model="item.fileList"
          :max-count="1"
          :after-read="(file) => handleAfterRead(file, item, index)"
          :deletable="true"
          accept="image/*"
          :multiple="false"
          preview-size="auto"
          class="custom-uploader"
        >
          <template #default>
            <div
              class="upload-box"
              v-if="!item.fileList.length"
              :style="{ backgroundImage: `url(${item.bg})` }"
            >
              <div class="overlay">
                <van-icon name="photograph" class="camera-icon" />
              </div>
            </div>
          </template>
        </van-uploader>
        <p class="upload-text">{{ item.label }}</p>
      </div>
    </div>

    <!-- 说明文字 -->
    <div class="info-section">
      <p class="info-title">当前操作可能用于：</p>
      <ol class="info-list">
        <li>开具数电发票</li>
        <li>上传身份证信息登录电子税务局完成实名认证</li>
        <li>办理其他涉税、高风险业务</li>
      </ol>
      <p class="info-tip">请您在如未认证用途中完成认证操作。</p>
    </div>

    <!-- 下一步按钮 -->
    <div class="btn-section">
      <van-button
        block
        type="primary"
        round
        class="next-btn"
        :disabled="!isReady"
        @click="handleNextDebounced"
      >
        下一步
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { showToast, showFailToast } from 'vant'
import { sysFileUploadApi } from '@/services/modules/common'
import { ocrApi, updateH5IdcardInfo } from '@/services/modules/identityUpload/index'
import { useDebounceFn } from '@/utils/util'
import { useRouter } from 'vue-router'
/** 背景图 */
import frontBg from '@/assets/images/id-front-bg.png'
import backBg from '@/assets/images/id-back-bg.png'
import { useUserStore } from '@/stores/modules/user'
// ✅ 使用封装好的 Hook
import { useInvoice } from '@/hooks/useInvoice'
import type { UpdateH5IdcardInfoRequest } from '@/services/modules/identityUpload/type.d'

// --- 初始化 Hooks ---
const { getStatus, submitInvoiceApply, getFaceAuthResult, faceAuthResult } = useInvoice()
const userStore = useUserStore()
/** 上传项类型 */
interface UploadFileItem {
  url?: string
  file?: File
  fileId?: string
  status?: 'uploading' | 'done' | 'failed'
  message?: string
}

interface UploadItem {
  label: string
  field: 'front' | 'back'
  fileList: UploadFileItem[]
  bg: string
}

const router = useRouter()

/** 上传列表 */
const uploadList = ref<UploadItem[]>([
  { label: '请上传身份证人像面', field: 'front', fileList: [], bg: frontBg },
  { label: '请上传身份证国徽面', field: 'back', fileList: [], bg: backBg },
])

/** 上传 + OCR识别逻辑 */
const handleAfterRead = async (file: any, item: UploadItem, index: number) => {
  const target = uploadList.value[index]
  if (!target) return

  try {
    target.fileList = [{ status: 'uploading', message: '上传中...' }]
    const formData = new FormData()
    formData.append('file', file.file)

    // 调用上传接口
    const res = await sysFileUploadApi(formData)

    if (res.code === 0 && res.data?.url) {
      const baseUrl = import.meta.env.VITE_APP_URL
      const fullUrl = res.data.url.startsWith('http') ? res.data.url : `${baseUrl}${res.data.url}`
      console.log('fullUrl', fullUrl)

      target.fileList = [{ url: fullUrl, status: 'done', fileId: res.data.fileId }]
      showToast(`${item.label} 上传成功`)
      // 调用 OCR 接口（传原始文件 + side）
      const ocrRes = await handleOcrCheck(item.field, file.file)
      if (!ocrRes.success) {
        target.fileList = []
        showFailToast(`识别${item.label}失败，请重新上传`)
      }
    } else {
      target.fileList = [{ status: 'failed', message: '上传失败' }]
      showFailToast(res.msg || '上传失败')
    }
  } catch (error) {
    console.error('upload error:', error)
    target.fileList = [{ status: 'failed', message: '上传异常' }]
    showFailToast('上传异常，请重试')
  }
}

/** 模拟OCR识别接口逻辑（你可以替换成实际API） */
/** OCR识别逻辑 */
const handleOcrCheck = async (side: 'front' | 'back', file: File) => {
  try {
    // 真实调用
    const res = await ocrApi({ file, side })
    if (res.code === 0) {
      // 当是人面向
      if (side === 'front') {
        submitInfo.idCard = res.data.idcard
        submitInfo.idCardFrontImg = res.data.imgUrl
        submitInfo.name = res.data.realname
      } else {
        submitInfo.idcardPeriodStart = res.data.begin
        submitInfo.idcardPeriodEnd = res.data.end
        submitInfo.idCardBackImg = res.data.imgUrl
      }

      return { success: true }
    }
    return { success: false }
  } catch (err) {
    console.error('OCR error', err)
    return { success: false }
  }
}
const submitInfo = reactive<UpdateH5IdcardInfoRequest>({
  pushRecordId: userStore.pushRecordId,
  idCard: '',
  name: '',
  idcardPeriodStart: '',
  idcardPeriodEnd: '',
  idCardFrontImg: '',
  idCardBackImg: '',
})

/** 是否完成上传 */
// ✅ 校验：每个字段必须有值（非空字符串）
const isReady = computed(() => {
  return Object.values(submitInfo).every(
    (value) => value !== '' && value !== null && value !== undefined,
  )
})

const handleNext = async () => {
  if (!isReady.value) return showToast('请先上传身份证正反面')

  try {
    const res = await updateH5IdcardInfo(submitInfo)
    if (res.code === 0) {
      // 需要人脸识别->跳转人脸识别
      // 已处理状态，跳转人脸识别
      if (userStore.needFaceId && !faceAuthResult.value) {
        return router.push({ path: '/face-recognition' })
      }
      // 其他情况，直接提交
      await submitInvoiceApply()
    }
  } catch (err: any) {
    const { message } = err
    showToast(message)
  }
}
/** 防抖包装 */
const handleNextDebounced = useDebounceFn(handleNext, 1000)

const onClickLeft = () => history.back()
/** 下一步按钮点击 */

onMounted(async () => {
  await Promise.all([getStatus(), getFaceAuthResult()])
})
</script>

<style scoped>
.identity-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding: 4vw;
  box-sizing: border-box;
  font-size: 3.6vw;
  color: #333;
}

.van-nav-bar {
  background-color: #fff;
  border-bottom: 1px solid #f2f2f2;
  font-weight: 600;
}

/* 修改左侧返回图标颜色与大小 */
:deep(.van-icon-arrow-left) {
  color: #0072f8;
  font-size: 28px;
}
/* 上传区域 */
.upload-section {
  display: flex;
  justify-content: space-between;
  margin: 10vw 0;
}
.upload-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}
.upload-box {
  width: 35vw;
  height: 22vw;
  border-radius: 2vw;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  overflow: hidden;
  box-shadow: inset 0 0 2vw rgba(0, 0, 0, 0.05);
  margin-bottom: 3vw;
}
.overlay {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.25);
  display: flex;
  align-items: center;
  justify-content: center;
}
.camera-icon {
  font-size: 8vw;
  color: #fff;
  opacity: 0.9;
}
.upload-text {
  font-size: 3.4vw;
  color: #666;
}

/* 预览图尺寸与上传框保持一致 */

:deep(.van-uploader__preview),
:deep(.van-uploader__preview-image) {
  width: 35vw !important;
  height: 22vw !important;
  border-radius: 2vw;
  object-fit: cover;
}

/* 说明文字 */
.info-section {
  margin: 8vw 0 12vw;
  line-height: 1.8;
}
.info-title {
  font-weight: 600;
  margin-bottom: 2vw;
}
.info-list {
  padding-left: 5vw;
  color: #444;
}
.info-list li {
  margin-bottom: 1.5vw;
}
.info-tip {
  color: #999;
  font-size: 3.2vw;
  margin-top: 3vw;
}

/* 按钮 */
.btn-section {
  padding: 0 5vw;
}
.next-btn {
  font-size: 4vw;
  height: 12vw;
  background: linear-gradient(90deg, #0072f8 0%, #3a9fff 100%);
  border: none;
}
.next-btn:disabled {
  background: #3a9fff;
  color: #fff;
}
</style>
