import { createContext, ReactNode, useCallback, useContext, useMemo, useState } from 'react'
import { Typetable } from './data'
import { GoodsType } from './SonGoodsList/data'

type InfoContextValue = {
  info: Typetable
  setInfoFu: (info: Typetable | ((prevInfo: Typetable) => Typetable)) => void
  snaps: GoodsType[]
  setSnapsFu: (snaps: GoodsType[]) => void
  timeKey: number
  setTimeKeyFu: () => void
  auditInfo: { status: number; rtfOpinion: string }
  setAuditInfoFu: (key: 'status' | 'rtfOpinion', val: string | number) => void
}

type Props = {
  children: ReactNode
}

const InfoContext = createContext<InfoContextValue | undefined>(undefined)

export function InfoProvider({ children }: Props) {
  // 用来刷新页面
  const [timeKey, setTimeKey] = useState(0)

  const setTimeKeyFu = useCallback(() => {
    setTimeKey(Date.now())
  }, [])

  // 审批信息
  const [auditInfo, setAuditInfo] = useState({ status: 0, rtfOpinion: '' })

  const setAuditInfoFu = useCallback(
    (key: 'status' | 'rtfOpinion', val: number | string) => {
      setAuditInfo({ ...auditInfo, [key]: val })
    },
    [auditInfo]
  )

  // 顶部信息
  const [info, setInfo] = useState({} as Typetable)

  // useEffect(() => {
  //   console.log('xxxxxxxx', info)
  // }, [info])

  const setInfoFu = useCallback(
    (newInfoOrUpdater: Typetable | ((prevInfo: Typetable) => Typetable)) => {
      if (typeof newInfoOrUpdater === 'function') {
        setInfo(newInfoOrUpdater)
      } else {
        setInfo(newInfoOrUpdater)
      }
    },
    []
  )

  // 藏品信息
  const [snaps, setSnaps] = useState<GoodsType[]>([])

  const setSnapsFu = useCallback((snaps: GoodsType[]) => {
    setSnaps(snaps)
  }, [])

  const value = useMemo(
    () => ({
      info,
      setInfoFu,
      snaps,
      setSnapsFu,
      timeKey,
      setTimeKeyFu,
      auditInfo,
      setAuditInfoFu
    }),
    [auditInfo, info, setAuditInfoFu, setInfoFu, setSnapsFu, setTimeKeyFu, snaps, timeKey]
  )

  return <InfoContext.Provider value={value}>{children}</InfoContext.Provider>
}

// 自定义Hook，方便在子组件中使用
export const useInfo = (): InfoContextValue => {
  const context = useContext(InfoContext)
  if (context === undefined) {
    throw new Error('useInfo必须在InfoProvider内部使用')
  }
  return context
}
