import { Query } from '@/api/webApi'
import { Ref } from 'vue'
import { CommonData, CommonTableColumn, CommonValue } from '~/common'

const idGetter = (name: string) => DATACONTENT_ID[name + 'DataQuery']

export function useTable(
  tableName: string,
  formData: CommonData,
  loading?: Ref<boolean>
) {
  const tableColumns = ref<CommonTableColumn[]>([])
  const tableData = ref<CommonData[]>([])

  const getTableData = async (defaultDataContent?: CommonValue[]) => {
    if (!idGetter(tableName)) {
      return
    }
    if (loading) {
      loading.value = true
    }
    try {
      const { startDate, endDate, keyWords } = formData
      const dataContent = [startDate, endDate, keyWords || null]
      const {
        code,
        returnData: { columnSet, listValues },
        message,
      } = await Query<CommonData>({
        id: idGetter(tableName),
        dataContent: defaultDataContent ?? dataContent,
      })
      if (Number(code) !== 0) {
        throw new Error(message || '失败')
      }
      tableColumns.value = columnSet.map(column => ({
        ...column,
        width:
          (tableName === 'flight' &&
            ['IATACode', 'flightNO'].includes(column.columnName) &&
            80) ||
          undefined,
      }))
      tableData.value = listValues.filter(
        row =>
          !Object.values(row).some(
            cellValue =>
              typeof cellValue === 'string' && cellValue.includes('undefined')
          )
      )
    } catch (error) {
      console.error(error)
    }
    if (loading) {
      loading.value = false
    }
  }

  onMounted(() => {
    getTableData([null, null, null])
  })

  return {
    tableColumns,
    tableData,
    getTableData,
  }
}
