import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'
import { getStatusApi, submitInvoiceApplyApi } from '@/services/modules/invoiceInformation'
import type { PushRecordIdRequest } from '@/services/modules/invoiceInformation/type.d.ts'
import { useUserStore } from '@/stores/modules/user'
import { getFaceAuthResultApi } from '@/services/modules/faceRecognition'

interface ToStatus {
  /** 待处理事件 */
  eventStatus?: string
  /** 开票状态 */
  invoiceStatus?: string
  /** 是否上传身份证图片 */
  isIdImgReady?: boolean
  [property: string]: any
}

/**
 * 发票状态 Hook
 * 用于复用：状态查询 + 提交开票申请
 */
export function useInvoice() {
  const userStore = useUserStore()
  const router = useRouter()

  const route = useRoute()

  // state
  const btnDisabled = ref(false)
  const statusMap = ref<ToStatus>({})
  const isLoading = ref(false)

  // 已提交状态映射
  const isSubmitStatusMap = ['PENDING', 'FINISHED', 'RED_INK_ENTRY', 'NOT_APPROVED', 'DISCARD']
  const isSubmitEventStatusMap = [
    'SUBMITTED',
    'PENDING_PAYMENT',
    'PAID',
    'PENDING_FINAL_INVOICING',
    'INVOICE_FAILED',
    'FINAL_INVOICE_SUBMITTED',
    'INVOICE_DOWNLOADABLE',
  ]

  // 请求参数
  const params = reactive<PushRecordIdRequest>({
    pushRecordId: userStore.pushRecordId,
  })

  const faceAuthResult = ref(false)

  // 获取认证结果
  const getFaceAuthResult = async () => {
    try {
      const res = await getFaceAuthResultApi(params)
      if (res.code === 0 && res.data?.success) {
        const rzzt = res.data.rzzt
        // 已认证或无需认证提交跳转
        if (rzzt === 'NO_REQUIRED_AUTHENTICATION') {
          faceAuthResult.value = true
        }
      }
    } catch (err: any) {
      console.error('获取认证结果失败', err)
      showToast(err!.message || '获取认证结果失败，请稍后重试')
      btnDisabled.value = true
    }
  }

  /**
   * 获取开票状态
   */
  const getStatus = async () => {
    isLoading.value = true
    try {
      const res = await getStatusApi(params)
      if (res.code === 0) {
        statusMap.value = res.data as ToStatus
        //  判断当前是否已提交
        const { invoiceStatus, eventStatus } = res.data
        const isInvoiceSubmitted = invoiceStatus && isSubmitStatusMap.includes(invoiceStatus)
        const isEventSubmitted = eventStatus && isSubmitEventStatusMap.includes(eventStatus)
        btnDisabled.value = isInvoiceSubmitted && isEventSubmitted
      }
    } catch (err) {
      console.error('获取状态失败', err)
      showToast('获取开票状态失败，请稍后重试')
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 提交开票申请
   */
  const submitInvoiceApply = async () => {
    try {
      // 1. 提交流程
      const res = await submitInvoiceApplyApi(params)
      // 2. 成功逻辑
      if (res.code === 0 && res.data) {
        showSuccessToast('提交成功')
        setTimeout(() => {
          userStore.LogOut()
          router.replace({ path: '/success' })
        }, 800)
        return
      }
      // 3. 失败逻辑（接口返回的错误）
      showToast(res.msg)
    } catch (err: any) {
      // 4. 异常逻辑
      console.error('提交失败', err)
      showToast(err.message)
    }

    // 5. 失败后统一处理 —— 判断当前页面是否需要跳转
    if (route.path !== '/h5/invoice-information/index') {
      setTimeout(() => {
        router.replace({
          path: '/invoice-information',
        })
      }, 1800)
    }
  }

  return {
    params,
    statusMap,
    btnDisabled,
    isLoading,
    faceAuthResult,
    getStatus,
    submitInvoiceApply,
    getFaceAuthResult,
  }
}
