import {useState, useEffect, useCallback} from 'react'
import Taro from '@tarojs/taro'
import {getShopDealerApply} from '@/api/shop/shopDealerApply'
import type {ShopDealerApply} from '@/api/shop/shopDealerApply/model'

// Hook 返回值接口
export interface UseDealerApplyReturn {
  // 经销商用户信息
  dealerApply: ShopDealerApply | null
  // 加载状态
  loading: boolean
  // 错误信息
  error: string | null
  // 刷新数据
  refresh: () => Promise<void>
}


/**
 * 经销商用户 Hook - 简化版本
 * 只查询经销商用户信息和判断是否存在
 */
export const useDealerApply = (): UseDealerApplyReturn => {
  const [dealerApply, setDealerApply] = useState<ShopDealerApply | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const userId = Taro.getStorageSync('UserId');

  // 获取经销商用户数据
  const fetchDealerData = useCallback(async () => {

    if (!userId) {
      console.log('🔍 用户未登录，提前返回')
      setDealerApply(null)
      return
    }

    try {
      setLoading(true)
      setError(null)

      // 查询当前用户的经销商信息
      const dealer = await getShopDealerApply(userId)

      if (dealer) {
        setDealerApply(dealer)
      } else {
        setDealerApply(null)
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取经销商信息失败'
      setError(errorMessage)
      setDealerApply(null)
    } finally {
      setLoading(false)
    }
  }, [userId])

  // 刷新数据
  const refresh = useCallback(async () => {
    await fetchDealerData()
  }, [fetchDealerData])

  // 初始化加载数据
  useEffect(() => {
    if (userId) {
      console.log('🔍 调用 fetchDealerData')
      fetchDealerData()
    } else {
      console.log('🔍 用户ID不存在，不调用 fetchDealerData')
    }
  }, [fetchDealerData, userId])

  return {
    dealerApply,
    loading,
    error,
    refresh
  }
}
