import { api } from "@nice/client";
import { useAuth } from "@web/src/providers/auth-provider";
import { Department, UserProfile } from "@nice/common";
import { createContext, ReactNode, useContext, useEffect, useState } from "react";

interface DailyContextProviderProps{
    staffs:UserProfile[],
    staffsLoading:boolean,
    depts:Department[],
    deptsLoading:boolean
}

interface DailyContextProps{
    children:ReactNode
}

const DailyContextProvider = createContext<DailyContextProviderProps>(null)

export default function DailyContext({children}:DailyContextProps){
    const {user,isAuthenticated} = useAuth()
    // 获取当前员工的单位下的所有staff的记录
    const {data:staffs,isLoading:staffsLoading} = isAuthenticated?api.staff.findByDept.useQuery({
        deptId:user.deptId
    }):{data:null,isLoading:false}

    const {data:depts,isLoading:deptsLoading} = isAuthenticated?api.department.getChildSimpleTree.useQuery({
        rootId:user.deptId
    }):{data:null,isLoading:false}
    
    useEffect(()=>{
        console.log(user)
    },[user])
    return <DailyContextProvider.Provider value={{
        staffs:staffs as any as UserProfile[],
        staffsLoading,
        depts:depts as any as Department[],
        deptsLoading
    }}>
        {children}
    </DailyContextProvider.Provider>
}

export function useDaily(){
    const daily = useContext(DailyContextProvider)
    if(!daily) {throw new Error("useParams must be used within a ParamsProvider");}
    return daily
}