import { CommonData, CommonValue } from '~/common'
import { Query } from '@/api/webApi'
import { ElMessage } from 'element-plus'

const flightTypeMap = ['货机', '客机', '其他']
const flightStateMap = {
  CAN: '取消',
  DLY: '延误',
}

const flightInfoItemsMap = {
  departure: [
    [
      {
        label: '始发站',
        key: 'departureAirportZh',
      },
      {
        label: '计划起飞时间',
        getter: info => info.planDepartureTime?.replace('T', ' ') ?? '',
      },
      {
        label: '实际起飞时间',
        getter: info => info.acDepartureTime?.replace('T', ' ') ?? '',
      },
      {
        label: '机型',
        key: 'planeType',
      },
      {
        label: '航班类型',
        getter: info =>
          typeof info.flightType === 'number'
            ? flightTypeMap[info.flightType] ?? '其他'
            : '其他',
      },
      {
        label: '航班状态',
        getter: info =>
          info.flightState
            ? flightStateMap[info.flightState] ?? '正常'
            : '正常',
      },
      {
        label: '停机位',
        key: 'takeOffStand',
      },
    ],
    [
      {
        label: '特货信息/运单数',
        key: 'speCargoInfo',
      },
      {
        label: '核单运单数/件数',
        key: 'loadInfo',
      },
      // {
      //   label: '中转进运单/货物数',
      //   key: "transInfo",
      // },
      // {
      //   label: '已配载集装器',
      //   key: 'stowage_Yes',
      //   showOverflowTooltip: true,
      // },
      {
        label: '交接复核集装器数',
        key: 'depotJoin',
      },
      {
        label: '已配载集装器/运单数/重量',
        key: 'loadPlane',
      },
      {
        label: '拉下集装器/件数',
        key: 'pull',
      },
      // {
      //   label: '集装器数量',
      //   key: 'stowage',
      // },
    ],
    [
      {
        label: '目的站',
        key: 'landingAirportZh',
      },
      {
        label: '计划降落时间',
        getter: info => info.planLandingTime?.replace('T', ' ') ?? '',
      },
      {
        label: '实际降落时间',
        getter: info => info.acLandingTime?.replace('T', ' ') ?? '',
      },
    ],
  ],
  arrival: [
    [
      {
        label: '始发站',
        key: 'departureAirportZh',
      },
      {
        label: '计划起飞时间',
        getter: info => info.planDepartureTime?.replace('T', ' ') ?? '',
      },
      {
        label: '实际起飞时间',
        getter: info => info.acDepartureTime?.replace('T', ' ') ?? '',
      },
      {
        label: '机型',
        key: 'planeType',
      },
      {
        label: '航班类型',
        getter: info =>
          typeof info.flightType === 'number'
            ? flightTypeMap[info.flightType] ?? '其他'
            : '其他',
      },
      {
        label: '航班状态',
        getter: info =>
          info.flightState
            ? flightStateMap[info.flightState] ?? '正常'
            : '正常',
      },
    ],
    [
      {
        label: '特货信息/运单数',
        key: 'speCargoInfo',
      },
      // {
      //   label: '卸载运单数/货物数',
      //   key: 'unLoadListInfo',
      // },
      // {
      //   label: '中转进运单/货物数',
      //   key: "transIn",
      // },
      // {
      //   label: '已卸载集装器',
      //   key: 'unloadStowageNum',
      //   showOverflowTooltip: true,
      // },
      {
        label: '卸载集装器数（板/箱/卡）',
        key: 'unloadPlaneInfo',
      },
      // {
      //   label: '货站交接数量（板/箱/卡）',
      //   key: 'pull',
      // },
      {
        label: '理货完成运单数/件数',
        key: 'tally',
      },
      {
        label: '出库运单数/件数',
        key: 'outWarehouse',
      },
    ],
    [
      {
        label: '目的站',
        key: 'landingAirportZh',
      },
      {
        label: '计划降落时间',
        getter: info => info.planLandingTime?.replace('T', ' ') ?? '',
      },
      {
        label: '实际降落时间',
        getter: info => info.acLandingTime?.replace('T', ' ') ?? '',
      },
      {
        label: '停机位',
        key: 'landingStand',
      },
    ],
  ],
}

export function useFlightInfo(name: string, dataContent: CommonValue[]) {
  const flightInfoItems = ref<
    {
      label: string
      key?: string
      getter?: (info: any) => string
      showOverflowTooltip?: boolean
    }[][]
  >([])
  const getFlightInfoItems = () => {
    flightInfoItems.value =
      flightInfoItemsMap[name.includes('Departure') ? 'departure' : 'arrival']
  }
  getFlightInfoItems()

  const flightInfo: CommonData = reactive({})
  const getFlightInfo = async () => {
    try {
      const {
        code,
        returnData: { listValues },
        message,
      } = await Query({
        id:
          DATACONTENT_ID[
            `${name.slice(0, 1).toLowerCase()}${name.slice(1)}Info`
          ],
        dataContent,
      })
      if (Number(code) !== 0) {
        throw new Error(message ?? '失败')
      }
      if (!listValues.length) {
        ElMessage.info('未查询到航班信息')
        return
      }
      Object.assign(flightInfo, listValues[0])
    } catch (error) {
      console.error(error)
    }
  }

  const computedFlightInfo = computed(() => item => {
    if (['departureAirportZh', 'landingAirportZh'].includes(item.key)) {
      return airportNameZhMap[flightInfo[item.key.slice(0, -2)]!]
    }
    if (item.getter) {
      return item.getter(flightInfo)
    }
    if (item.key) {
      return String(flightInfo[item.key] ?? '')
    }
    return ''
  })

  const airportNameZhMap: { [code: string]: string } = reactive({})
  const getAirportNameZh = async (airportCode: string) => {
    try {
      const {
        code,
        returnData: { listValues },
        message,
      } = await Query({
        id: DATACONTENT_ID.airportNameZh,
        dataContent: [airportCode],
      })
      if (Number(code) !== 0) {
        throw new Error(message ?? '失败')
      }
      if (!listValues.length) {
        ElMessage.info('未查询到航班中文名：' + airportCode)
        return airportCode
      }
      return listValues[0].airportname
    } catch (error) {
      console.error(error)
      return airportCode
    }
  }

  watch(flightInfo, async () => {
    const { departureAirport, landingAirport } = flightInfo
    if (departureAirport) {
      if (!airportNameZhMap[departureAirport]) {
        airportNameZhMap[departureAirport] = await getAirportNameZh(
          String(departureAirport)
        )
      }
    }
    if (landingAirport) {
      if (!airportNameZhMap[landingAirport]) {
        airportNameZhMap[landingAirport] = await getAirportNameZh(
          String(landingAirport)
        )
      }
    }
  })

  return {
    flightInfoItems,
    flightInfo,
    computedFlightInfo,
    getFlightInfo,
  }
}
