import React, { useReducer, useEffect, useState, Fragment } from 'react'
import List from '../components/List'
import Item from '../components/item'
import Paging from '../components/Paging'
import styles from './index.module.css'
import GrentOper from './GrentOper'
import {
  initialState,
  reducer,
  getList,
  getListAction,
  delItemAction,
  updateItemAction
} from './ListState'

interface ItemsProps {
  list: Array<any>,
  children: Function,
  changePage: Function,
  total: number,
  current: number
}

const ListItems = (props: ItemsProps) => {
  return (
    <Fragment>
      <List data={props.list} className={styles.listlayer}>
        <Item data={['文件名', '路径', '类型', '创建时间', '当前状态', '操作']} />
        {(model: Model) => props.children(model)}
      </List>
      <div className={styles.paging}>
        <Paging
          total={props.total}
          current={props.current}
          show={5}
          handleChange={(current: number) => props.changePage(current)} />
      </div>

    </Fragment>
  )
}


interface GrentApi {
  getUrl: string,
  delUrl: string,
  zipUrl?: string,
  sectionUrl?: string,
  transformUrl?: string,
  transferUrl?: string,
  judgeUrl?: string,
  ItemFn?: Function,
  region?: boolean
}
export default function GrentReducer({ getUrl, delUrl, zipUrl, sectionUrl, transformUrl, transferUrl, judgeUrl, ItemFn, region  }: GrentApi) {
  let [referCount, setReferCount] = useState(0)
  let [modelState, modelDispatch] = useReducer(reducer, initialState())
  const models = getList(modelState)
  const updateAction = (current: number) => getListAction(modelDispatch, getUrl, current)
  const referData = () => setReferCount(++referCount)
  const delHandle = async (model: Model) => {
    await delItemAction(modelDispatch, delUrl + model.id + '/', model)
    setReferCount(++referCount)
  }
  const referItem = (model: Model): Model => updateItemAction(modelDispatch, model)
  const setItemStaus = (model: Model, status: number) : Model => {
    model.ajaxStatue = status
    return referItem(model)
  }

  useEffect(() => { updateAction(modelState.paging.current) }, [referCount])

  


  const Element = (
    <ListItems
      list={models}
      total={modelState.paging.total}
      current={modelState.paging.current}
      changePage={(page: number) => updateAction(page)}>
      {(model: Model) => {
        let { ItemFn: PublicItemFn } = GrentOper({
          setItemStaus,
          modelDispatch,
          referData,
          delHandle,
          api: { zip: zipUrl, section: sectionUrl, transfer: transferUrl, judge: judgeUrl, transform: transformUrl },
          region
        })
        return (
          <Fragment key={model.id}>
            {PublicItemFn(model, ItemFn)}
          </Fragment>
        )
        }}
    </ListItems>
  )

  return {
    modelDispatch,
    models,
    referData,
    delHandle,
    updateAction,
    referItem,
    Element,
    setItemStaus
  }
}
