<!--
 * @Author: your name
 * @Date: 2022-01-17 10:39:22
 * @LastEditTime: 2022-08-12 18:59:39
 * @LastEditors: your name
 * @Description: 航班视图
-->
<template>
  <div class="flight-view">
    <div class="flight-wrapper">
      <div class="part1">
        <div class="title">
          <span class="manageTitle">航班基本信息</span>
          <!-- <BackButton /> -->
        </div>
        <div class="part1-wrapper">
          <div class="airline">
            {{ queryData.flightNO }}
            <el-select
              v-model="selectedAirline"
              size="mini"
              class="airline-select"
            >
              <el-option
                v-for="airline in airlineList"
                :key="airline.value"
                :value="airline.value"
                :label="airline.label"
              />
            </el-select>
          </div>
          <div class="part1_info">
            <div class="part1_info_box">
              <el-row>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span>起飞机场简称：</span>
                </el-col>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span>{{ flightInfo.departureName }}</span>
                </el-col>
              </el-row>
              <!-- <el-row>
                <el-col :xs="24" :sm="24" :xl="12">
                  <span>起飞机场三字码：</span>
                </el-col>
                <el-col :xs="24" :sm="24" :xl="12">
                  <span>{{ flightInfo.planDepartureApt }}</span>
                </el-col>
              </el-row> -->
              <el-row>
                <!-- <el-col :xs="24" :sm="24" :xl="12">
                  <span>航站楼：{{ flightInfo.departureBuild }}</span>
                </el-col> -->
                <el-col :span="24">
                  <span>分拣转盘：{{ flightInfo.sortCarousel }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span> 日期：{{ flightInfo.planDepartureTime && flightInfo.planDepartureTime.split('T')[0] }} </span>
                </el-col>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span> 时间：{{ flightInfo.planDepartureTime && flightInfo.planDepartureTime.split('T')[1] }} </span>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span>登机口：{{ flightInfo.bordingGate }}</span>
                </el-col>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span>停机位：{{ flightInfo.standForDepartrue }}</span>
                </el-col>
              </el-row>
            </div>
            <i class="part1_info_arrow_right el-icon-caret-right" />
            <div class="part1_info_box">
              <!-- <el-row>
                <el-col :span="12">
                  <span>航班号：</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ flightInfo.flightNO }}</span>
                </el-col>
              </el-row> -->
              <el-row>
                <el-col
                  :xs="16"
                  :sm="16"
                  :xl="12"
                >
                  <span>航班状态：</span>
                </el-col>
                <el-col
                  :xs="8"
                  :sm="8"
                  :xl="12"
                >
                  <!-- <span>{{ flightInfo.flightStatus === null ? "正常" : flightInfo.flightStatus }}</span> -->
                  <span>{{ flightInfo.flightStateCN }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="16"
                  :sm="16"
                  :xl="12"
                >
                  <span>机号：</span>
                </el-col>
                <el-col
                  :xs="8"
                  :sm="8"
                  :xl="12"
                >
                  <span>{{ flightInfo.craftNo }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="16"
                  :sm="16"
                  :xl="12"
                >
                  <span>托运旅客数：</span>
                </el-col>
                <el-col
                  :xs="8"
                  :sm="8"
                  :xl="12"
                >
                  <span>{{ flightInfo.count1 }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="16"
                  :sm="16"
                  :xl="12"
                >
                  <span>终点行李数：</span>
                </el-col>
                <el-col
                  :xs="8"
                  :sm="8"
                  :xl="12"
                >
                  <span>{{ flightInfo.count2 }}</span>
                </el-col>
              </el-row>
              <!-- <el-row>
                <el-col :xs="18" :sm="18" :xl="12">
                  <span>中转进行李数：</span>
                </el-col>
                <el-col :xs="6" :sm="6" :xl="12">
                  <span>{{ flightInfo.count4 }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="18" :sm="18" :xl="12">
                  <span>中转出行李数：</span>
                </el-col>
                <el-col :xs="6" :sm="6" :xl="12">
                  <span>{{ flightInfo.count3 }}</span>
                </el-col>
              </el-row> -->
            </div>
            <i class="part1_info_arrow_right el-icon-caret-right" />
            <div class="part1_info_box">
              <el-row>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span>降落机场简称：</span>
                </el-col>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span>{{ flightInfo.landingName }}</span>
                </el-col>
              </el-row>
              <!-- <el-row>
                <el-col :xs="24" :sm="24" :xl="12">
                  <span>降落机场三字码：</span>
                </el-col>
                <el-col :xs="24" :sm="24" :xl="12">
                  <span>{{ flightInfo.planLandingApt }}</span>
                </el-col>
              </el-row> -->
              <!-- <el-row>
                <el-col :span="12">
                  <span>航站楼：</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ flightInfo.landingBuild }}</span>
                </el-col>
              </el-row> -->
              <el-row>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span> 日期：{{ flightInfo.expectLandingTime && flightInfo.expectLandingTime.split('T')[0] }} </span>
                </el-col>
                <el-col
                  :xs="24"
                  :sm="24"
                  :xl="12"
                >
                  <span> 时间：{{ flightInfo.expectLandingTime && flightInfo.expectLandingTime.split('T')[1] }} </span>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="16"
                  :sm="16"
                  :xl="12"
                >
                  <span>提取转盘：</span>
                </el-col>
                <el-col
                  :xs="8"
                  :sm="8"
                  :xl="12"
                >
                  <span>{{ flightInfo.carousel }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="16"
                  :sm="16"
                  :xl="12"
                >
                  <span>停机位：</span>
                </el-col>
                <el-col
                  :xs="8"
                  :sm="8"
                  :xl="12"
                >
                  <span>{{ flightInfo.standForLanding }}</span>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </div>
      <div class="part2">
        <div class="title">
          <span class="manageTitle">航班容器列表</span>
          <img
            class="btn-square btn-shadow"
            src="@/assets/baggage/ic_export.png"
            title="导出"
            @click="exportHandler('containerTable', '航班容器列表')"
          />
        </div>
        <el-table
          ref="containerTable"
          :data="containerTableData"
          border
          style="width: 100%"
          height="290px"
          stripe
          size="mini"
          show-summary
          :summary-method="summaryMethod"
          :header-cell-style="{ color: '#101116' }"
          :row-class-name="rowClass"
          :cell-class-name="cellClass"
          @cell-click="cellClickHandler"
        >
          <el-table-column
            v-for="col in containerTableColumn"
            :key="col.id"
            :prop="col.prop"
            :label="col.label"
            :width="col.width"
            :align="col.align || 'center'"
            :show-overflow-tooltip="true"
          />
        </el-table>
      </div>
      <!-- <div
        class="part3"
        style="padding-right: 4px"
      >
        <div class="title">中转进</div>
        <el-table
          ref="transferInBaggageTable"
          :data="transferInBaggageTableData"
          border
          style="width: 100%"
          height="162"
          stripe
          size="mini"
          show-summary
          :summary-method="summaryMethod"
          :header-cell-style="{ color: '#101116' }"
          :cell-class-name="cellClass"
          @cell-click="cellClickHandler"
        >
          <el-table-column
            v-for="col in transferInTableColumn"
            :key="col.id"
            :prop="col.prop"
            :label="col.label"
            :align="col.align || 'center'"
            :show-overflow-tooltip="true"
          />
        </el-table>
      </div>
      <div
        class="part3"
        style="padding-left: 4px"
      >
        <div class="title">中转出</div>
        <el-table
          ref="transferOutBaggageTable"
          :data="transferOutBaggageTableData"
          border
          style="width: 100%"
          height="162"
          stripe
          size="mini"
          show-summary
          :summary-method="summaryMethod"
          :header-cell-style="{ color: '#101116' }"
          :cell-class-name="cellClass"
          @cell-click="cellClickHandler"
        >
          <el-table-column
            v-for="col in transferOutTableColumn"
            :key="col.id"
            :prop="col.prop"
            :label="col.label"
            :align="col.align || 'center'"
            :show-overflow-tooltip="true"
          />
        </el-table>
      </div> -->
      <div
        class="drag-mask"
        :class="{ active: dragActive }"
      />
      <div
        class="part4"
        :style="draggableStyle"
      >
        <div
          ref="dragBox"
          class="drag-box"
          :class="{ active: dragActive }"
        >
          <i class="drag-icon el-icon-d-caret" />
          <div
            class="drag-line"
            :style="dragLineStyle"
          />
        </div>
        <div class="title">
          <span class="manageTitle">航班行李列表</span>
          <div class="filter-select">
            <span class="label">快捷筛选</span>
            <!-- <el-select
              v-model="selectedFilter"
              size="mini"
              placeholder="无"
              clearable
            >
              <el-option
                v-for="option in filterSelectOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </el-select> -->
            <el-cascader
              v-model="selectedFilter"
              :options="filterSelectOptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true }"
              size="mini"
              placeholder="无"
              clearable
            />
          </div>
          <TimeZoneSelector />
          <img
            class="btn-square btn-shadow"
            src="@/assets/baggage/ic_export.png"
            title="导出"
            @click="exportHandler('flightBaggageTable', '航班行李列表')"
          />
          <img
            class="btn-square btn-shadow"
            src="@/assets/baggage/ic_setting.png"
            title="列设置"
            @click="show"
          />
        </div>
        <el-table
          ref="flightBaggageTable"
          :data="dealedTableData"
          border
          style="width: 100%"
          height="calc(100% - 64px)"
          stripe
          size="mini"
          show-summary
          :summary-method="summaryRow(dealedTableData.length)"
          :header-cell-class-name="headerCellClass"
          :header-cell-style="{ color: '#101116' }"
          :row-class-name="rowClass"
          :cell-class-name="cellClass"
          @cell-click="cellClickHandler"
        >
          <el-table-column
            v-for="col in tableColsCopy"
            :key="col.index"
            :prop="col.prop"
            :label="col.label"
            :align="col.align || 'center'"
            :width="col.width"
            :fixed="col.fixed"
            :formatter="tableFormat"
          >
            <template #header>
              <TableHeaderCell
                :label="col.label"
                :filter-options="flightBaggageTableFilters[col.prop]"
                :filter-values.sync="filterValues[col.prop]"
                :sortable="col.sortable"
                :sort-rule.sync="tableDataSortRules[col.prop]"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--列设置-->
    <Dialog
      :flag="dialogFlag"
      class="dialog-check-group"
    >
      <div class="dialog-wrapper">
        <div class="title">列设置</div>
        <div class="content">
          <el-tree
            ref="columnSetTree"
            :data="tableCols"
            :class="colsCheckClass"
            show-checkbox
            node-key="index"
            :default-expand-all="true"
            :props="{
              label: 'label',
              children: 'children'
            }"
            :default-checked-keys="checkedKeysTemp"
            @check="handleCheck"
          />
        </div>
        <div class="foot right t30">
          <el-button
            size="medium"
            class="r24"
            type="primary"
            @click="onCheck('flightBaggageTableData')"
            >确定</el-button
          >
          <el-button
            size="medium"
            @click="hide"
            >取消</el-button
          >
        </div>
      </div>
    </Dialog>
  </div>
</template>
<script>
// import BackButton from '@/components/BackButton'
import Dialog from '@/layout/components/Dialog/index.vue'
import TimeZoneSelector from '@/components/TimeZoneSelector'
import { myQuery } from '@/api/temp'
import tableColsMixin from '../../mixins/tableCols'
import timeZoneMixin from '../../mixins/timeZone'
import TableHeaderCell from '@/components/TableHeaderCell'
import { setTableFilters } from '@/utils/table'
import { mapGetters } from 'vuex'
import { throttledExportToExcel } from '@/utils/table'

export default {
  name: 'FlightView',
  components: {
    Dialog,
    TimeZoneSelector,
    TableHeaderCell
  },
  mixins: [tableColsMixin, timeZoneMixin],
  data() {
    return {
      loading: false,
      airlineList: [],
      selectedAirline: '',
      queryData: {},
      flightInfo: {},
      warningRules: [],
      debounceTime: 300,
      containerTableColumn: [
        { label: '容器编号', prop: 'containerNumber', width: 100 },
        { label: '类型', prop: 'style' },
        { label: '行李数', prop: 'numberOfBags' },
        { label: '舱位', prop: 'containerSpace' }
      ],
      // transferInTableColumn: [
      //   { label: '航班号', prop: 'preFlightNO' },
      //   { label: '日期', prop: 'preFlightDate' },
      //   { label: '时间', prop: 'flightTime' },
      //   { label: '始发站', prop: 'planDepartureApt' },
      //   { label: '航班状态', prop: 'flightStatus' },
      //   { label: '中转数', prop: 'totalNumber' }
      // ],
      // transferOutTableColumn: [
      //   { label: '航班号', prop: 'transferFlightNO' },
      //   { label: '日期', prop: 'transferFlightDate' },
      //   { label: '时间', prop: 'flightTime' },
      //   { label: '始发站', prop: 'planDepartureApt' },
      //   { label: '目的站', prop: 'planLandingApt' },
      //   { label: '中转数', prop: 'transferNumber' }
      // ],
      tableCols: [
        {
          label: '旅客姓名',
          prop: 'PassengerNameUpcase',
          width: 140,
          fixed: 'left',
          filterable: true,
          sortable: true
        },
        {
          label: '行李牌号',
          prop: 'BagSN',
          width: 120,
          fixed: 'left',
          filterable: true,
          sortable: true
        },
        {
          label: '特殊行李类型',
          prop: 'SpecialType',
          width: 120,
          filterable: true,
          sortable: true
        },
        {
          label: '容器编号',
          prop: 'U_Device_ID',
          width: 120,
          filterable: true,
          sortable: true
        },
        { label: '装载序号', prop: 'LoadSN' },
        { label: '值机', prop: 'checkInTime', width: 140 },
        {
          label: '状态',
          prop: 'latestStatus',
          filterable: true,
          sortable: true
        },
        { label: '安检', prop: 'securityTime', width: 140 },
        { label: '分拣', prop: 'sortTime', width: 140 },
        { label: '装车', prop: 'loadTime', width: 140 },
        { label: '装机', prop: 'inflTime', width: 140 },
        {
          label: '中转进航班',
          prop: 'inFlightNO',
          filterable: true,
          sortable: true,
          width: 105
        },
        {
          label: '中转出航班',
          prop: 'transferFlightNO',
          filterable: true,
          sortable: true,
          width: 105
        },
        {
          label: '卷宗号',
          prop: 'fileNumber',
          filterable: true,
          sortable: true,
          width: 100
        }
      ],
      containerTableData: [], // 容器统计
      transferInBaggageTableData: [], // 中转进
      transferOutBaggageTableData: [], // 中转出
      flightBaggageTableData: [], // 行李列表
      flightBaggageTableFilters: {},
      filterValues: {},
      tableDataSortRules: {},
      warningContainers: [],
      dragHeight: 0,
      dragY: 0,
      dragActive: false,
      filterSelectOptions: [
        {
          label: '值机',
          value: 'checkInTime'
        },
        {
          label: '未激活',
          value: 'unActive' // STATUS为'I'
        },
        {
          label: '预计装载',
          value: 'preLoad' // STATUS不为'I'，isDEL不为'del'
        },
        {
          label: '已装载',
          value: 'loaded' // 'loadTime'不为空，isDEL不为'DEL'
        },
        {
          label: '安检',
          value: 'securityTime'
        },
        {
          label: '分拣',
          value: 'sortTime'
        },
        {
          label: '装车',
          value: 'loadTime'
        },
        {
          label: '装机',
          value: 'inflTime'
        },
        {
          label: '到达',
          value: 'arrivedID' // 1/0
        },
        {
          label: '卸载',
          value: 'unloadID' // 1/0
        },
        {
          label: '终点到达',
          value: 'destination' // 'arrivedID'为1，transferFlightNO为null
        },
        {
          label: '容器',
          value: 'inContainer' // 有容器ID
        },
        {
          label: '散装',
          value: 'FBULK' // 容器ID为'FBULK'
        },
        {
          label: '待翻减',
          value: 'toUnload' // 装车或装机后，isDEL为'DEL'，waitOFF为1
        },
        {
          label: '已翻减',
          value: 'unloaded' // 装车或装机后，isDEL为'DEL'，waitOFF为0
        },
        {
          label: '取消托运',
          value: 'canceled' // isDEL为'DEL'
        },
        {
          label: '无BSM',
          value: 'NOBSM' // 1/0
        },
        {
          label: '预警',
          value: 'warning'
        },
        {
          label: '报警',
          value: 'alarm'
        },
        {
          label: '中转进航班',
          value: 'inFlightNO',
          children: []
        },
        {
          label: '中转出航班',
          value: 'transferFlightNO',
          children: []
        }
      ],
      selectedFilter: []
    }
  },
  computed: {
    ...mapGetters(['clickedCells', 'savedTableFilterValuesMap']),
    fasterFilteredTableData() {
      const [key, value] = this.selectedFilter
      if (!key) {
        return this.flightBaggageTableData
      }
      const that = this
      function isWarning(row) {
        if (row['STATUS'] === 'I' || row['loadTime'] || row['isDEL'] === 'DEL') {
          return 0
        }
        const planDepartureTime = that.flightInfo.planDepartureTime
        if (!planDepartureTime) {
          return 0
        }
        const currentTime = new Date().getTime()
        const departureTime = new Date(planDepartureTime.replace('T', ' ')).getTime()
        if (currentTime > departureTime) {
          return 0
        }

        let flag = 0
        const duration = departureTime - currentTime
        that.warningRules.some(rule => {
          if (!rule.startDate || !rule.endDate) {
            return false
          }
          const ruleStartTime = new Date(rule.startDate).getTime()
          const ruleEndTime = new Date(rule.endDate).getTime()
          if (currentTime < ruleStartTime || currentTime > ruleEndTime) {
            return false
          }
          if (rule.alarmDuration && duration < rule.alarmDuration * 60 * 1000) {
            flag = 1
            return true
          } else if (rule.warningDuration && duration < rule.warningDuration * 60 * 1000) {
            flag = 2
            return true
          } else {
            return false
          }
        })
        return flag
      }
      return this.flightBaggageTableData.filter(row => {
        switch (key) {
          case 'arrivedID':
          case 'unloadID':
          case 'NOBSM':
            return row[key] === 1
          case 'unActive':
            return row['STATUS'] === 'I'
          case 'preLoad':
            return row['STATUS'] !== 'I' && row['isDEL'] !== 'DEL'
          case 'loaded':
            return row['loadTime'] && row['isDEL'] !== 'DEL'
          case 'destination':
            return row['arrivedID'] === 1 && !row['transferFlightNO']
          case 'inContainer':
            return row['U_Device_ID'] && row['U_Device_ID'] !== 'FBULK'
          case 'FBULK':
            return row['U_Device_ID'] === 'FBULK'
          case 'toUnload':
            return (row['loadTime'] || row['inflTime']) && row['isDEL'] === 'DEL' && row['waitOFF'] === 1
          case 'unloaded':
            return (row['loadTime'] || row['inflTime']) && row['isDEL'] === 'DEL' && row['waitOFF'] !== 1
          case 'canceled':
            return row['isDEL'] === 'DEL'
          case 'inFlightNO':
          case 'transferFlightNO':
            return value ? row[key] === value : (row[key] ?? '') !== ''
          case 'warning':
            return isWarning(row) === 2
          case 'alarm':
            return isWarning(row) === 1
          default:
            return (row[key] ?? '') !== ''
        }
      })
    },
    dealedTableData() {
      const filtered = this.fasterFilteredTableData.filter(item => {
        let flag = true
        Object.entries(this.filterValues).forEach(([key, arr]) => {
          if (arr.length && !arr.includes(String(item[key]))) {
            flag = false
          }
        })
        return flag
      })
      const sortRules = Object.entries(this.tableDataSortRules).reduce(
        (pre, [key, value]) => {
          if (value) {
            pre[0].push(key)
            value = value === 'ascending' ? 'asc' : 'desc'
            pre[1].push(value)
          }
          return pre
        },
        [[], []]
      )
      return this._.orderBy(filtered, sortRules[0], sortRules[1])
    },
    draggableStyle() {
      return {
        height: `calc(100vh - 80px - 64px - 16px - 290px + ${this.dragHeight}px)`
      }
    },
    dragLineStyle() {
      return {
        transform: `translateY(${this.dragHeight - this.dragY}px)`
      }
    }
  },
  watch: {
    loading(val) {
      if (val) {
        this.fullscreenLoading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      } else {
        this.fullscreenLoading?.close()
      }
    },
    selectedAirline(val) {
      if (!val) {
        return
      }
      const { flightNO, flightDate } = this.queryData
      const [departureAirport, landingAirport] = val.split('-')
      this.queryAll([flightNO, flightDate, departureAirport, landingAirport])
    },
    selectedFilter(val) {
      const { path, query } = this.$route
      const newQuery = { ...query }
      delete newQuery.fastFilter
      if (val.length) {
        newQuery.fastFilter = val.join(',')
      }
      this.$router.replace({
        path,
        query: newQuery
      })
    },
    filterValues: {
      handler(val) {
        this.$store.dispatch('savedSettings/saveTableFilterValues', {
          filterValues: val,
          tableName: 'flightBaggage'
        })
      },
      deep: true
    }
  },
  created() {
    const { flightNO, flightDate, departureAirport, landingAirport } = this.$route.query
    if (flightNO && flightDate) {
      this.queryAirline([flightNO, flightDate])
      this.queryData = {
        flightNO,
        flightDate,
        departureAirport,
        landingAirport
      }
    } else {
      this.$router.push('/')
    }
    const filterValues = this.savedTableFilterValuesMap[this.$route.name + '/flightBaggage']
    Object.values(this.tableCols).forEach(({ prop, filterable, sortable }) => {
      if (filterable) {
        this.$set(this.flightBaggageTableFilters, prop, [])
        this.$set(this.filterValues, prop, filterValues?.[prop] ?? [])
      }
      if (sortable) {
        this.$set(this.tableDataSortRules, prop, '')
      }
    })
  },
  mounted() {
    this.setDragBox()
  },
  updated() {
    this.resizeHandler()
  },
  activated() {
    const { fastFilter } = this.$route.query
    this.selectedFilter = fastFilter ? fastFilter.split(',') : []
    this.getWarningData()
    this.resizeHandler()
    this.debouncedResizeHandler = this._.debounce(this.resizeHandler, this.debounceTime)
    window.addEventListener('resize', this.debouncedResizeHandler)
  },
  deactivated() {
    this.fullscreenLoading?.close()
    window.removeEventListener('resize', this.debouncedResizeHandler)
  },
  methods: {
    setDragBox() {
      const dragBox = this.$refs['dragBox']
      const offsetTop = dragBox.offsetParent.offsetTop
      const that = this
      let mousedownY
      let dragY
      let dragHeight
      function mousemoveHandler(e) {
        e.stopPropagation()
        e.preventDefault()
        dragY = dragHeight + mousedownY - e.screenY
        dragY = dragY < 0 ? 0 : dragY > offsetTop ? offsetTop : dragY
        that.dragY = dragY
      }
      function mouseupHandler(e) {
        e.stopPropagation()
        e.preventDefault()
        that.dragHeight = that.dragY
        that.dragY = 0
        that.dragActive = false
        document.removeEventListener('mousemove', mousemoveHandler)
        document.removeEventListener('mouseup', mouseupHandler)
      }
      dragBox.addEventListener('mousedown', e => {
        that.dragActive = true
        mousedownY = e.screenY
        dragHeight = that.dragHeight
        that.dragY = dragHeight
        document.addEventListener('mousemove', mousemoveHandler)
        document.addEventListener('mouseup', mouseupHandler)
      })
    },
    resizeHandler() {
      this.$refs['containerTable']?.doLayout()
      // this.$refs['transferInBaggageTable']?.doLayout()
      // this.$refs['transferOutBaggageTable']?.doLayout()
      this.$refs['flightBaggageTable']?.doLayout()
    },
    setfastFilterValues() {
      const inFlightNOList = new Set()
      const transferFlightNOList = new Set()
      this.flightBaggageTableData.forEach(item => {
        item['inFlightNO'] && inFlightNOList.add(item['inFlightNO'])
        item['transferFlightNO'] && transferFlightNOList.add(item['transferFlightNO'])
      })
      this.filterSelectOptions.splice(
        this.filterSelectOptions.length - 2,
        2,
        {
          label: '中转进航班',
          value: 'inFlightNO',
          children: [...inFlightNOList].map(value => ({
            label: value,
            value
          }))
        },
        {
          label: '中转出航班',
          value: 'transferFlightNO',
          children: [...transferFlightNOList].map(value => ({
            label: value,
            value
          }))
        }
      )
    },
    rowClass({ row, rowIndex }) {
      const classes = []
      if (
        this.warningContainers.includes(row['containerNumber']) ||
        ((row['loadTime'] || row['inflTime']) && row['isDEL'] === 'DEL' && row['waitOFF'] === 1)
      ) {
        classes.push('row-warning')
      }
      if (row['Status'] === 'DEL') {
        classes.push('bgl-deleted')
      }
      return classes.join(' ')
    },
    // 给表头单元格加上 ascending 或 descending 使用 element 自带的排序箭头变色
    headerCellClass({ row, column, rowIndex, columnIndex }) {
      const classes = []
      const rule = this.tableDataSortRules[column.property]
      if (rule) {
        classes.push(rule)
      }
      return classes.join(' ')
    },
    cellClass({ row, column, rowIndex, columnIndex }) {
      const classes = []
      if (
        ['checkInTime', 'DealInfo', 'sortLocationMark', 'loadLocationMark', 'inflLocationMark'].includes(
          column.property
        )
      ) {
        classes.push('pre-line')
      }
      if (
        [
          'containerNumber',
          'preFlightNO',
          // 'totalNumber',
          'inFlightNO',
          'transferFlightNO',
          // 'transferNumber',
          // 'PassengerNameUpcase',
          'BagSN',
          'U_Device_ID',
          'fileNumber'
        ].includes(column.property) &&
        row[column.property] &&
        row[column.property] !== 'FBULK'
      ) {
        classes.push('cell-click')
        if (
          this.clickedCells.some(
            cell =>
              cell.pageName === this.$route.name &&
              Object.entries(cell.row).every(([key, value]) => row[key] === value) &&
              cell.columnProp === column.property
          )
        ) {
          classes.push('cell-clicked')
        }
      }
      return classes.join(' ')
    },
    cellClickHandler(row, column, cell, event) {
      if (
        [
          'containerNumber',
          'preFlightNO',
          // 'totalNumber',
          'inFlightNO',
          'transferFlightNO',
          // 'transferNumber',
          // 'PassengerNameUpcase',
          'BagSN',
          'U_Device_ID',
          'fileNumber'
        ].includes(column.property) &&
        row[column.property] &&
        row[column.property] !== 'FBULK'
      ) {
        this.$store.dispatch('keepAlive/addClickedCell', {
          row,
          columnProp: column.property,
          pageName: this.$route.name
        })
        switch (column.property) {
          case 'containerNumber': {
            const [departureAirport, landingAirport] = this.selectedAirline.split('-')
            this.$router.push({
              path: `${this.$route.path.split('/').slice(0, -1).join('/')}/containerView`,
              query: {
                flightNO: this.queryData.flightNO,
                flightDate: this.queryData.flightDate,
                departureAirport,
                landingAirport,
                containerID: row.containerNumber,
                containerType: row.style,
                containerSpace: row.containerSpace
              }
            })
            break
          }
          case 'preFlightNO':
            this.$router.push({
              path: `${this.$route.path.split('/').slice(0, -1).join('/')}/flightView`,
              query: {
                flightNO: row.preFlightNO,
                flightDate: row.preFlightDate
              }
            })
            break
          // case 'totalNumber':
          //   this.$router.push({
          //     path: '/advance',
          //     query: {
          //       flightNO: this.queryData.flightNO,
          //       startDate: this.queryData.flightDate,
          //       endDate: this.queryData.flightDate,
          //       transferArrival: row.preFlightNO
          //     }
          //   })
          //   break
          case 'inFlightNO':
            this.$router.push({
              path: `${this.$route.path.split('/').slice(0, -1).join('/')}/flightView`,
              query: {
                flightNO: row.inFlightNO,
                flightDate: row.inFlightDate
              }
            })
            break
          case 'transferFlightNO':
            this.$router.push({
              path: `${this.$route.path.split('/').slice(0, -1).join('/')}/flightView`,
              query: {
                flightNO: row.transferFlightNO,
                flightDate: row.transferFlightDate
              }
            })
            break
          // case 'transferNumber':
          //   this.$router.push({
          //     path: '/advance',
          //     query: {
          //       flightNO: this.queryData.flightNO,
          //       startDate: this.queryData.flightDate,
          //       endDate: this.queryData.flightDate,
          //       transferDeparture: row.transferFlightNO
          //     }
          //   })
          //   break
          // case 'PassengerNameUpcase':
          //   this.$store.dispatch('app/setPassengerQueryParams', {
          //     flightNO: this.queryData.flightNO,
          //     flightDate: this.queryData.flightDate,
          //     passengerName: row.PassengerNameUpcase
          //   })
          //   this.$store.dispatch('app/togglePassengerDialogFlag', true)
          //   break
          case 'BagSN':
            this.$router.push({
              path: `${this.$route.path.split('/').slice(0, -1).join('/')}/baggageView`,
              query: {
                bagSN: row.BagSN,
                flightNO: this.queryData.flightNO,
                flightDate: this.queryData.flightDate
              }
            })
            break
          case 'U_Device_ID': {
            const [departureAirport, landingAirport] = this.selectedAirline.split('-')
            const container = this.containerTableData.find(({ containerNumber }) => containerNumber === row.U_Device_ID)
            this.$router.push({
              path: `${this.$route.path.split('/').slice(0, -1).join('/')}/containerView`,
              query: {
                flightNO: this.queryData.flightNO,
                flightDate: this.queryData.flightDate,
                departureAirport,
                landingAirport,
                containerID: row.U_Device_ID,
                containerType: container.style,
                containerSpace: container.containerSpace
              }
            })
            break
          }
          case 'fileNumber':
            this.$store.dispatch('app/setAbnormalBaggageQueryParams', {
              flightNO: this.queryData.flightNO,
              flightDate: this.queryData.flightDate,
              bagSN: row.BagSN,
              fileNumber: row.fileNumber
            })
            this.$store.dispatch('app/toggleAbnormalBaggageDialogFlag', true)
            break
          default:
            break
        }
      }
    },
    // 合计行
    summaryMethod({ columns, data }) {
      const sums = []
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
          } else if (
            // 需要计算的列
            [
              'numberOfBags'
              // 'totalNumber',
              // 'transferNumber'
            ].includes(column.property)
          ) {
            const values = data.map(item => Number(item[column.property]))
            if (values.some(value => !isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return Number(prev) + Number(curr)
                } else {
                  return Number(prev)
                }
              }, 0)
            } else {
              sums[index] = 0
            }
          } else {
            // 过滤某些字段不参与计算
            sums[index] = '-'
          }
        })
      }
      return sums
    },
    // 统计行数
    summaryRow(num) {
      return function () {
        return ['合计', `共${num}件`]
      }
    },
    exportHandler(refName, tableName) {
      const table = this.$refs[refName].$el.cloneNode(true)
      const fileName = `${tableName}-${this.queryData.flightNO}-${this.queryData.flightDate}.xlsx`
      throttledExportToExcel(table, tableName, fileName)
    },
    queryflightInfo(dataContent) {
      return myQuery(SERVICE_ID.flightInfo, ...dataContent)
    },
    queryContainer(dataContent) {
      return myQuery(SERVICE_ID.flightContainer, ...dataContent)
    },
    queryBaggageByFlightNO(dataContent) {
      return myQuery(SERVICE_ID.flightBaggage, ...dataContent)
    },
    async queryAirline(dataContent) {
      try {
        this.selectedAirline = ''
        this.flightInfo = {}
        this.containerTableData = []
        this.flightBaggageTableData = []
        const listValues = await myQuery(SERVICE_ID.flightAirline, ...dataContent)
        this.airlineList = listValues.map(({ departureAirport, landingAirport, departureBuild, landingBuild }) => ({
          label: `${departureAirport}${departureBuild ? `(${departureBuild})` : ''}-${landingAirport}${
            landingBuild ? `(${landingBuild})` : ''
          }`,
          value: `${departureAirport}-${landingAirport}`
        }))
        if (this.airlineList.length) {
          let currentIndex = this.airlineList.findIndex(
            ({ value }) => value === `${this.queryData.departureAirport}-${this.queryData.landingAirport}`
          )
          currentIndex = currentIndex > -1 ? currentIndex : 0
          this.selectedAirline = this.airlineList[currentIndex].value
        } else {
          this.$message.info('未查询到航班数据')
        }
      } catch (error) {
        this.$message.error('失败')
      }
    },
    async queryAll(dataContent) {
      this.loading = true
      this.flightInfo = {}
      try {
        const [flightInfo, containerTableDataData, flightBaggageTableData] = await Promise.all([
          this.queryflightInfo(dataContent),
          this.queryContainer(dataContent),
          this.queryBaggageByFlightNO(dataContent)
        ])
        if (flightInfo.length) {
          this.flightInfo = flightInfo[0]
        } else {
          this.$message.info('未查询到航班基础数据')
        }
        this.containerTableData = containerTableDataData
        this.warningContainers = []
        this.flightBaggageTableData = flightBaggageTableData.map(item => {
          if ((item['loadTime'] || item['inflTime']) && item['isDEL'] === 'DEL' && item['waitOFF'] === 1) {
            this.warningContainers.push(item['U_Device_ID'])
          }
          return item
        })
        setTableFilters(this.flightBaggageTableData, this.flightBaggageTableFilters)
        this.setfastFilterValues()
      } catch (error) {
        this.$message.error('失败')
      }
      this.loading = false
    },
    async getWarningData() {
      try {
        const listValues = await myQuery(SERVICE_ID.departureWarningId)
        this.warningRules = listValues
      } catch (error) {
        this.$message.error('失败')
      }
    }
  }
}
</script>

<style
  lang="scss"
  scoped
>
.flight-view {
  padding: 0 0 16px 8px;
  overflow: hidden;
  background: #dfe3ea;
  .flight-wrapper {
    padding-right: 8px;
    width: 100%;
    height: calc(100vh - 80px - 16px);
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-content: flex-start;
    flex-wrap: wrap;
    position: relative;
    .title {
      padding: 16px 0;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      background: #dfe3ea;
      .manageTitle {
        flex: 1;
        height: 32px;
        margin-right: 0;
      }
      .btn-square {
        margin-left: 20px;
        &:last-child {
          margin-right: 30px;
        }
      }
    }
    .part1 {
      width: 71.15%;
      .title {
        justify-content: flex-start;
        .manageTitle {
          flex: 0 1 auto;
        }
      }
      .part1-wrapper {
        height: 290px;
        background: #041741;
        padding: 24px;
        .airline {
          font-size: 18px;
          font-weight: bold;
          color: #ffffff;
          ::v-deep .airline-select {
            .el-input__inner {
              width: 200px;
              background-color: transparent;
              font-size: 18px;
              font-weight: bold;
              color: #ffffff;
            }
            .el-select__caret {
              color: #ffffff;
            }
          }
        }
        .part1_info {
          width: 100%;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          padding-top: 24px;

          .part1_info_box {
            width: calc(33.333% - 48px);
            height: 190px;
            background: #2c416d;
            padding: 24px 2% 12px;
            display: flex;
            flex-direction: column;
            align-content: space-around;
            overflow-x: hidden;
            overflow-y: auto;
            .el-row {
              margin-bottom: 24px;
              &:last-child {
                margin: 0;
              }
              @media only screen and (max-width: 1919px) {
                .el-col-sm-24:nth-child(2) {
                  margin-top: 24px;
                }
              }
            }
            span {
              display: inline-block;
              font-size: 16px;
              font-weight: 400;
              color: #ffffff;
            }
          }
          .part1_info_arrow_right {
            font-size: 32px;
            color: #ffffff;
          }
        }
      }
    }
    .part2 {
      width: calc(100% - 71.15%);
      padding-left: 16px;
      .title .btn-square:last-child {
        margin-right: 22px;
      }
    }
    .part4 {
      width: 100%;
      position: absolute;
      z-index: 100;
      bottom: 0;
      .drag-box {
        position: absolute;
        top: 0;
        width: 100%;
        height: 62px;
        z-index: 101;
        // cursor: row-resize;
        .drag-icon {
          width: 60px;
          height: 60px;
          line-height: 60px;
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          margin: auto;
          font-size: 20px;
          text-align: center;
          // background: #385086;
          color: #ffffff;
          // &:nth-child(1) {
          //   top: 0;
          //   border-radius: 0 0 8px 8px;
          // }
          // &:nth-child(2) {
          //   bottom: 0;
          //   border-radius: 8px 8px 0 0;
          // }
        }
        &:hover,
        &.active {
          .drag-icon {
            color: #2d67e3;
          }
        }
        .drag-line {
          display: none;
          width: 100%;
          height: 0;
          border-top: 1px dashed #000000;
          position: absolute;
          top: 0;
          z-index: 101;
        }
        &.active .drag-line {
          display: block;
        }
      }
      .title {
        .manageTitle {
          flex: 0 1 auto;
        }
        ::v-deep .filter-select {
          margin-left: 24px;
          flex: 1;
          height: 32px;
          display: flex;
          align-items: center;
          .label,
          .el-input__inner {
            font-family: Helvetica, 'Microsoft YaHei';
          }
          .label {
            padding-right: 14px;
          }
          .el-cascader {
            z-index: 102;
          }
        }
        .el-dropdown {
          height: 30px;
          z-index: 102;
        }
        .btn-square {
          z-index: 102;
          &:last-child {
            margin-right: 30px;
          }
        }
      }
    }
    .drag-mask {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      z-index: 99;
      display: none;
      &.active {
        display: block;
      }
    }
  }
  ::v-deep .el-table {
    .cell-click {
      cursor: pointer;
      color: #2d7cff;
      &.cell-clicked {
        color: purple;
      }
    }
    .el-table__body-wrapper,
    .el-table__fixed-body-wrapper {
      tr.bgl-deleted {
        background: #d2d6df;
        td {
          background: #d2d6df;
          font-style: italic;
        }
      }
      .row-warning .el-table__cell {
        background: lightcoral;
      }
    }
  }
}
</style>
