<template>
  <!--表格-->
  <div v-loading="loading" class="terminal-table" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-table ref="table" class="table" :height="computedTableHeight" :data="dealedTableData" :header-cell-class-name="headerCellClass" :row-class-name="tableRowClassName" :cell-class-name="cellClass" show-summary :summary-method="summaryMethod" border stripe fit @cell-click="cellClickHandler">
      <el-table-column v-for="col in tableColsCopy" :key="col.prop" :prop="col.prop" :label="col.label" :width="col.width" :fixed="col.fixed">
        <el-table-column v-for="childCol in col.children" :key="childCol.prop" :prop="childCol.prop" :label="childCol.label" :width="childCol.width" :formatter="tableFormat">
          <template #header>
            <el-tooltip :content="childCol.desc || childCol.label" placement="top">
              <TableHeaderCell :label="childCol.label" :filter-options="tableDataFilters[childCol.prop]" :filter-values.sync="filterValues[childCol.prop]" :sortable="childCol.sortable" :sort-rule.sync="tableDataSortRules[childCol.prop]" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import TimeZoneSelector from "@/components/TimeZoneSelector";
import terminalMixin from "./mixins/terminal";
import formMixin from "./mixins/form";
import tableColsMixin from "./mixins/tableCols";
import timeZoneMixin from "./mixins/timeZone";
import TableHeaderCell from "@/components/TableHeaderCell";
import { setTableFilters } from "@/utils/table";

export default {
  name: "DepartureTerminalView",
  components: { TimeZoneSelector, TableHeaderCell },
  mixins: [terminalMixin, formMixin, tableColsMixin, timeZoneMixin],
  data () {
    return {
      orderNum: ["0", "0", "0", "0", "0", "0"], // 默认总数
      popoverVisible: false,
      // 初始表头
      tableCols: [
        {
          prop: "flightInfo",
          label: "航班信息",
          width: 185,
          fixed: "left",
          children: [
            {
              prop: "flightNO",
              label: "航班号",
              desc: "指航班编号",
              width: 80,
              filterable: true,
              sortable: true,
            },
            {
              prop: "flightDate",
              label: "执飞日期",
              desc: "指航班计划起飞日期（不变的，机票上），不是预计起飞日期（预计起飞时间可能多个），也不是实际起飞日期（实际起飞等于最后预计）",
              width: 105,
              filterable: true,
              sortable: true,
            },
            {
              prop: "arrivalTime",
              label: "降落时间",
              desc: "根据优先级别显示时间。优先级别：1.实际降落时间，2.预计降落时间，3.计划降落时间",
              width: 150,
              filterable: true,
              sortable: true,
            },
            {
              prop: "departureAirport",
              label: "起飞航站",
              desc: "指航班执飞航段的起飞航站，以航站三字码显示",
              width: 85,
              filterable: true,
              sortable: true,
            },
            {
              prop: "arrivalTerminal",
              label: "到达航站楼",
              desc: "指航班执飞航段的目的航站的航站楼代码",
              width: 100,
              filterable: true,
              sortable: true,
            },
            {
              prop: "luggageCarousel",
              label: "行李转盘",
              desc: "指航班进港，旅客提取行李转盘的代码",
              width: 85,
              filterable: true,
              sortable: true,
            },
            {
              prop: "parkingSpace",
              label: "停机位",
              desc: "指航班的停机位代码，数据是变化的，仅显示最新信息",
              filterable: true,
              sortable: true,
            },
          ],
        },
        {
          prop: "originAirportBaggageInfo",
          label: "始飞站行李信息",
          children: [
            {
              prop: "checkIns",
              label: "值机",
              desc: "指已办理值机托运的行李数量，含取消托运的行李数量，含未激活",
            },
            {
              prop: "projectedLoad",
              label: "预计装载",
              desc: "指已办理值机托运的行李数量，不含取消托运的行李数量，不包含未激活",
            },
            {
              prop: "loadedQuantity",
              label: "已装载",
              desc: "指实际装机完成的行李数量，不包含取消托运的行李数量",
            },
          ],
        },
        {
          prop: "arrvivalBaggageInfo",
          label: "到达行李信息",
          children: [
            {
              prop: "numberOfDestinationArrivals",
              label: "到达",
              desc: "指行李到达提取转盘的行李数量，数据是变化的，仅显示最新信息",
            },
            {
              prop: "endPointNotReached",
              label: "未到达",
              desc: "指行李仍未到达提取转盘的行李数量，数据是变化的，仅显示最新信息",
            },
            {
              prop: "specialQuantity",
              label: "特殊",
              desc: "指非正常行李的数量，包括（装笼动物、机组行李、易碎行李、VIP 行李等），参考 BSM 报文.E 项",
              width: 65,
            },
            {
              prop: "numberOfClaims",
              label: "理赔",
              desc: "指航班收到旅客申请理赔的行李数量",
              width: 65,
            },
          ],
        },
        {
          prop: "uninstallInfo",
          label: "卸载状态",
          children: [
            {
              prop: "uninstalled",
              label: "已卸载",
              desc: "指卸机的行李数量，数据是变化的，仅显示最新信息",
            },
            {
              prop: "numberToBeUninstalled",
              label: "待卸载",
              desc: "指仍未卸机的行李数量，数据是变化的，仅显示最新信息",
            },
          ],
        },
        {
          prop: "terminationdBaggageInfo",
          label: "终止行李",
          children: [
            {
              prop: "terminateArrivalQuantity",
              label: "到达",
              desc: "指旅客已到达目的站的行李数量，数据是变化的，仅显示最新信息",
            },
            {
              prop: "terminateUnreachedQuantity",
              label: "未到达",
              desc: "指未到达目的站的行李数量，数据是变化的，仅显示最新信息",
            },
          ],
        },
        {
          prop: "transferBaggageInfo",
          label: "转运行李",
          children: [
            {
              prop: "quantityShipped",
              label: "已转运",
              desc: "指当前航班中转出的行李已完成转运的行李数量，数据是变化的，仅显示最新信息",
            },
            {
              prop: "undeliveredQuantity",
              label: "未转运",
              desc: "指当前航班中转出的行李未完成转运的行李数量，数据是变化的，仅显示最新信息",
            },
          ],
        },
        {
          prop: "baggageDistributionInfo",
          label: "行李分布",
          children: [
            {
              prop: "numberOfContainers",
              label: "容器",
              desc: "指当前航班使用容器装载的行李数量，数据是变化的，仅显示最新信息",
            },
            {
              prop: "numberOfBulk",
              label: "散装",
              desc: "指当前航班没有使用容器装载的行李数量，数据是变化的，仅显示最新信息",
              width: 65,
            },
          ],
        },
      ],
      tableDataSortRules: {
        flightCanceled: "ascending",
      },
      loading: false,
      AirportList: [],
      loopEvent: null,
      arrivalCount: 0,
      baggageCount: 0,
      hasSetTableScroll: false,
      table: null,
    };
  },
  computed: {
    singleDay () {
      return this.startDate === this.endDate;
    },
  },
  methods: {
    tableRowClassName ({ row, rowIndex }) {
      const classes = [];
      if (row.flightStatus === "DLY") {
        classes.push("bgl-delayed");
      }
      if (row.flightStatus === "CAN") {
        classes.push("bgl-canceled");
      }
      if (row.hasArrived) {
        classes.push("bgl-hui");
        if (rowIndex === this.arrivalCount - 1) {
          classes.push("redBorder");
        }
      }
      return classes.join(" ");
    },
    headerCellClass ({ row, column }) {
      const classes = [];
      const rule = this.tableDataSortRules[column.property];
      if (rule) {
        classes.push(rule);
      }
      return classes.join(" ");
    },
    initTableData (tableData) {
      this.arrivalCount = 0;
      this.baggageCount = 0;
      tableData.forEach((item) => {
        item["flightCanceled"] = item["flightStatus"] === "CAN" ? 1 : 0;
        if (this.hasArrived(item)) {
          this.arrivalCount++;
        }
        this.baggageCount = this.baggageCount + item.projectedLoad;
      });
      this.tableData = this._.orderBy(tableData, ["hasArrived", "arrivalTime"], ["desc", "asc"]);
      setTableFilters(this.tableData, this.tableDataFilters);
      this.toOrderNum(this.baggageCount);
      this.$nextTick(() => {
        this.setTableScroll();
      });
    },
    hasArrived (flight) {
      if (flight.arrivalTime) {
        const now = new Date();
        const arrivalTime = new Date(flight.arrivalTime);
        flight["hasArrived"] = now > arrivalTime && !flight["flightCanceled"];
      } else {
        flight["hasArrived"] = false;
      }
      return flight["hasArrived"];
    },
    setTableScroll () {
      if (!this.singleDay || this.hasSetTableScroll || this.arrivalCount === 0) {
        return;
      }
      const table = this.$refs["table"].$el;
      const scrollParent = table.querySelector(".el-table__body-wrapper");
      if (scrollParent.scrollHeight <= scrollParent.offsetHeight) {
        return;
      }
      const lastRow = table.querySelectorAll(".el-table__body tr")[this.arrivalCount - 1];
      setTimeout(() => {
        const scrollMid = lastRow.offsetTop + lastRow.offsetHeight - scrollParent.offsetHeight / 2;
        const scrollMax = scrollParent.scrollHeight - scrollParent.offsetHeight;
        if (scrollMid > 0) {
          const scrollHeight = Math.min(scrollMid, scrollMax);
          scrollParent.scrollTo(0, scrollHeight);
        }
      }, 0);
      this.hasSetTableScroll = true;
    },
  },
};
</script>

<style>
</style>