import { CommonData, CommonValue, MaybeRef } from '~/common'
import { Query } from '@/api/webApi'
import { ElMessage } from 'element-plus'
import _ from 'lodash'
import { parseTime } from '@/utils/validate'

type FlightInfoItem = {
  label: string
  key?: string
  getter?: (info: CommonData, UTCFlag?: boolean) => string
}

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

const datetimeFormatter = (str: any, UTCFlag?: boolean) => {
  if (typeof str !== 'string' || !str) {
    return ''
  }
  const datetime = new Date(str.replace('T', ' '))
  if (UTCFlag) {
    datetime.setTime(datetime.getTime() - 8 * 60 * 60 * 1000)
  }
  return parseTime(datetime, '{y}-{m}-{d} {h}:{i}:{s}') as string
}

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

export function useFlightInfo(
  name: string,
  dataContent: CommonValue[],
  UTCFlag?: MaybeRef<boolean>
) {
  const flightInfoItems = ref<FlightInfoItem[][]>([])
  const getFlightInfoItems = () => {
    flightInfoItems.value = _.cloneDeep(
      flightInfoItemsMap[name.includes('Departure') ? 'departure' : 'arrival']
    )
  }
  getFlightInfoItems()

  const proxyItem = {
    label: '机场代理',
    key: 'proxy',
    getter: info => (String(info.proxy) === '1' ? '是' : '否'),
  }
  if (name.includes('International')) {
    flightInfoItems.value[0].push(proxyItem)
  }

  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, unref(UTCFlag))
    }
    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,
  }
}
