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,
  page: Ref<number>,
  noMore: Ref<boolean>,
  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 {
      let {
        flightDate,
        inOrOut,
        planeType,
        sAirport,
        eAirport,
        flightType,
        sFlightDate,
        company,
        startDate,
        endDate,
        keyWords,
      } = formData
      if (
        tableName === 'waybill' &&
        typeof keyWords === 'string' &&
        keyWords.length === 11
      ) {
        keyWords = `${keyWords.slice(0, 3)}-${keyWords.slice(3)}`
      }
      let dataContent =
        tableName === 'flight'
          ? [
              keyWords,
              company,
              flightDate,
              planeType,
              sAirport,
              eAirport,
              flightType,
              sFlightDate,
            ]
          : [startDate, endDate, keyWords]
      dataContent = dataContent.map(v => (v === '' ? null : v))
      const {
        code,
        returnData: { columnSet, listValues },
        message,
      } = await Query<CommonData>({
        id: idGetter(tableName),
        dataContent: defaultDataContent ?? dataContent,
        needPage: page.value,
      })
      if (Number(code) !== 0) {
        throw new Error(message || '失败')
      }
      tableColumns.value = columnSet.map(column => ({
        ...column,
        width:
          (tableName === 'flight' &&
            ['IATACode', 'flightNO'].includes(column.columnName) &&
            80) ||
          undefined,
      }))
      if (listValues.length) {
        tableData.value.push(
          ...listValues.filter(
            row =>
              !Object.values(row).some(
                cellValue =>
                  typeof cellValue === 'string' &&
                  cellValue.includes('undefined')
              )
          )
        )
      } else {
        page.value--
        noMore.value = true
      }
    } catch (error) {
      console.error(error)
      page.value--
      noMore.value = true
    }
    if (loading) {
      loading.value = false
    }
  }

  onMounted(() => {
    const defaultDataContent =
      tableName === 'flight'
        ? [null, null, '2000-01-01', null, null, null, null, null]
        : [null, null, null]
    getTableData(defaultDataContent)
  })

  return {
    tableColumns,
    tableData,
    getTableData,
  }
}
