import { reactive, toRefs } from 'vue'
interface Pageable {
  pageNum: number
  pageSize: number
  total: number
  RemainingTime?: number
  small: boolean
  disabled: boolean
}
interface Table {
  tableData: any[]
  pageable: Pageable
  searchParam: any
  searchInitParam: any
  totalParam: any
}

/**
 *
 * @param requestApi 请求接口
 * @param initParam 请求参数
 * @param isPagination 是否需要分页
 * @param dataCallback 对后台返回参数进行处理
 * @returns
 */
export const useTable = (
  requestApi: (params: any) => Promise<any>,
  initParam: object = {},
  isPagination: boolean = true,
  dataCallback?: (data: any) => any
) => {
  const state = reactive<Table>({
    // 表格数据
    tableData: [],
    // 分页数据
    pageable: {
      // 当前页数
      pageNum: 1,
      // 每页显示条数
      pageSize: 10,
      // 总条数
      total: 0,
      RemainingTime: 0,
      small: false,
      disabled: false
    },
    // 查询参数(只包括查询)
    searchParam: {},
    // 初始化默认的查询参数
    searchInitParam: {},
    // 总参数(包含分页和查询参数)
    totalParam: {}
  })

  const getTableList = async () => {
    const params: any = {
      ...initParam,
      page: state.pageable.pageNum,
      page_z: state.pageable.pageSize
    }
    const res = await requestApi(params)
    dataCallback && dataCallback(res)
    state.tableData = res.Data.Data
    state.pageable.total = res.Data.Num
    if (res.Data.RemainingTime) {
      state.pageable.RemainingTime = res.Data.RemainingTime
    }
  }

  if (isPagination) {
  }

  const handleSizeChange = (val: number) => {
    state.pageable.pageSize = val
    getTableList()
  }

  const handleCurrentChange = (val: number) => {
    state.pageable.pageNum = val
    getTableList()
  }

  const searchTable = () => {
    state.pageable.pageNum = 1
    getTableList()
  }

  return {
    ...toRefs(state),
    getTableList,
    searchTable,
    handleSizeChange,
    handleCurrentChange
  }
}
