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

export function useFlightState(
  name: string,
  tableData: Ref<CommonData[]>,
  finishedCount: Ref<number>
) {
  const warningRules = ref<CommonData[]>([])
  const getWarningRules = async () => {
    try {
      const {
        code,
        returnData: { listValues },
        message,
      } = await Query<CommonData>({
        id: DATACONTENT_ID.warningRules,
        dataContent: [],
      })
      if (Number(code) !== 0) {
        throw new Error(message || '失败')
      }
      warningRules.value = listValues
    } catch (error) {
      console.error(error)
    }
  }

  watch(tableData, data => {
    finishedCount.value = 0
    const now = Date.now()
    data.forEach(row => {
      if (
        name.includes('DepartureAirport') &&
        typeof row.planDepartureTime === 'string'
      ) {
        const departureTime = new Date(
          row.planDepartureTime.replace('T', ' ')
        ).getTime()
        // 判断已起飞
        if (now >= departureTime) {
          row.hasTakenOff = 'Y'
          finishedCount.value++
        } else {
          row.hasTakenOff = 'N'

          // 未起飞的匹配预警报警策略
          row.warningState = getWarningState(row)
        }
      }
      if (
        name.includes('InternationalDeparture') &&
        !(['CA', 'ZH', 'CZ', 'O3', '5X', 'FX', 'DO'] as CommonValue[]).includes(
          row.IATACode
        )
      ) {
        row.groundService = 'Y'
      }
      if (
        name.includes('ArrivalAirport') &&
        typeof row.planLandingTime === 'string'
      ) {
        const landingTime = new Date(
          row.planLandingTime.replace('T', ' ')
        ).getTime()
        // 判断已降落
        if (now >= landingTime) {
          row.hasLanded = 'Y'
          finishedCount.value++
        } else {
          row.hasLanded = 'N'
        }
      }
    })
  })

  const getWarningState = (flightData: CommonData) => {
    let warningState = ''
    if (
      typeof flightData.planDepartureTime !== 'string' ||
      typeof flightData.loadPlaneTime !== 'string'
    ) {
      return warningState
    }

    const now = Date.now()
    const departureTime = new Date(
      flightData.planDepartureTime.replace('T', ' ')
    ).getTime()
    const loadTime = new Date(
      flightData.loadPlaneTime.replace('T', ' ')
    ).getTime()
    const duration = departureTime - loadTime

    warningRules.value.some(
      ({
        startDate,
        endDate,
        IATACode,
        flightNO,
        warningDuration,
        alarmDuration,
      }) => {
        let startTime = 0,
          endTime = 0
        if (typeof startDate === 'string') {
          startTime = new Date(startDate.replace('T', ' ')).getTime()
        }
        if (typeof endDate === 'string') {
          endTime = new Date(endDate.replace('T', ' ')).getTime()
        }
        // 排除不在生效期内或是航司、航班号不匹配的策略
        if ((startTime && startTime > now) || (endTime && endTime < now)) {
          return false
        }
        if (IATACode && IATACode !== flightData.IATACode) {
          return false
        }
        if (flightNO && flightNO !== flightData.flightNO) {
          return false
        }
        if (typeof alarmDuration === 'number' && duration < alarmDuration) {
          warningState = 'alarm'
          return true
        }
        if (typeof warningDuration === 'number' && duration < warningDuration) {
          warningState = 'warning'
          return true
        }
        return false
      }
    )

    return warningState
  }

  return {
    warningRules,
    getWarningRules,
  }
}
