import { defineStore } from 'pinia'
import { ref } from 'vue'
import { post } from '@/utils/request'

export interface AgentApplyRecord {
  id: number
  memberId: number
  realName: string
  phone: string
  email: string
  auditStatus: 0 | 1 | 2
  rejectReason: string | null
  createTime: string
  updateTime: string
}

export const useAgentApplyStore = defineStore('agentApply', () => {
  const submitting = ref(false)
  const submitError = ref<string | null>(null)

  const list = ref<AgentApplyRecord[]>([])
  const listLoading = ref(false)
  const listError = ref<string | null>(null)
  const totalPages = ref(0)
  const totalElements = ref(0)
  const pageNo = ref(1)
  const pageSize = 10

  async function submit(): Promise<void> {
    submitting.value = true
    submitError.value = null
    try {
      await post('/uc/agent/apply/submit', {})
    } catch (e) {
      submitError.value = e instanceof Error ? e.message : '申请提交失败'
      throw e
    } finally {
      submitting.value = false
    }
  }

  /** 是否存在待审核（auditStatus=0）的申请 */
  async function hasPendingApply(): Promise<boolean> {
    try {
      const data = await post<{
        content: AgentApplyRecord[]
      }>('/uc/agent/apply/my-list', { pageNo: 1, pageSize: 50 })
      return (data?.content ?? []).some((r) => r.auditStatus === 0)
    } catch {
      return false
    }
  }

  async function fetchList(page = 1): Promise<void> {
    listLoading.value = true
    listError.value = null
    try {
      const data = await post<{
        content: AgentApplyRecord[]
        totalElements: number
        totalPages: number
        size: number
        number: number
      }>('/uc/agent/apply/my-list', { pageNo: page, pageSize })
      list.value = data?.content ?? []
      totalElements.value = data?.totalElements ?? 0
      totalPages.value = data?.totalPages ?? 0
      pageNo.value = page
    } catch (e) {
      listError.value = e instanceof Error ? e.message : '获取申请记录失败'
    } finally {
      listLoading.value = false
    }
  }

  return {
    submitting, submitError,
    list, listLoading, listError,
    totalPages, totalElements, pageNo,
    submit, fetchList, hasPendingApply,
  }
})
