<template>
  <div class="airport-view">
    <div class="airport-header">
      <AirportForm :name="name" @form-data-change="formDataChangeHandler" />
      <div class="airport-count">
        <CountBox
          :count-number="tableDataCount.flightCount"
          label="今日计划航班数"
        />
        <CountBox
          :count-number="
            isDeparture ? finishedCount : tableDataCount.tallyCount
          "
          label="已完成航班数"
        />
        <!-- <CountBox
          :count-number="tableDataCount.weightCount"
          label="已转载重量"
        /> -->
      </div>
      <div class="airport-settings">
        <div v-permission="getPermission('count')">
          <CommonSwitch v-model:flag="countFlag" label="显示件数" />
        </div>
        <!-- <div v-permission="getPermission('UTC')">
          <CommonSwitch v-model:flag="UTCFlag" label="开启UTC" />
        </div> -->
        <div v-permission="getPermission('columnSet')">
          <ColumnSet
            :table-columns="tableColumns"
            @checked-submit="columnChecked"
          />
        </div>
      </div>
    </div>
    <div class="airport-table">
      <SimpleTable
        ref="tableRef"
        :columns="tableColumns"
        :data="tableData"
        row-key="rowKey"
        sequence
        highlight-current-row
        scrollbar-always-on
        :stripe="false"
        show-summary
        :cache-keys="cacheKeys"
        :filter-sort-options="filterSortOptions"
        :label-formatter="tableColumnFormatter"
        :row-class-name="rowClassName"
        :cell-class-name="cellClass"
        :column-props="{ formatter: tableDataFormatter }"
        @sort-rule-change="sortRuleChangeHandler"
        @cell-click="cellClickHandler"
      />
    </div>
    <!-- <div class="table-footer">
      <span class="table-footer-count"
        >货运航班总数：{{ tableDataCount.freightFlightCount }}</span
      >
      <span class="table-footer-count"
        >货站交接总数：{{ tableDataCount.depotFlightCount }}</span
      >
      <span v-if="isDeparture" class="table-footer-count"
        >已装机总数：{{ tableDataCount.loadCount }}</span
      >
      <span v-else class="table-footer-count"
        >已卸机总数：{{ tableDataCount.unloadCount }}</span
      >
    </div> -->
  </div>
</template>
<script lang="tsx" setup>
import AirportForm from './AirportForm.vue'
import ColumnSet from '@/components/ColumnSet/index.vue'
import CountBox from '../../components/CountBox/index.vue'
import CommonSwitch from '../../components/CommonSwitch/index.vue'
import SimpleTable from '@/components/SimpleTable/index.vue'
import { useTableColumnSet } from '@/hooks/useTableColumnSet'
import { useAirportTable } from './useAirportTable'
import { useTableStyle } from '../../hooks/useTableStyle'
import { useTableCellClick } from '../../hooks/useTableCellClick'
import { useFormatter } from './useFormatter'
import { CommonData } from '~/common'
import { useLoop } from '@/hooks/useLoop'
import { useTableSettingsStore } from '@/store/tableSettings'
import { useFlightState } from './useFlightState'

const props = defineProps({
  name: {
    type: String,
    required: true,
  },
})

const isDeparture = props.name.includes('Departure')

const formData: CommonData = reactive({})
const formDataChangeHandler = (data: CommonData) => {
  Object.assign(formData, data)
}

const { tableColumns, tableData, getTableData } = useAirportTable(
  props.name,
  formData
)

const finishedCount = ref(0)

const { getWarningRules } = useFlightState(props.name, tableData, finishedCount)

useLoop(
  [
    // getWarningRules,
    getTableData,
  ],
  'airport',
  [formData]
)

const countFlag = ref(false)
const { tableColumnFormatter, tableDataFormatter } = useFormatter(countFlag)

// const UTCFlag = ref(true)

/* 离港视图默认的排序方式：
 * 1.已起飞排在前
 * 2.未起飞中已装机在前
 * 3.已起飞和未起飞分类中各自按照预计起飞时间排序
 */
const defaultSortFunction = (a: CommonData, b: CommonData) => {
  const departureTimeCompare = (a: CommonData, b: CommonData) => {
    if (a.planDepartureTime) {
      if (b.planDepartureTime) {
        if (a.planDepartureTime > b.planDepartureTime) {
          return 1
        } else if (a.planDepartureTime < b.planDepartureTime) {
          return -1
        } else {
          return 0
        }
      } else {
        return -1
      }
    } else if (b.planDepartureTime) {
      return 1
    } else {
      return 0
    }
  }

  if (a.hasTakenOff === 'Y') {
    if (b.hasTakenOff === 'Y') {
      return departureTimeCompare(a, b)
    } else {
      return -1
    }
  } else if (b.hasTakenOff === 'Y') {
    return 1
  } else {
    if (a.loadPlaneSureTime) {
      if (b.loadPlaneSureTime) {
        return departureTimeCompare(a, b)
      } else {
        return -1
      }
    } else if (b.loadPlaneSureTime) {
      return 1
    } else {
      return departureTimeCompare(a, b)
    }
  }
}

const filterSortOptions = computed(() => ({
  defaultFilterValueMap,
  extraFilterValueMap: flightStateFilter,
  defaultSortRuleMap: isDeparture
    ? undefined
    : {
        planLandingTime: 'ascending',
      },
  defaultSortFunction: isDeparture ? defaultSortFunction : undefined,
}))

const sortRuleMap = ref({})
const sortRuleChangeHandler = map => {
  sortRuleMap.value = map
}

const { columnChecked } = useTableColumnSet(tableColumns)
const { rowClass, cellClass } = useTableStyle(props.name)

const rowClassName = params => {
  const { row, rowIndex } = params
  const classes: string[] = []
  if (
    (row.hasTakenOff === 'Y' || row.hasLanded === 'Y') &&
    (['planDepartureTime', 'planLandingTime'].some(
      key => sortRuleMap.value[key] === 'ascending'
    ) ||
      Object.keys(sortRuleMap.value).length === 0) &&
    finishedCount.value < tableData.value.length &&
    rowIndex === finishedCount.value - 1
  ) {
    classes.push('underline-red')
  }

  return `${rowClass(params)} ${classes.join(' ')}`
}

const tableDataCount = computed(() =>
  tableData.value.reduce(
    (counts: { [x: string]: number }, current) => {
      // const preCount = current[isDeparture ? 'preLoad' : 'preUnload']
      // if (preCount) {
      //   counts.waybillCount += Number(String(preCount).split('/')[0])
      //   counts.goodsCount += Number(String(preCount).split('/')[1])
      // }
      if (typeof current['allNumber'] === 'number') {
        counts.flightCount = current['allNumber']
      }
      if (current['depotJoinTime'] || current['depotJoinTime_IN']) {
        counts.depotFlightCount++
      }
      const isFreight = tableColumns.value.some(
        column => column.groupName === '地服相关' && current[column.columnName]
      )
      if (isFreight) {
        counts.freightFlightCount++
      }
      if (current['loadPlaneSureTime']) {
        counts.loadCount++
      }
      if (current['unLoadTime']) {
        counts.unloadCount++
      }
      if (current['tallyTime_in']) {
        counts.tallyCount++
      }
      return counts
    },
    {
      // waybillCount: 0,
      // goodsCount: 0,
      flightCount: 0,
      depotFlightCount: 0,
      freightFlightCount: 0,
      loadCount: 0,
      unloadCount: 0,
      tallyCount: 0,
      weightCount: 0,
    }
  )
)

const { cellClickHandler } = useTableCellClick(props.name)

const route = useRoute()
const { savedTableFilterValueMap } = useTableSettingsStore()
const defaultFilterValueMap = savedTableFilterValueMap[route.path]
const flightStateFilter = computed<{} | { [x: string]: string[] }>(() => {
  switch (formData.flightState) {
    case 'hasTakenOff':
      return { hasTakenOff: ['Y'] }
    case 'hasNotTakenOff':
      return { hasTakenOff: ['N'] }
    case 'hasLanded':
      return { hasLanded: ['Y'] }
    case 'hasNotLanded':
      return { hasLanded: ['N'] }
    case 'canceled':
      return { flightState: ['CAN'] }
    case 'groundService':
      return { groundService: ['Y'] }
    default:
      return {}
  }
})

const cacheKeys = ['IATACode']

const permissionMap = {
  DepartureAirport: {
    count:
      'number_of_pieces_displayed_in_domestic_departure_terminal_view_button',
    UTC: 'turn_on_utc_in_view_of_domestic_departure_terminal_button',
    columnSet: 'domestic_departure_terminal_view_column_setting_button',
  },
  InternationalDepartureAirport: {
    count:
      'number_of_pieces_displayed_in_international_departure_terminal_view_button',
    UTC: 'international_departure_terminal_view_opens_utc_button',
    columnSet: 'international_departure_terminal_view_column_setting_button',
  },
  ArrivalAirport: {
    count:
      'number_of_pieces_displayed_in_domestic_inbound_terminal_view_button',
    UTC: 'turn_on_utc_in_view_of_domestic_inbound_terminal_button',
    columnSet: 'domestic_inbound_terminal_view_column_setting_button',
  },
  InternationalArrivalAirport: {
    count:
      'number_of_display_pieces_of_international_inbound_terminal_view_button',
    UTC: 'the_view_of_international_inbound_terminal_opens_utc_button',
    columnSet: 'view_column_setting_of_international_inbound_terminal_button',
  },
}
const getPermission = (type?: string) => {
  return [permissionMap[props.name][type]]
}

const tableRef = ref<InstanceType<typeof SimpleTable> | null>(null)
const hasSetTableScroll = ref(false)
watch(
  [() => formData.startDate, () => formData.endDate],
  ([startDate, endDate], [preStartDate, preEndDate]) => {
    if (startDate !== preStartDate || endDate !== preEndDate) {
      hasSetTableScroll.value = false
    }
  }
)
watch(tableData, async () => {
  await nextTick()
  if (hasSetTableScroll.value || !finishedCount.value) {
    return
  }
  if (tableRef.value?.table) {
    tableRef.value?.table?.setScrollTop((finishedCount.value - 1) * 50)
  }
  hasSetTableScroll.value = true
})
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
