<template>
  <div class="container-view">
    <div class="container-basic">
      <div class="title">
        <div class="manageTitle">容器基本信息</div>
        <el-button
          type="primary"
          size="small"
          @click="toContainerHistory"
        >历史记录</el-button>
      </div>
      <div
        ref="basicBox"
        class="basic-info-box"
      >
        <el-row :gutter="10">
          <el-col
            :xs="6"
            :sm="6"
            :xl="4"
          >
            <div class="grid-content">容器编号：{{ $route.query.containerID }}</div>
          </el-col>
          <el-col
            :xs="6"
            :sm="6"
            :xl="3"
          >
            <div class="grid-content">容器类型：{{ $route.query.containerType }}</div>
          </el-col>
          <el-col
            :xs="6"
            :sm="6"
            :xl="3"
          >
            <div class="grid-content">舱位：{{ $route.query.containerSpace }}</div>
          </el-col>
          <el-col
            :xs="6"
            :sm="6"
            :xl="3"
          >
            <div class="grid-content">航班号：{{ $route.query.flightNO }}</div>
          </el-col>
          <el-col
            :xs="12"
            :sm="12"
            :xl="5"
          >
            <div class="grid-content">航班日期：{{ $route.query.flightDate }}</div>
          </el-col>
          <el-col
            :xs="6"
            :sm="6"
            :xl="3"
          >
            <div class="grid-content">起飞站：{{ $route.query.departureAirport }}</div>
          </el-col>
          <el-col
            :xs="6"
            :sm="6"
            :xl="3"
          >
            <div class="grid-content">目的站：{{ $route.query.landingAirport }}</div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="container-table">
      <div class="title">
        <div class="manageTitle">容器行李列表</div>
        <!-- <TimeZoneSelector /> -->
        <img
          class="btn-square btn-shadow"
          src="@/assets/baggage/ic_export.png"
          title="导出"
          @click="exportHandler('table', '容器行李列表')"
        >
        <img
          class="btn-square btn-shadow"
          src="@/assets/baggage/ic_setting.png"
          title="列设置"
          @click="show"
        >
      </div>
      <div class="table-wrapper">
        <el-table
          ref="table"
          :data="dealedTableData"
          :height="computedTableHeight"
          border
          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="tableDataFilters[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('tableData')"
          >确定</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 { 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: 'ContainerView',
  components: {
    // TimeZoneSelector,
    Dialog,
    TableHeaderCell
  },
  mixins: [
    tableColsMixin
    //  timeZoneMixin
  ],
  data() {
    return {
      loading: false,
      queryData: {},
      computedTableHeight: undefined,
      tableCols: [
        {
          prop: 'passengerName',
          label: '旅客姓名',
          desc: '指旅客姓名的拼音大写',
          filterable: true,
          sortable: true
        },
        {
          prop: 'luggageSN',
          label: '行李牌号',
          desc: '指行李的10位数字行李牌号码',
          filterable: true,
          sortable: true
        },
        {
          prop: 'specialType',
          label: '特殊行李类型',
          desc: '指有别于普通托运行李的特殊行李分类，包括（装笼动物、机组行李、易碎行李、VIP行李等），参考BSM报文.E项说明',
          width: 120,
          filterable: true,
          sortable: true
        },
        {
          prop: 'isDEL',
          label: '删除',
          desc: '指旅客是否取消值机托运，根据BSM报文状态是否有DEL判断，已删除的行李记录为斜体灰色字体',
          filterable: true,
          sortable: true
        },
        {
          prop: 'activeState',
          label: '激活',
          desc: '指托运行李是否被激活，参照BSM报文.S项说明',
          filterable: true,
          sortable: true
        },
        {
          prop: 'luggageWeight',
          label: '重量',
          desc: '指托运行李的重量，参照BSM报文.W项说明'
        },
        {
          prop: 'lastStatus',
          label: '最新状态',
          desc: '指托运行李的当前查询时间所在的节点状态',
          filterable: true,
          sortable: true
        },
        {
          prop: 'lastLocation',
          label: '最新位置',
          desc: '指托运行李的当前查询时间所在的节点状态的识读位置代号',
          filterable: true,
          sortable: true
        },
        {
          prop: 'inFlightNO',
          label: '中转进航班',
          desc: '指有中转行李转出的进港航班号',
          width: 110,
          filterable: true,
          sortable: true
        },
        {
          prop: 'transferFlightNO',
          label: '中转出航班',
          desc: '指有中转行李转入的离港航班号',
          width: 110,
          filterable: true,
          sortable: true
        }
      ],
      tableData: [],
      tableDataFilters: {},
      filterValues: {},
      tableDataSortRules: {}
    }
  },
  computed: {
    ...mapGetters(['clickedCells']),
    dealedTableData() {
      const filtered = this.tableData.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])
    }
  },
  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()
      }
    }
  },
  created() {
    const { flightNO, flightDate, departureAirport, landingAirport, containerID } = this.$route.query
    if (flightNO && flightDate && departureAirport && landingAirport && containerID) {
      this.queryData = { flightNO, flightDate, departureAirport, landingAirport, containerID }
      this.queryContainerBaggage([flightNO, flightDate, departureAirport, landingAirport, containerID])
    } else {
      this.$router.push('/')
    }
    Object.values(this.tableCols).forEach(({ prop, filterable, sortable }) => {
      if (filterable) {
        this.$set(this.tableDataFilters, prop, [])
        this.$set(this.filterValues, prop, [])
      }
      if (sortable) {
        this.$set(this.tableDataSortRules, prop, '')
      }
    })
  },
  activated() {
    this.setTableHeight()
  },
  updated() {
    this.setTableHeight()
  },
  deactivated() {
    this.fullscreenLoading?.close()
  },
  methods: {
    setTableHeight() {
      const headerHeight = 80
      const bottomBlankHeight = 16
      const titleHeight = 64
      const basicBoxHeight = this.$refs['basicBox'].offsetHeight
      this.computedTableHeight = `calc(100vh - ${
        headerHeight + bottomBlankHeight + titleHeight * 2 + basicBoxHeight
      }px)`
      this.$nextTick(() => {
        this.$refs['table']?.doLayout()
      })
    },
    rowClass({ row, rowIndex }) {
      const classes = []
      if (row['isDEL'] === 'DEL') {
        classes.push('bgl-deleted')
        if (row['waitOFF'] === 1) {
          classes.push('bgl-toUnload')
        }
      }
      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 (
        [
          // 'passengerName',
          'luggageSN'
          // 'inFlightNO',
          // 'transferFlightNO'
        ].includes(column.property) &&
        row[column.property]
      ) {
        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 (
        [
          // 'passengerName',
          'luggageSN'
          // 'inFlightNO',
          //  'transferFlightNO'
        ].includes(column.property) &&
        row[column.property]
      ) {
        this.$store.dispatch('keepAlive/addClickedCell', {
          row,
          columnProp: column.property,
          pageName: this.$route.name
        })
        switch (column.property) {
          // case 'passengerName':
          //   this.$store.dispatch('app/setPassengerQueryParams', {
          //     flightNO: this.queryData.flightNO,
          //     flightDate: this.queryData.flightDate,
          //     passengerName: row.passengerName
          //   })
          //   this.$store.dispatch('app/togglePassengerDialogFlag', true)
          //   break
          case 'luggageSN':
            this.$router.push({
              path: `${this.$route.path.split('/').slice(0, -1).join('/')}/baggageView`,
              query: {
                bagSN: row.luggageSN,
                flightNO: this.queryData.flightNO,
                flightDate: this.queryData.flightDate
              }
            })
            break
          default:
            break
        }
      }
    },
    toContainerHistory() {
      this.$router.push({
        path: `${this.$route.path.split('/').slice(0, -1).join('/')}/containerHistory`,
        query: {
          containerID: this.queryData.containerID
        }
      })
    },
    // 统计行数
    summaryRow(num) {
      return function () {
        return ['合计', `共${num}件`]
      }
    },
    tableFormat(row, column, cellValue) {
      switch (column.property) {
        case 'isDEL':
          return cellValue === 'DEL' ? '删除' : ''
        case 'activeState':
          return Number(cellValue) === 1 ? '激活' : '未激活'
        default:
          return cellValue ?? ''
      }
    },
    exportHandler(refName, tableName) {
      const table = this.$refs[refName].$el.cloneNode(true)
      const fileName = `${tableName}-${Object.values(this.queryData).join('-')}.xlsx`
      throttledExportToExcel(table, tableName, fileName)
    },
    async queryContainerBaggage(dataContent) {
      this.loading = true
      this.tableData = []
      try {
        const tableData = await myQuery(SERVICE_ID.containerBaggage, ...dataContent)
        this.tableData = tableData
        setTableFilters(this.tableData, this.tableDataFilters)
      } catch {
        this.$message.error('失败')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.container-view {
  width: 100%;
  height: calc(100vh - 80px - 16px);
  overflow: hidden;
  background: #dfe3ea;
  padding: 0px 8px;
  .title {
    display: flex;
    justify-content: space-between;
    padding: 16px 0;
    margin-right: 0;
  }
  .container-basic {
    .basic-info-box {
      width: 100%;
      background: #041741;
      padding: 16px 30px;
      color: #fff;
    }
  }
  .container-table {
    .title {
      height: 64px;
      .manageTitle {
        flex: 1;
      }
      .el-dropdown {
        height: 30px;
      }
      .btn-square {
        height: 30px;
        margin-left: 20px;
        &:last-child {
          margin-right: 30px;
        }
      }
    }
    .table-wrapper {
      background-color: #fff;
      ::v-deep .el-table {
        width: 100%;
        .cell {
          padding: 0;
          text-align: center;
          font-size: 14px;
          font-family: Helvetica, 'Microsoft YaHei';
          letter-spacing: 0;
        }
        .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;
            }
            &.bgl-warning td {
              background: lightcoral;
            }
          }
        }
      }
    }
  }
}
</style>
