<template>
  <div class="container-view">
    <div
      v-loading="treeLoading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      class="container-left"
    >
      <el-tree
        :data="containerHistoryTree"
        :props="defaultTreeProps"
        node-key="index"
        default-expand-all
        :expand-on-click-node="false"
        @current-change="currentChangeHandler"
      />
    </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 TableHeaderCell from '@/components/TableHeaderCell'
import { mapGetters } from 'vuex'
import { myQuery } from '@/api/dataIntegration'
import { setTableFilters } from '@/utils/table'

export default {
  name: 'ContainerView',
  components: {
    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: {}
    }
  },
  computed: {
    ...mapGetters(['clickedCells']),
    containerHistoryTree() {
      return [
        {
          index: -1,
          label: '容器历史',
          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(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: {
    $route: {
      handler({ path, query }) {
        if (path.includes('containerView')) {
          const { containerID } = query
          if (containerID) {
            const { containerID: oldContainerID } = this.queryData
            if (containerID !== oldContainerID) {
              this.queryData = { containerID }
              this.queryContainerHistory([containerID])
            }
          } else {
            this.$router.push('/')
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    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
  },
  beforeDestroy() {
    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 (
        [
          'flightNO',
          '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 (
        [
          // 'flightNO',
          '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 'flightNO':
          //   this.$router.push({
          //     path: '/advance/flightView',
          //     query: {
          //       flightNO: this.selectedHistoryData.flightNO,
          //       flightDate: this.selectedHistoryData.flightDate
          //     }
          //   })
          //   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' ? cellValue : ''
        case 'activeState':
          return 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
      } catch (error) {
        console.log('出错了', error.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) {
        console.log('出错了', error.message || error)
      }
      this.tableLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.container-view {
  padding: 17px 24px 20px;
  display: flex;
  .container-left {
    flex: 0 1 352px;
    margin-right: 16px;
    background-color: #ffffff;
    ::v-deep .el-tree > .el-tree-node {
      > .el-tree-node__children {
        display: block;
      }
      .el-tree-node__content {
        height: 38px;
        .el-tree-node__label {
          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>