<template>
  <div class="identity-page">
    <van-nav-bar title="自然人开票" fixed placeholder />

    <!-- 上传区域 -->
    <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="onNext">
        下一步
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { showToast, showFailToast } from 'vant'
import { sysFileUploadApi } from '@/services/modules/common'

/** 上传项类型 */
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
}

/** 背景图 */
import frontBg from '@/assets/images/id-front-bg.png'
import backBg from '@/assets/images/id-back-bg.png'

/** 上传列表 */
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}`

      target.fileList = [{ url: fullUrl, status: 'done', fileId: res.data.fileId }]
      showToast(`${item.label} 上传成功`)

      // 调用OCR识别
      const ocrRes = await handleOcrCheck(item.field, res.data.fileId, fullUrl)
      if (!ocrRes.success) {
        // OCR 识别失败：清除该图片并提示
        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） */
const handleOcrCheck = async (
  side: 'front' | 'back',
  fileId: string,
  url: string,
): Promise<{ success: boolean }> => {
  // 示例：这里可以根据 side 调用不同的 OCR 接口
  // 例如 front 调用 /ocr/idcard/front   back 调用 /ocr/idcard/back
  try {
    console.log('识别请求 =>', { side, fileId, url })
    // 模拟延时识别
    await new Promise((resolve) => setTimeout(resolve, 800))

    // ✅ 模拟成功 / ❌ 模拟失败
    const success = Math.random() > 0.2 // 80% 成功率示例
    return { success }
  } catch (err) {
    console.error('OCR error', err)
    return { success: false }
  }
}

/** 是否完成上传 */
const isReady = computed(() => uploadList.value.every((item) => item.fileList.length > 0))

/** 下一步按钮点击 */
const onNext = () => {
  if (!isReady.value) return showToast('请先上传身份证正反面')

  // 拼装最终提交数据
  const result = uploadList.value.map((item) => ({
    field: item.field,
    fileId: item.fileList[0]?.fileId,
    url: item.fileList[0]?.url,
  }))

  console.log('提交数据:', result)
  showToast('上传完成，进入下一步')
}
</script>

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

/* 上传区域 */
.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;
}

/* 预览图尺寸与上传框保持一致 */
.custom-uploader >>> .van-uploader__preview,
.custom-uploader >>> .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, #ff7a00, #ff9800);
  border: none;
}
.next-btn:disabled {
  background: #ffd1a1;
  color: #fff;
}
</style>
