import { useEffect, useRef, useState } from 'react'
import HeaderFilter from './components/HeaderFilter'
import ContentTable from './components/ContentTable'
import CreateModal from './components/CreateModal'
import { useGlobalStateUpdate } from '@src/store/globalStates/loadingState'
import { 
  createAd as createAdRequest,
  getAdList,
  openAd,
  clsoeAd,
  getAllAppList
} from './request'
import type { 
  RowDataType, 
  PaginationParamsType, 
} from './components/ContentTable/types'
import type { 
  RefType, 
  FormDataType 
} from './components/CreateModal/types'
import type { AllAppListItemType } from './types'



export function AdManage(){
  const [tableData, setTableData] = useState<RowDataType[]>([])
  const [total, setTotal] = useState(0)
  const [paginationParams, setPaginationParams] = useState<PaginationParamsType>({ pageNumber:1, pageSize:10})
  const [allAppList, setAllAppList] = useState<AllAppListItemType[]>([])
  const createModalRef = useRef<RefType>()
  const setloading = useGlobalStateUpdate()

  useEffect(()=>{
    getAllAppList().then(res=>{
      if (res) {
        setAllAppList(res)
      }
    })
  },[])

  useEffect(()=>{
    getTableData()   
  },[paginationParams])

  const  getTableData = async () => {
    setloading(true)
    
    const {pageNumber,pageSize} = paginationParams
    const data = await getAdList({
      pageSize,
      currentPage: pageNumber,
    })
    if (data) {
      setTableData(data.objs)
      setTotal(data.totalSize)
    }

    setloading(false)
  }

  const onPaginationChange =async (params:PaginationParamsType) => {
    setPaginationParams(params)
  }

  const onCreate = () => {
    createModalRef.current?.open()
  }

  const onSwitchStatus = async ({row, checked}:{row:RowDataType, checked:boolean}) => {
    setloading(true)
    const res =  checked ? await openAd(row.id) : await clsoeAd(row.id)
    setloading(false)
    if (res) {
      getTableData()
    }
  }

  const createAd = async (form:FormDataType, cb:EventFunctionType<[]>) => {
    setloading(true)
    const res = await createAdRequest(form)
    setloading(false)
    if (res) {
      getTableData()
      cb() // 关闭modal
    }
  }

  const updateAd = (form:RowDataType,  cb:EventFunctionType<[]>) => {
    console.log('更新',form)
    // TODO 更新接口
    cb()
  }

  return (
    <>
      <HeaderFilter onCreate={onCreate} />
      <ContentTable 
        total={total} 
        pageNumber={paginationParams.pageNumber}
        pageSize={paginationParams.pageSize}
        tableData={tableData} 
        onPaginationChange = {onPaginationChange}
        onSwitchStatus={onSwitchStatus}
      />
      <CreateModal 
        ref={createModalRef}
        allAppList={allAppList}
        onCreate={createAd}
        onUpdate={updateAd}
      />
    </>
  )
}