<template>
  <div class="container-history">
    <div class="container-left">
      <div class="title">
        <span class="manageTitle">容器历史</span>
        <!-- <BackButton /> -->
      </div>
      <div
        v-loading="treeLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        class="container-tree"
      >
        <el-tree
          :data="containerHistoryTree"
          :props="defaultTreeProps"
          node-key="index"
          default-expand-all
          :expand-on-click-node="false"
          @current-change="currentChangeHandler"
        >
          <span
            slot-scope="{ node, data }"
            class="el-tree-node__label"
          >
            <el-tooltip
              v-if="data.index === -1"
              class="item"
              effect="dark"
              :content="msg"
              placement="top"
            >
              <span>{{ node.label }}</span>
            </el-tooltip>
            <span v-else>{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
    </div>
    <div
      v-loading="tableLoading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      class="container-right"
    >
      <el-table
        ref="table"
        :data="dealedTableData"
        border
        stripe
        fit
        height="calc(100vh - 80px - 17px - 20px)"
        :header-cell-class-name="headerCellClass"
        :row-class-name="tableRowClassName"
        :cell-class-name="cellClass"
        @cell-click="cellClickHandler"
      >
        <el-table-column
          v-for="col in tableCols"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          :fixed="col.fixed"
          :formatter="tableFormat"
        >
          <template #header>
            <el-tooltip
              :content="col.desc || col.label"
              placement="top"
            >
              <TableHeaderCell
                :label="col.label"
                :filter-options="tableDataFilters[col.prop]"
                :filter-values.sync="filterValues[col.prop]"
                :sortable="col.sortable"
                :sort-rule.sync="tableDataSortRules[col.prop]"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
// import BackButton from '@/components/BackButton'
import TableHeaderCell from '@/components/TableHeaderCell'
import { mapGetters } from 'vuex'
import { myQuery } from '@/api/dataIntegration'
import { setTableFilters } from '@/utils/table'

export default {
  name: 'ContainerHistory',
  components: {
    // BackButton,
    TableHeaderCell
  },
  data() {
    return {
      queryData: {},
      containerHistory: [],
      selectedHistoryData: {},
      defaultTreeProps: {
        children: 'children',
        label: 'label'
      },
      treeLoading: false,
      tableLoading: false,
      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: 115,
          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: {},
      msg: '容器历史默认显示最近10条历史，如果需要可联系管理员进行配置'
    }
  },
  computed: {
    ...mapGetters(['clickedCells']),
    containerHistoryTree() {
      return [
        {
          index: -1,
          label: `容器历史-${this.queryData.containerID}`,
          children: this.containerHistory.map(({ flightNO, flightDate, departureAirport, arriveAirport }, index) => ({
            index,
            label: [flightNO, flightDate.replaceAll('-', '/'), departureAirport, arriveAirport].join('-')
          }))
        }
      ]
    },
    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])
    }
  },
  created() {
    const { containerID } = this.$route.query
    if (containerID) {
      this.queryData = { containerID }
      this.queryContainerHistory([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, '')
      }
    })
  },
  updated() {
    // table数据更新
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  deactivated() {
    this.treeLoading = false
    this.tableLoading = false
  },
  methods: {
    currentChangeHandler({ index }) {
      if (index > -1) {
        this.selectedHistoryData = this.containerHistory[index]
        const { flightNO, flightDate, departureAirport, arriveAirport, containerID } = this.selectedHistoryData
        const dataContent = [flightNO, flightDate, departureAirport, arriveAirport, containerID]
        this.queryBaggageList(dataContent)
      }
    },
    // 给表头单元格加上 ascending 或 descending 使用 element 自带的排序箭头变色
    headerCellClass({ row, column, rowIndex, columnIndex }) {
      const classes = []
      const rule = this.tableDataSortRules[column.property]
      if (rule) {
        classes.push(rule)
      }
      return classes.join(' ')
    },
    tableRowClassName({ row, rowIndex }) {
      const classes = []
      if (row.isDEL === 'DEL') {
        classes.push('bgl-deleted')
      }
      return classes.join(' ')
    },
    cellClass({ row, column, rowIndex, columnIndex }) {
      const classes = []
      if (
        [
          'passengerName',
          'luggageSN'
          // 'inFlightNO',
          // 'transferFlightNO'
        ].includes(column.property) &&
        row[column.property]
      ) {
        classes.push('cell-click')
        if (
          this.clickedCells.some(
            cell =>
              cell.pageName === 'advance' &&
              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.selectedHistoryData.flightNO,
              flightDate: this.selectedHistoryData.flightDate,
              passengerName: row.passengerName
            })
            this.$store.dispatch('app/togglePassengerDialogFlag', true)
            break
          case 'luggageSN':
            this.$router.push({
              path: `/${this.$route.path.split('/').slice(1, -1).join('/')}/baggageView`,
              query: {
                flightNO: this.selectedHistoryData.flightNO,
                flightDate: this.selectedHistoryData.flightDate,
                bagSN: row.luggageSN
              }
            })
            break
          // case 'inFlightNO':
          //   this.$router.push({
          //     path: '/advance/flightView',
          //     query: {
          //       flightNO: row.inFlightNO,
          //       flightDate: row.preFlightDate
          //     }
          //   })
          //   break
          // case 'transferFlightNO':
          //   this.$router.push({
          //     path: '/advance/flightView',
          //     query: {
          //       flightNO: row.transferFlightNO,
          //       flightDate: row.transferFlightDate
          //     }
          //   })
          //   break
          default:
            break
        }
      }
    },
    tableFormat(row, column, cellValue) {
      switch (column.property) {
        case 'isDEL':
          return cellValue === 'DEL' ? '删除' : ''
        case 'activeState':
          return Number(cellValue) === 1 ? '激活' : '未激活'
        default:
          return cellValue ?? ''
      }
    },
    async queryContainerHistory(dataContent) {
      this.treeLoading = true
      this.tableData = []
      try {
        const result = await myQuery(DATACONTENT_ID.containerHistory, ...dataContent)
        this.containerHistory = result
        this.msg = '容器历史默认显示最近' + this.containerHistory[0].k + '条历史，如果需要可联系管理员进行配置'
      } catch (error) {
        this.$message.error('失败')
      }
      this.treeLoading = false
    },
    async queryBaggageList(dataContent) {
      this.tableLoading = true
      this.tableData = []
      try {
        const result = await myQuery(DATACONTENT_ID.containerBaggage, ...dataContent)
        this.tableData = result
        setTableFilters(this.tableData, this.tableDataFilters)
      } catch (error) {
        this.$message.error('失败')
      }
      this.tableLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.container-history {
  padding: 17px 24px 20px;
  display: flex;
  .container-left {
    flex: 0 1 352px;
    margin-right: 16px;
    background-color: #ffffff;
    .title {
      height: 32px;
      .manageTitle {
        margin-right: 0;
      }
    }
    ::v-deep .el-tree {
      height: calc(100vh - 80px - 32px - 17px - 20px);
      overflow-x: hidden;
      overflow-y: auto;
      > .el-tree-node {
        > .el-tree-node__children {
          display: block;
        }
        .el-tree-node__content {
          height: 38px;
          .el-tree-node__label {
            margin-left: 0;
            letter-spacing: 1px;
            line-height: 38px;
            font-size: 14px;
            font-family: Helvetica, 'Microsoft YaHei';
            font-weight: bold;
            color: #101116;
          }
        }
        > .el-tree-node__content {
          > .el-tree-node__expand-icon.el-icon-caret-right:not(.is-leaf):before {
            font-size: 16px;
            color: #101116;
          }
          > .el-tree-node__label {
            font-size: 16px;
          }
        }
      }
    }
  }

  .container-right {
    flex: 1;
    ::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__header-wrapper,
      .el-table__fixed-header-wrapper {
        .cell {
          font-weight: bold;
          color: #101116;
        }
      }
      .el-table__body-wrapper,
      .el-table__fixed-body-wrapper {
        tr.bgl-deleted {
          background: #d2d6df;
          td {
            background: #d2d6df;
            font-style: italic;
          }
        }
      }
    }
  }
}
</style>
