import {useState, useEffect, useCallback} from 'react'
import Taro from '@tarojs/taro'
import {ClinicDoctorUser} from "@/api/clinic/clinicDoctorUser/model";
import {getClinicDoctorUser} from "@/api/clinic/clinicDoctorUser";

// Hook 返回值接口
export interface ClinicDoctorUserReturn {
  // 医师用户信息
  doctorUser: ClinicDoctorUser | null
  // 加载状态
  loading: boolean
  // 错误信息
  error: string | null
  // 刷新数据
  refresh: () => Promise<void>
}


/**
 * 医师用户 Hook - 简化版本
 * 只查询医师用户信息和判断是否存在
 */
export const useDoctorUser = (): ClinicDoctorUserReturn => {
  const [doctorUser, setDoctorUser] = useState<ClinicDoctorUser | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

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

  // 获取医师用户数据
  const fetchDoctorData = useCallback(async () => {

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

    try {
      setLoading(true)
      setError(null)

      // 查询当前用户的医师信息
      const doctor = await getClinicDoctorUser(userId)

      if (doctor) {
        setDoctorUser(doctor)
      } else {
        setDoctorUser(null)
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取医师信息失败'
      setError(errorMessage)
      setDoctorUser(null)
    } finally {
      setLoading(false)
    }
  }, [userId])

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

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

  return {
    doctorUser,
    loading,
    error,
    refresh
  }
}
