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

type InfoContextValue = {
  info: Typetable
  info2: Typetable
  setInfoFu: (info: Typetable | ((prevInfo: Typetable) => Typetable), isTow?: boolean) => void
  snaps: GoodsType[]
  setSnapsFu: (snaps: GoodsType[]) => void
  timeKey: number
  setTimeKeyFu: () => void
  auditInfo: { status: number; rtfOpinion: string }
  setAuditInfoFu: (key: 'status' | 'rtfOpinion', val: string | number) => void
  editObj: { new: GoodsType; old: GoodsType; keyArr: string[] }
  setEditObjFu: (val: any) => 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)

  // 第二个模块的信息
  const [info2, setInfo2] = useState({} as Typetable)

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

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

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

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

  // 藏品修改信息
  const [editObj, setEditObj] = useState({} as any)

  const setEditObjFu = useCallback((val: any) => {
    setEditObj(val)
  }, [])

  const value = useMemo(
    () => ({
      info,
      info2,
      setInfoFu,
      snaps,
      setSnapsFu,
      timeKey,
      setTimeKeyFu,
      auditInfo,
      setAuditInfoFu,
      editObj,
      setEditObjFu
    }),
    [
      auditInfo,
      editObj,
      info,
      info2,
      setAuditInfoFu,
      setEditObjFu,
      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
}
