import style from './style.module.scss'
import { SceneType } from "constant"
import { memo } from 'react'
import { Table, Input, Button, Upload, message } from 'antd'
import { useTypeColumns } from './cloumns'
import { useThunkPaging } from 'hook'
import { 
  useSelector, 
  useDispatch,
  filterScenesSelector,
  fetchScenes,
  uploadModelScene
} from 'store'

import { GetSceneByTypeParams, PagingRequest } from 'api'
import type { UploadProps } from 'antd'

const { Search } = Input

type ListHeaderProps = SceneListProps & {
  onDataChange?: () => void,
  onSearch: (params: (GetSceneByTypeParams extends PagingRequest<infer T> ? Omit<T, 'type'> : never)) => void
}
const ListHeader = memo(({ type, onSearch, onDataChange }: ListHeaderProps) => {
  const dispatch = useDispatch()
  const onUpload: UploadProps['beforeUpload'] = file => {
    const isZip = ['application/zip', 'application/rar'].includes(file.type)
    if (!isZip) {
      message.error('只能上传zip或rar文件')
    }
    dispatch(uploadModelScene({ file }))
      .unwrap()
      .finally(onDataChange)
    return Upload.LIST_IGNORE
  }

  const renderUpload = type === SceneType.SWMX && (
    <Upload beforeUpload={onUpload} multiple={false} >
      <Button type="primary" children="上传数据" />
    </Upload>
  )

  return (
    <div className={style['table-header']}>
      { renderUpload }
      <Search
        className={style['table-search']}
        placeholder="输入名称搜索" 
        onSearch={sceneName => onSearch({ sceneName }) }
        style={{ width: 264 }} 
      />
    </div>
  )
})

export type SceneListProps = { type: SceneType }
export const SceneList = memo(({ type }: SceneListProps) => {
  const scenes = useSelector((state) => filterScenesSelector(state, { type }))
  const states = useThunkPaging({ type, sceneName: '' }, fetchScenes)
  const [[paging, setPaging], [, setParams], refresh] = states
  const cloumns = useTypeColumns(type, refresh)

  return (
    <div className={style['table-layout']}>
      <ListHeader type={type} onSearch={setParams} onDataChange={refresh} />

      <Table
        columns={cloumns} 
        dataSource={scenes} 
        rowKey="id"
        pagination={{
          showSizeChanger: false,
          pageSize: paging.pageSize,
          total: paging.total,
          onChange: (page, pageSize) => setPaging({ pageNum: page, pageSize })
        }}
      />
    </div>
  )
})

export default SceneList