<!--
 * @Author: your name
 * @Date: 2022-01-17 10:39:22
 * @LastEditTime: 2022-05-26 09:56:00
 * @LastEditors: your name
 * @Description: 航班视图
-->
<template>
  <div class="flight-view">
    <div class="flight-wrap">
      <div class="part1">
        <div class="title">
          {{ flightInfo.PlanDepartureApt }} - {{ flightInfo.FlightNO }} -
          {{ flightInfo.PlanLandingApt }}
        </div>
        <div class="part1_info">
          <div class="part1_info_box">
            <el-row>
              <el-col :span="12">
                <span>起飞机场简称：</span>
              </el-col>
              <el-col :span="12">
                <span>{{ flightInfo.departureName }}</span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>起飞机场三字码：</span>
              </el-col>
              <el-col :span="12">
                <span>{{ flightInfo.PlanDepartureApt }}</span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>起飞机场航站楼：</span>
              </el-col>
              <el-col :span="12">
                <span>{{ flightInfo.DepartureBuild }}</span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>
                  日期：
                  {{ flightInfo.PlanDepartureTime && flightInfo.PlanDepartureTime.split("T")[0] }}
                </span>
              </el-col>
              <el-col :span="12">
                <span>
                  时间：
                  {{ flightInfo.PlanDepartureTime && flightInfo.PlanDepartureTime.split("T")[1] }}
                </span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>登机口：{{ flightInfo.BordingGate }}</span>
              </el-col>
              <el-col :span="12">
                <span>停机位：{{ flightInfo.StandForDepartrue }}</span>
              </el-col>
            </el-row>
          </div>
          <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 :span="12">
                <span>航班状态：</span>
              </el-col>
              <el-col :span="12">
                <span>{{ flightInfo.FlightStatus === null ? '正常' : flightInfo.FlightStatus }}</span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>托运旅客数：</span>
              </el-col>
              <el-col :span="12">
                <span>{{ flightInfo.count1 }}</span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>终点行李数：</span>
              </el-col>
              <el-col :span="12">
                <span>{{ flightInfo.count2 }}</span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>中转进行李数：</span><span>{{ flightInfo.count4 }}</span>
              </el-col>
              <el-col :span="12">
                <span>中转出行李数：</span><span>{{ flightInfo.count3 }}</span>
              </el-col>
            </el-row>
          </div>
          <div class="part1_info_box">
            <el-row>
              <el-col :span="12">
                <span>降落机场简称：</span>
              </el-col>
              <el-col :span="12">
                <span>{{ flightInfo.landingName }}</span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>降落机场三字码：</span>
              </el-col>
              <el-col :span="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 :span="12">
                <span>
                  日期：
                  {{ flightInfo.ExpectLandingTime && flightInfo.ExpectLandingTime.split("T")[0] }}
                </span>
              </el-col>
              <el-col :span="12">
                <span>
                  时间：
                  {{ flightInfo.ExpectLandingTime && flightInfo.ExpectLandingTime.split("T")[1] }}
                </span>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <span>提取转盘：{{ flightInfo.Carousel }}</span>
              </el-col>
              <el-col :span="12">
                <span>停机位：{{ flightInfo.StandForLanding }}</span>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
      <div class="part2">
        <el-table
          ref="containerTable"
          :data="containerTableData"
          border
          style="width: 100%"
          height="344px"
          stripe
          size="mini"
          show-summary
          :summary-method="summaryMethod"
          :header-cell-style="{ color: '#101116' }"
          @row-click="containeClick"
        >
          <el-table-column
            v-for="col in containerTableColumn"
            :key="col.id"
            :prop="col.prop"
            :label="col.name"
            :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.name"
            :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.name"
            :align="col.align || 'center'"
            :show-overflow-tooltip="true"
          />
        </el-table>
      </div>
      <div class="part4">
        <div class="title">
          <!-- <el-cascader
            placeholder="全部行李"
            :options="options"
            :props="props"
            collapse-tags
            size="mini"
            clearable
          /> -->
          <!-- <div class="search">
            <el-input
              v-model="keyWords"
              placeholder="请输入需要搜索姓名或行李编号"
              size="mini"
              style="width: 280px"
            />
            <el-button
              class="searchBtn"
              type="primary"
              size="mini"
            >搜索</el-button>
          </div> -->
          <TimeZoneSelector />
          <img
            class="btn-square"
            src="../../../../assets/baggage/ic_export.png"
          >
          <img
            class="btn-square"
            src="../../../../assets/baggage/ic_setting.png"
            @click="show"
          >
        </div>
        <el-table
          ref="flightBaggageTable"
          :data="filteredTableData"
          border
          style="width: 100%"
          height="320"
          stripe
          size="mini"
          show-summary
          :summary-method="summaryRow(flightBaggageTableData.length)"
          :header-cell-style="{ color: '#101116' }"
          :cell-class-name="cellClass"
          @cell-click="cellClickHandler"
        >
          <el-table-column
            v-for="col in tableColsCopy"
            :key="col.index"
            :prop="col.prop"
            :label="col.name"
            :align="col.align || 'center'"
            :width="col.width"
            :formatter="tableFormat"
          >
            <template #header>
              <div class="table-header-cell">
                <span>{{ col.name }}</span>
                <template v-if="flightBaggageTableFilters[col.prop]">
                  <TableHeaderCellWithFilter
                    :label="col.name"
                    :filter-options="flightBaggageTableFilters[col.prop]"
                    :filter-value.sync="filterValues[col.prop]"
                  />
                </template>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--列设置-->
    <Dialog
      :flag="dialogFlag"
      class="dialog-check-cols"
    >
      <div class="col-dialog">
        <div class="title">列设置</div>
        <div class="content">
          <el-tree
            :data="tableCols"
            :class="colsCheckClass"
            show-checkbox
            node-key="index"
            :default-expand-all="true"
            :props="{
              label: 'name',
              children: 'children'
            }"
            :default-checked-keys="checkedKeysTemp"
            @check="handleCheck"
          />
        </div>
        <div class="foot right t30">
          <el-button
            size="medium"
            class="r24"
            type="primary"
            @click="onCheck"
          >确定</el-button>
          <el-button
            size="medium"
            @click="hide"
          >取消</el-button>
        </div>
      </div>
    </Dialog>
  </div>
</template>
<script>
import Dialog from '@/layout/components/Dialog/index.vue'
import TimeZoneSelector from '@/components/TimeZoneSelector'
import { queryMap, myQuery } from '@/api/dataIntegration'
import tableColsMixin from '../../mixins/tableCols'
import timeZoneMixin from '../../mixins/timeZone'
import TableHeaderCellWithFilter from '@/components/TableHeaderCellWithFilter'
import { setTableFilters } from '@/utils/table'

// const arrivalBaggageTableColumn = [
//   { name: '序号', prop: 'index' },
//   { name: '旅客姓名', prop: 'name', sortable: 'custom' },
//   { name: '行李牌号', prop: 'bagNo' },
//   {
//     name: '特殊行李类型',
//     prop: 'specialType',
//     sortable: 'custom'
//   },
//   {
//     name: '容器编号',
//     prop: 'containerNo',
//     sortable: 'custom'
//   },
//   { name: '装载序号', prop: 'loadSequenceIndex' },
//   { name: '卸载', prop: 'uninstall' },
//   { name: '到达', prop: 'arrival' },
//   { name: '提取', prop: 'extract' },
//   { name: '旅客仓位', prop: 'positionNo' },
//   { name: '中转标志', prop: 'transitStatus' },
//   { name: '卷宗号', prop: 'fileNumber' }
// ]
const departureBaggageTableColumn = [
  // { name: '序号', prop: 'index' },
  { name: '旅客姓名', prop: 'PassengerNameUpcase', sortable: 'custom' },
  { name: '行李牌号', prop: 'BagSN' },
  {
    name: '特殊行李类型',
    prop: 'SpecialType',
    sortable: 'custom'
  },
  {
    name: '容器编号',
    prop: 'U_Device_ID',
    sortable: 'custom'
  },
  { name: '装载序号', prop: 'LoadSN' },
  { name: '值机', prop: 'checkIn', width: 140 },
  { name: '状态', prop: 'latestStatus' },
  { name: '安检', prop: 'security', width: 140 },
  { name: '分拣', prop: 'sorting', width: 140 },
  { name: '装车', prop: 'loading', width: 140 },
  { name: '装机', prop: 'installed', width: 140 },
  { name: '中转标志', prop: 'transitFlag' },
  { name: '卷宗号', prop: 'fileNumber' }
]
export default {
  name: 'FlightView',
  components: {
    Dialog,
    TimeZoneSelector,
    TableHeaderCellWithFilter
  },
  mixins: [tableColsMixin, timeZoneMixin],
  data() {
    return {
      queryData: {},
      flightInfo: {},
      keyWords: '',
      openUTC: true,
      props: { multiple: true },
      // options: [
      //   { value: 0, label: 'VIP行李' },
      //   { value: 0, label: 'VIP行李' }
      // ],
      containerTableColumn: [
        { name: '容器编号', prop: 'containerNumber' },
        { name: '类型', prop: 'style' },
        { name: '行李数', prop: 'numberOfBags' }
      ],
      transferInTableColumn: [
        { name: '航班号', prop: 'PreFlightNO' },
        { name: '日期', prop: 'PreFlightDate' },
        { name: '时间', prop: 'flightTime' },
        { name: '始发站', prop: 'PlanDepartureApt' },
        { name: '航班状态', prop: 'FlightStatus' },
        { name: '中转数', prop: 'totalNumber' }
      ],
      transferOutTableColumn: [
        { name: '航班号', prop: 'TransferFlightNO' },
        { name: '日期', prop: 'TransferFlightDate' },
        { name: '时间', prop: 'flightTime' },
        { name: '始发站', prop: 'PlanDepartureApt' },
        { name: '目的站', prop: 'PlanLandingApt' },
        { name: '中转数', prop: 'transferNumber' }
      ],
      // tableCols:
      //   this.$route.matched[0].path === '/arrival' || this.$route.matched[1].path === '/transfer/arrival'
      //     ? arrivalBaggageTableColumn
      //     : departureBaggageTableColumn,
      tableCols: departureBaggageTableColumn,
      containerTableData: [], // 容器统计
      transferInBaggageTableData: [], // 中转进
      transferOutBaggageTableData: [], // 中转出
      flightBaggageTableData: [], // 行李列表
      flightBaggageTableFilters: {
        PassengerNameUpcase: [],
        BagSN: [],
        SpecialType: [],
        U_Device_ID: [],
        latestStatus: []
      },
      filterValues: {
        PassengerNameUpcase: '',
        BagSN: '',
        SpecialType: '',
        U_Device_ID: '',
        latestStatus: ''
      },
      warningContainers: []
    }
  },
  computed: {
    filteredTableData() {
      return this.flightBaggageTableData.filter(item => {
        let flag = true
        Object.entries(this.filterValues).forEach(([key, value]) => {
          if (value !== '' && item[key] !== value) {
            flag = false
          }
        })
        return flag
      })
    }
  },
  created() {
    this.queryData = this._.cloneDeep(this.$route.query)
    // console.log(this.queryData)
    const queryData = [this.queryData.FlightNO, this.queryData.FlightDate]
    this.queryAll(queryData)
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['containerTable'].doLayout()
      this.$refs['transferInBaggageTable'].doLayout()
      this.$refs['transferOutBaggageTable'].doLayout()
      this.$refs['flightBaggageTable'].doLayout()
    })
  },
  methods: {
    cellClass({ row, column, rowIndex, columnIndex }) {
      const classes = []
      if (['checkIn', 'security', 'sorting', 'loading', 'installed'].includes(column.property)) {
        classes.push('pre-line')
      }
      if (
        ['PreFlightNO', 'totalNumber', 'TransferFlightNO', 'transferNumber', 'PassengerNameUpcase', 'BagSN'].includes(
          column.property
        )
      ) {
        classes.push('cell-click')
      }
      if (
        (column.property === 'latestStatus' && row[column.property] === '待翻减') ||
        this.warningContainers.includes(row['containerNumber'])
      ) {
        classes.push('cell-warning')
      }
      return classes.join(' ')
    },
    cellClickHandler(row, column, cell, event) {
      switch (column.property) {
        case 'PreFlightNO':
          this.$router.push({
            path: '/advance/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 'TransferFlightNO':
          this.$router.push({
            path: '/advance/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.$message.info('开发中')
          break
        case 'BagSN':
          this.$router.push({
            path: `/${this.$route.path.split('/').slice(1, -1).join('/')}/baggageView`,
            query: {
              BagSN: row.BagSN,
              FlightNO: this.queryData.FlightNO,
              FlightDate: this.queryData.FlightDate
            }
          })
          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}件`]
      }
    },
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    containeClick(row) {
      this.$router.push({
        path: '/advance',
        query: {
          FlightNO: this.queryData.FlightNO,
          startDate: this.queryData.FlightDate,
          endDate: this.queryData.FlightDate,
          U_Device_ID: row.containerNumber
        }
      })
    },
    queryflightInfo(dataContent) {
      return myQuery(queryMap.flightInfo, ...dataContent)
    },
    queryContainer(dataContent) {
      return myQuery(queryMap.container, ...dataContent)
    },
    queryTrasferOutBaggage(dataContent) {
      return myQuery(queryMap.transferOutBaggage, ...dataContent)
    },
    queryTrasferInBaggage(dataContent) {
      return myQuery(queryMap.transferInBaggage, ...dataContent)
    },
    queryBaggageByFlightNO(dataContent) {
      return myQuery(queryMap.baggageByFlightNO, ...dataContent)
    },
    async queryAll(dataContent) {
      try {
        const [
          flightInfo,
          containerTableDataData,
          transferOutBaggageTableData,
          transferInBaggageTableData,
          flightBaggageTableData
        ] = await Promise.all([
          this.queryflightInfo(dataContent),
          this.queryContainer(dataContent),
          this.queryTrasferOutBaggage(dataContent),
          this.queryTrasferInBaggage(dataContent),
          this.queryBaggageByFlightNO(dataContent)
        ])
        flightInfo.length && (this.flightInfo = flightInfo[0])
        this.containerTableData = containerTableDataData
        this.transferOutBaggageTableData = transferOutBaggageTableData.map(item => {
          item['flightTime'] = item['flightDate'] ? item['flightDate'].split('T')[1] : ''
          return item
        })
        this.transferInBaggageTableData = transferInBaggageTableData.map(item => {
          item['flightTime'] = item['flightDate'] ? item['flightDate'].split('T')[1] : ''
          return item
        })

        this.warningContainers = []
        this.flightBaggageTableData = flightBaggageTableData.map((item, index) => {
          item['latestStatus'] === '待翻减' && this.warningContainers.push(item['U_Device_ID'])

          item['checkIn'] = `${item['checkIn'] ?? ''}\n${item['checkInTime'] ?? ''}`
          // item['latestStatus'] = item['Status'] === 'DEL' ? '删除' : item['latestStatus']
          item['security'] = `${item['DealInfo'] ?? ''}\n${item['DealTime'] ?? ''}`
          item['sorting'] = `${item['sortLocationMark'] ?? ''}\n${item['sortDealTime'] ?? ''}`
          item['loading'] = `${item['loadLocationMark'] ?? ''}\n${item['loadDealTime'] ?? ''}`
          item['installed'] = `${item['inflLocationMark'] ?? ''}\n${item['inflLoadDealTime'] ?? ''}`
          item['transitFlag'] = item['PreFlightNO'] ? '是' : '否'
          return item
        })

        setTableFilters(this.flightBaggageTableData, this.flightBaggageTableFilters)
      } catch (error) {
        console.log('错误', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.flight-view {
  padding: 16px 0 44px 8px;
  overflow: hidden;
  background: #dfe3ea;
  .flight-wrap {
    padding-right: 8px;
    width: 100%;
    height: calc(100vh - 140px);
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: wrap;
    overflow: auto;
    .part1 {
      width: 71.15%;
      height: 344px;
      background: #041741;
      padding: 24px;
      .title {
        font-size: 18px;
        font-weight: bold;
        color: #ffffff;
      }
      .part1_info {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        padding-top: 32px;

        .part1_info_box {
          width: calc(33.333% - 48px);
          height: 244px;
          background: #2c416d;
          position: relative;
          padding: 24px;
          display: flex;
          flex-direction: column;
          align-content: space-around;
          .el-row {
            margin-bottom: 27px;
          }
          span {
            display: inline-block;
            font-size: 16px;
            font-weight: 400;
            color: #ffffff;
          }
        }
        .part1_info_box::after {
          content: '';
          border-top: 15px solid transparent;
          border-left: 10px solid transparent;
          border-bottom: 10px solid #fff;
          position: absolute;
          right: -34px;
          transform: rotate(-45deg);
          top: 50%;
          margin-top: -15px;
        }
        .part1_info_box:last-child::after {
          content: '';
          border-top: 0;
          border-left: 0;
          border-bottom: 0;
        }
      }
    }
    .part2 {
      width: calc(100% - 71.15%);
      height: 344px;
      padding-left: 16px;
    }
    .part3 {
      width: 50%;
      height: 204px;
      margin-top: 8px;
      .title {
        background: #fafcff;
        font-size: 14px;
        font-weight: bold;
        color: #101116;
        padding: 12px 0;
        text-align: center;
      }
    }
    .part4 {
      width: 100%;
      height: 384px;
      .title {
        padding: 16px 0;
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        align-items: center;
        .search {
          display: flex;
          flex-direction: row;
          margin-left: 20px;
          margin-right: 10px;
        }
        .el-dropdown {
          height: 30px;
        }
        .btn-square {
          margin-left: 20px;
          cursor: pointer;
          &:last-child {
            margin-right: 30px;
          }
        }
      }
      .el-table {
        .el-table__body-wrapper {
          min-height: 178px;
        }
      }
    }
  }
  ::v-deep .el-table {
    .cell-click {
      cursor: pointer;
      color: #2d7cff;
      &.cell-clicked {
        color: purple;
      }
    }
    .cell-warning {
      background: orange;
    }
  }
}
</style>
