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

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

const tableColumnsMap: {
  [tableName: string]: {
    columnLabel: string
    columnName: string
    [x: string]: any
  }[]
} = {
  flight: [
    {
      columnLabel: '航司二字码',
      columnName: 'IATACode',
      width: 80,
    },
    {
      columnLabel: '航班号',
      columnName: 'flightNO',
      width: 80,
    },
    {
      columnLabel: '机型',
      columnName: 'planeType',
    },
    {
      columnLabel: '起飞机场',
      columnName: 'departureAirport',
    },
    {
      columnLabel: '经停机场',
      columnName: 'transferAirport',
    },
    {
      columnLabel: '降落机场',
      columnName: 'landingAirport',
    },
    {
      columnLabel: '计划起飞时间',
      columnName: 'planDepartureTime',
    },
    {
      columnLabel: '实际起飞时间',
      columnName: 'acDepartureTime',
    },
    {
      columnLabel: '计划降落时间',
      columnName: 'planLandingTime',
    },
    {
      columnLabel: '实际降落时间',
      columnName: 'acLandingTime',
    },
    {
      columnLabel: '航班类型',
      columnName: 'flightType',
    },
    {
      columnLabel: '航班状态',
      columnName: 'flightState',
    },
    {
      columnLabel: '国内国际',
      columnName: 'DIType',
    },
    {
      columnLabel: '国内国际标识',
      columnName: 'DIType_OLD',
    },
  ],
  waybill: [
    {
      columnLabel: '运单号',
      columnName: 'stockCode',
    },
    {
      columnLabel: '品名',
      columnName: 'typeCode',
    },
    {
      columnLabel: '离港航班号',
      columnName: 'flightNO',
    },
    {
      columnLabel: '离港航班日期',
      columnName: 'flightDate',
    },
    {
      columnLabel: '离港出发机场',
      columnName: 'departureAirport',
    },
    {
      columnLabel: '离港到达机场',
      columnName: 'arriveAirport',
    },
    {
      columnLabel: '总重量',
      columnName: 'weight',
    },
    {
      columnLabel: '总件数',
      columnName: 'luggageCount',
    },
    {
      columnLabel: '计费重量',
      columnName: 'feeWeight',
    },
  ],
}

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,
        flightNO,
      } = 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,
            ]
          : tableName === 'waybill'
          ? [startDate, endDate, flightNO, keyWords]
          : [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,
        pageSize: 9999,
        // needPage: page.value,
      })
      if (Number(code) !== 0) {
        throw new Error(message || '失败')
      }
      if (!tableColumnsMap[tableName]) {
        tableColumns.value = columnSet
      }
      if (listValues.length) {
        tableData.value.push(
          ...listValues.filter(
            (row) =>
              !Object.values(row).some(
                (cellValue) =>
                  typeof cellValue === 'string' &&
                  cellValue.includes('undefined')
              )
          )
        )
        tableData.value.forEach((row, rowIndex) => {
          row.index = rowIndex + 1
        })
      } else {
        page.value--
        noMore.value = true
      }
    } catch (error) {
      console.error(error)
      page.value--
      noMore.value = true
    }
    if (loading) {
      loading.value = false
    }
  }

  const route = useRoute()
  const { flightDate, stockCode } = route.query

  onMounted(() => {
    if (tableColumnsMap[tableName]) {
      tableColumns.value = tableColumnsMap[tableName].map((column) => ({
        columnDescribe: '',
        dataType: '',
        listqueryTemplateID: null,
        needCount: null,
        needFilters: null,
        needGroup: null,
        needSearch: null,
        needShow: 1,
        needSort: null,
        orderNumber: null,
        queryTemplateColumnSetID: null,
        queryTemplateID: null,
        ...column,
      }))
    }

    // const defaultDataContent =
    //   tableName === 'flight'
    //     ? [null, null, '2000-01-01', null, null, null, null, null]
    //     : stockCode
    //     ? [flightDate, flightDate, stockCode]
    //     : [null, null, null]
    // getTableData(defaultDataContent as CommonValue[])
    if (tableName === 'waybill') {
      formData.startDate = formData.endDate = null
      if (stockCode) {
        formData.keyWords = stockCode as string
        getTableData()
      }
    } else if (tableName === 'freight') {
      getTableData([null, null, null])
    }
  })

  return {
    tableColumns,
    tableData,
    getTableData,
  }
}
