<template>
  <div class="min-h-screen bg-[#FFF7F9] p-4 pb-8">
    <div
      class="relative overflow-hidden rounded-2xl border border-[#FFD7DF] bg-gradient-to-br from-[#FFF7F9] via-white to-[#FFE4EA] shadow-[0_12px_32px_rgba(232,66,77,0.08)] p-6 sm:p-7 backdrop-blur-sm">
      <div class="absolute -right-10 -top-16 h-40 w-40 rounded-full bg-[#FFE3EA] blur-3xl opacity-70"></div>
      <div class="absolute -left-14 -bottom-16 h-40 w-40 rounded-full bg-[#FFD6E2] blur-3xl opacity-60"></div>

      <div class="relative z-10 space-y-5">
        <div class="text-center text-xl text-[#E8424D] font-semibold">身份证核验</div>

        <!-- <div class="bg-white/90 rounded-xl p-4 shadow-[0_6px_18px_rgba(232,66,77,0.06)] border border-[#FFD7DF]">
          <div class="flex items-center justify-between mb-3">
            <div class="text-base font-semibold text-gray-800">结婚证信息</div>
            <button class="text-xs text-[#E8424D]" @click="goBack">返回上一页</button>
          </div>
          <div class="text-sm text-[#7A5967] space-y-2">
            <div>结婚证字号：{{ marriageInfo?.marriageNo || '-' }}</div>
              <div class="grid grid-cols-1 gap-2">
                <div class="flex items-center">
                  <span class="inline-block w-24 text-gray-500">男方姓名：</span>
                  <span class="text-gray-800">{{ marriageInfo?.husbandName || '-' }}</span>
                </div>
                <div class="flex items-center">
                  <span class="inline-block w-24 text-gray-500">男方证件号：</span>
                  <span class="text-gray-800 break-all">{{ marriageInfo?.husbandId || '未识别' }}</span>
                </div>
                <div class="flex items-center">
                  <span class="inline-block w-24 text-gray-500">女方姓名：</span>
                  <span class="text-gray-800">{{ marriageInfo?.wifeName || '-' }}</span>
                </div>
                <div class="flex items-center">
                  <span class="inline-block w-24 text-gray-500">女方证件号：</span>
                  <span class="text-gray-800 break-all">{{ marriageInfo?.wifeId || '未识别' }}</span>
                </div>
              </div>
            <div>登记日期：{{ marriageInfo?.registerDate || '-' }}</div>
          </div>
        </div> -->

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-5">
          <div class="bg-white/95 rounded-2xl p-5 shadow-[0_6px_18px_rgba(232,66,77,0.06)] border border-[#FFD7DF] flex flex-col gap-4">
            <div class="flex items-start gap-3">
              <div class="space-y-1">
                <div class="text-base font-semibold text-gray-800">上传男方身份证（人像面）</div>
                <div class="text-xs text-[#7A5967] leading-relaxed space-y-1">
                  <div>需与结婚证信息一致：</div>
                  <div class="flex flex-col gap-0.5 text-gray-800">
                    <span>姓名：{{ marriageInfo?.husbandName || '-' }}</span>
                    <span class="break-all">证件号：{{ marriageInfo?.husbandId || '身份证号未识别' }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="text-xs text-[#7A5967] bg-[#FFF3F5] border border-[#FFE0E7] rounded-lg p-3 leading-relaxed">
              身份证照片需清晰无遮挡，保持文字方向正确，四角完整，避免反光或模糊。
            </div>

            <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
              <button
                class="flex-1 h-14! px-5 py-3! rounded-xl text-base font-semibold border border-[#E8424D]! text-[#E8424D]! bg-white! hover:bg-[#FFE8EE]! active:bg-[#FFD6E2]! active:scale-98 transition disabled:border-gray-300! disabled:text-gray-400! disabled:bg-gray-100!"
                @click="triggerUpload('husband')" :disabled="!userInfo">
                上传
              </button>
              <div
                :class="['flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-3 min-h-[48px] sm:w-48', statusPanelClass(husbandMatchedStatus)]">
                <span :class="['inline-block w-2.5 h-2.5 rounded-full', statusDotClass(husbandMatchedStatus)]"></span>
                <span>{{ husbandMatchedStatus === '待上传' ? '等待上传' : husbandMatchedStatus }}</span>
              </div>
            </div>
          </div>

          <div class="bg-white/95 rounded-2xl p-5 shadow-[0_6px_18px_rgba(232,66,77,0.06)] border border-[#FFD7DF] flex flex-col gap-4">
            <div class="flex items-start gap-3">
              <div class="space-y-1">
                <div class="text-base font-semibold text-gray-800">上传女方身份证（人像面）</div>
                <div class="text-xs text-[#7A5967] leading-relaxed space-y-1">
                  <div>需与结婚证信息一致：</div>
                  <div class="flex flex-col gap-0.5 text-gray-800">
                    <span>姓名：{{ marriageInfo?.wifeName || '-' }}</span>
                    <span class="break-all">证件号：{{ marriageInfo?.wifeId || '身份证号未识别' }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="text-xs text-[#7A5967] bg-[#FFF3F5] border border-[#FFE0E7] rounded-lg p-3 leading-relaxed">
              身份证照片需清晰无遮挡，保持文字方向正确，四角完整，避免反光或模糊。
            </div>

            <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
              <button
                class="flex-1 h-14! px-5 py-3! rounded-xl text-base font-semibold border border-[#E8424D]! text-[#E8424D]! bg-white! hover:bg-[#FFE8EE]! active:bg-[#FFD6E2]! active:scale-98 transition disabled:border-gray-300! disabled:text-gray-400! disabled:bg-gray-100!"
                @click="triggerUpload('wife')" :disabled="!userInfo">
                上传
              </button>
              <div
                :class="['flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-3 min-h-[48px] sm:w-48', statusPanelClass(wifeMatchedStatus)]">
                <span :class="['inline-block w-2.5 h-2.5 rounded-full', statusDotClass(wifeMatchedStatus)]"></span>
                <span>{{ wifeMatchedStatus === '待上传' ? '等待上传' : wifeMatchedStatus }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="pt-2">
          <button
            class="w-full h-14 bg-gradient-to-r from-[#E8424D]! to-[#FF7A7A]! text-white! rounded-full text-lg font-bold transition-all hover:opacity-90 active:scale-98 disabled:from-[#8a8a8a]! disabled:to-[#8a8a8a]!"
            @click="submitClaim" :disabled="!canSubmit || submitting">
            <div class="text-lg">{{ submitting ? '提交中...' : '提交领取喜礼' }}</div>
          </button>
        </div>
      </div>
    </div>

    <input type="file" ref="husbandUpload" class="hidden" accept="image/*" @change="handleIdChange('husband')" />
    <input type="file" ref="wifeUpload" class="hidden" accept="image/*" @change="handleIdChange('wife')" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import apiService, { type IdCardOcrParseResponse } from '@/services/apiService'
import { showLoading, hideLoading } from '@/components/loading'
import { showDialog } from 'vant'
import 'vant/es/dialog/style'

type Role = 'husband' | 'wife'
type MarriageInfo = {
  marriageNo?: string
  husbandName?: string
  wifeName?: string
  registerDate?: string
  certificateHolder?: string
  wifeId?: string
  husbandId?: string
  wifeGender?: string | null
  husbandGender?: string | null
  wifeBirthDate?: string
  husbandBirthDate?: string
  wifeNationality?: string
  husbandNationality?: string
  phone?: string
  smsCode?: string
}

const STORAGE_KEY_USER = 'userAs'
const STORAGE_KEY_MARRIAGE = 'marriageOcr'

const router = useRouter()

const userInfo = ref<{ phone: string; smsCode: string } | null>(null)
const marriageInfo = ref<MarriageInfo | null>(null)
const husbandUpload = ref<HTMLInputElement>()
const wifeUpload = ref<HTMLInputElement>()
const husbandIdParsed = ref<IdCardOcrParseResponse['parsed'] | null>(null)
const wifeIdParsed = ref<IdCardOcrParseResponse['parsed'] | null>(null)
const submitting = ref(false)

const loadFromStorage = () => {
  const userRaw = localStorage.getItem(STORAGE_KEY_USER)
  const marriageRaw = localStorage.getItem(STORAGE_KEY_MARRIAGE)

  if (!userRaw || !marriageRaw) {
    showDialog({
      message: '请先完成手机验证与结婚证识别',
    }).then(() => router.replace('/claim'))
    return
  }

  try {
    const user = JSON.parse(userRaw)
    const marriage = JSON.parse(marriageRaw)
    if (!user?.smsCode || marriage?.smsCode !== user.smsCode) {
      localStorage.removeItem(STORAGE_KEY_MARRIAGE)
      showDialog({
        message: '验证码已失效，请重新验证后再试',
      }).then(() => router.replace('/claim'))
      return
    }
    userInfo.value = { phone: user.phone, smsCode: user.smsCode }
    marriageInfo.value = marriage
  } catch (error) {
    console.error('读取本地缓存失败', error)
    showDialog({
      message: '身份信息读取失败，请重新验证',
    }).then(() => router.replace('/claim'))
  }
}

onMounted(() => {
  loadFromStorage()
})

const normalize = (val?: string | null) => (val || '').replace(/\s+/g, '').toUpperCase()

const checkMatch = (parsed: IdCardOcrParseResponse['parsed'] | null, target: { name?: string; id?: string; gender?: string | null }) => {
  if (!parsed || !target.name) return false
  const nameMatched = normalize(parsed.name) === normalize(target.name)
  const idMatched = target.id ? normalize(parsed.id_number) === normalize(target.id) : true
  const genderMatched = target.gender ? parsed.gender === target.gender : true
  return nameMatched && idMatched && genderMatched
}

const IMAGE_STATUS_TEXT: Record<IdCardOcrParseResponse['parsed']['image_status'], string> = {
  normal: '识别正常',
  reversed_side: '身份证正反面颠倒',
  non_idcard: '上传的图片中不包含身份证',
  blurred: '身份证模糊',
  other_type_card: '其他类型证照',
  over_exposure: '身份证关键字段反光或过曝',
  over_dark: '身份证欠曝（亮度过低）',
  unknown: '未知状态',
}

const isImageNormal = (parsed: IdCardOcrParseResponse['parsed'] | null) => parsed?.image_status === 'normal'

const husbandMatched = computed(() =>
  isImageNormal(husbandIdParsed.value) &&
  checkMatch(husbandIdParsed.value, {
    name: marriageInfo.value?.husbandName,
    id: marriageInfo.value?.husbandId,
    gender: marriageInfo.value?.husbandGender,
  })
)
const wifeMatched = computed(() =>
  isImageNormal(wifeIdParsed.value) &&
  checkMatch(wifeIdParsed.value, {
    name: marriageInfo.value?.wifeName,
    id: marriageInfo.value?.wifeId,
    gender: marriageInfo.value?.wifeGender,
  })
)

const resolveIdCardStatus = (parsed: IdCardOcrParseResponse['parsed'] | null, matched: boolean) => {
  if (!parsed) return '待上传'
  if (!isImageNormal(parsed)) return IMAGE_STATUS_TEXT[parsed.image_status] || '未知状态'
  return matched ? '已匹配' : '信息不一致'
}

const husbandMatchedStatus = computed(() => resolveIdCardStatus(husbandIdParsed.value, husbandMatched.value))
const wifeMatchedStatus = computed(() => resolveIdCardStatus(wifeIdParsed.value, wifeMatched.value))

const statusPanelClass = (status: string) => {
  if (status === '已匹配') return 'text-green-700 bg-green-50 border-green-200'
  if (status === '待上传') return 'text-gray-600 bg-gray-50 border-gray-200'
  return 'text-[#E8424D] bg-[#FFF3F5] border-[#FFD7DF]'
}

const statusDotClass = (status: string) => {
  if (status === '已匹配') return 'bg-green-500 shadow-[0_0_0_4px_rgba(34,197,94,0.15)]'
  if (status === '待上传') return 'bg-gray-400 shadow-[0_0_0_4px_rgba(156,163,175,0.15)]'
  return 'bg-[#E8424D] shadow-[0_0_0_4px_rgba(232,66,77,0.15)]'
}

const canSubmit = computed(() => husbandMatched.value && wifeMatched.value && !!marriageInfo.value && !!userInfo.value)

const triggerUpload = (role: Role) => {
  if (role === 'husband') {
    husbandUpload.value?.click()
  } else {
    wifeUpload.value?.click()
  }
}

const handleIdChange = async (role: Role) => {
  const input = role === 'husband' ? husbandUpload.value : wifeUpload.value
  const file = input?.files?.[0]
  if (!file) {
    showDialog({
      message: '请选择图片文件',
    })
    return
  }
  if (!userInfo.value) {
    showDialog({
      message: '请先返回上一页完成验证',
    })
    return
  }

  const formFormData = new FormData()
  formFormData.append('file', file)

  showLoading()
  try {
    const response: any = await apiService.uploadOcrImage(formFormData)
    const res: any = await apiService.idCardParseOcrInfo({
      mobile: userInfo.value.phone,
      smsCode: userInfo.value.smsCode,
      uploadId: response.data.uploadId,
    })
    const parsed = res?.data?.parsed
    if (!parsed) {
      throw new Error('识别失败，请重试')
    }
    if (role === 'husband') {
      husbandIdParsed.value = parsed
    } else {
      wifeIdParsed.value = parsed
    }
  } catch (error: any) {
    console.error('身份证识别失败', error)
    const msg = error?.msg || error?.message || '身份证识别失败，请稍后重试'
    showDialog({
      message: msg,
    }).then(() => {
      if (msg.includes('验证码')) {
        localStorage.removeItem(STORAGE_KEY_MARRIAGE)
        router.replace('/claim')
      }
    })
  } finally {
    hideLoading()
    if (input) {
      input.value = ''
    }
  }
}

const submitClaim = async () => {
  if (!canSubmit.value || !marriageInfo.value || !userInfo.value) return
  submitting.value = true
  showLoading()
  try {
    await apiService.receiveCheck({
      marriageNo: marriageInfo.value.marriageNo,
      receiveName: marriageInfo.value.husbandName || marriageInfo.value.certificateHolder || marriageInfo.value.wifeName,
      receiveMobile: userInfo.value.phone,
      smsCode: userInfo.value.smsCode,
    })
    showDialog({
      message: '提交成功，请返回首页查看核销二维码',
    }).then(() => {
      router.replace('/claim')
    })
  } catch (error: any) {
    const msg = error?.msg || '提交失败，请稍后重试'
    showDialog({
      message: msg,
    }).then(() => {
      if (msg.includes('验证码')) {
        localStorage.removeItem(STORAGE_KEY_MARRIAGE)
        router.replace('/claim')
      }
    })
  } finally {
    hideLoading()
    submitting.value = false
  }
}

const goBack = () => {
  router.back()
}
</script>
