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

interface DailyContextProviderProps{
    staffsMsg:{
        id:string,
        showname:string,
        username:string
    }[],
    staffsLoading:boolean,
    selectedUserMsg:UserProfile,
    setSelectedUserMsg:(userMsg:UserProfile)=>void
}

interface DailyContextProps{
    children:ReactNode
}

const DailyContextProvider = createContext<DailyContextProviderProps>(null)

export default function DailyContext({children}:DailyContextProps){
    const {user} = useAuth()
    const [selectedUserMsg,setSelectedUserMsg] = useState(null)
    // 获取当前员工的单位下的所有staff的记录
    const {data:staffs,isLoading:staffsLoading} = api.staff.findByDept.useQuery({
        deptId:user.deptId
    })
    const staffsMsg = staffs?.map((staff)=>{
        return {
            id:staff.id,
            showname:staff.showname,
            username:staff.username
        }
    })


    return <DailyContextProvider.Provider value={{
        staffsMsg,
        staffsLoading,
        selectedUserMsg,
        setSelectedUserMsg
    }}>
        {children}
    </DailyContextProvider.Provider>
}

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