/*
 * @Author: Badguy
 * @Date: 2022-03-04 11:41:55
 * @LastEditTime: 2022-06-09 16:24:07
 * @LastEditors: your name
 * @Description: 航站视图通用部分
 * have a nice day!
 */

import { mapGetters } from 'vuex'
import { commonTableCellClass } from '@/utils/table'

export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      tableDataFilters: {},
      filterValues: {},
      tableDataSortRules: {},
      spanArr: [],
      pos: 0,
      loading: false,
      computedTableHeight: 0
    }
  },
  created() {
    this.setFilterAndSort(this.tableCols)
  },
  updated() {
    const headerHeight = 80
    const bottomBlankHeight = 41
    const formWrapHeight = this.$refs['formWrap'].offsetHeight
    this.computedTableHeight = `calc(100vh - ${headerHeight + bottomBlankHeight + formWrapHeight}px)`
  },
  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(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: {
    dealedTableData: {
      handler(val) {
        this.spanArr = []
        let contactDot = this.contactDot
        val.forEach((item, index, arr) => {
          if (index === 0) {
            this.spanArr.push(1)
          } else {
            if (
              item['FlightNO'] === arr[index - 1]['FlightNO'] &&
              item['FlightDate'] === arr[index - 1]['FlightDate']
            ) {
              this.spanArr[contactDot] += 1
              this.spanArr.push(0)
            } else {
              this.spanArr.push(1)
              contactDot = index
            }
          }
        })
      },
      deep: true
    }
  },
  methods: {
    // 设置筛选和排序
    setFilterAndSort (tableCols) {
      const self = this
      Object.values(tableCols).forEach(({ prop, filterable, sortable, children }) => {
        if (children) {
          self.setFilterAndSort(children)
        } else {
          if (filterable) {
            self.$set(self.tableDataFilters, prop, [])
            self.$set(self.filterValues, prop, [])
          }
          if (sortable) {
            self.$set(self.tableDataSortRules, prop, '')
          }
        }
      })
    },
    // 合计行
    summaryMethod({ columns, data }) {
      const sums = []
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
          } else if (index === 1) {
            sums[index] = '航班数：' + this.tableData.length
          } else if (
            // 需要计算的列
            [
              'passagernum',
              'checkNumber',
              'not_actived',
              'expect_load',
              'security_all',
              'sortNumber',
              'loadNumber',
              'tounLoad',
              'unLoad',
              'delbag',
              'noBSM',
              'transfer_all',
              'reach',
              'did_not_arrive',
              'special',
              'claim',
              'uninstalled',
              'to_be_uninstalled',
              'terminateArrive',
              'terminatedNotArrived',
              'delivered',
              'not_shipped',
              'container',
              'bulk',
              'checkInTravellerNumber',
              'checkInNumber',
              'unActive',
              'preLoad',
              'noCheckInNumber',
              'midIn',
              'checkIns',
              'projectedLoad',
              'loadedQuantity',
              'numberOfDestinationArrivals',
              'endPointNotReached',
              'specialQuantity',
              'numberOfClaims',
              'numberToBeUninstalled',
              'terminateArrivalQuantity',
              'terminateUnreachedQuantity',
              'quantityShipped',
              'undeliveredQuantity',
              'numberOfBulk',
              'inTransferBaggageCount',
              'inTransferredBaggageCount',
              'outTransferBaggageCount',
              'outTransferredBaggageCount'
            ].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
    },
    cellClass({ row, column, rowIndex, columnIndex }) {
      const classes = commonTableCellClass({ row, column, rowIndex, columnIndex })
      if (
        [
          'FlightNO',
          'PreFlightNO',
          'inTransferBaggageCount',
          'inTransferredBaggageCount',
          'tounLoad',
          'unLoad',
          'checkInNumber',
          'unActive',
          'midIn',
          'noCheckInNumber',
          'checkNumber',
          'sortNumber',
          'loadNumber',
          'landingNumber',
          'checkIns'
        ].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')
        }
      }
      if (column.property === 'tounLoad' && row[column.property]) {
        classes.push('cell-tounLoad')
      }
      return classes.join(' ')
    },
    cellClickHandler(row, column, cell, event) {
      if (
        [
          'FlightNO',
          'PreFlightNO',
          'inTransferBaggageCount',
          'inTransferredBaggageCount',
          'tounLoad',
          'unLoad',
          'checkInNumber',
          'unActive',
          'midIn',
          'noCheckInNumber',
          'checkNumber',
          'sortNumber',
          'loadNumber',
          'landingNumber',
          'checkIns'
        ].includes(column.property)
      ) {
        this.$store.dispatch('keepAlive/addClickedCell', {
          row,
          columnProp: column.property,
          pageName: this.$route.name
        })
      }
      switch (column.property) {
        case 'FlightNO':
          this.$router.push({
            path: `${this.$route.path}/flightView`,
            query: {
              FlightNO: row.FlightNO,
              FlightDate: row.FlightDate
            }
          })
          break
        case 'PreFlightNO':
          this.$router.push({
            path: '/transfer/arrival/flightView',
            query: {
              FlightNO: row.PreFlightNO,
              FlightDate: row.FlightDate
            }
          })
          break
        case 'inTransferBaggageCount':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.PreFlightNO,
              transferDeparture: row.FlightNO,
              startDate: row.PreFlightDate,
              endDate: row.PreFlightDate
            }
          })
          break
        case 'inTransferredBaggageCount':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              transferArrival: row.PreFlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate
            }
          })
          break
        case 'tounLoad':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate,
              unLoad: 0
            }
          })
          break
        case 'unLoad':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate,
              unLoad: 1
            }
          })
          break
        case 'checkInNumber':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate,
              checkIn: 1
            }
          })
          break
        case 'unActive':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate,
              active: 0
            }
          })
          break
        case 'midIn':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate,
              transferIn: 1
            }
          })
          break
        case 'noCheckInNumber':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate,
              canceled: 1
            }
          })
          break
        case 'checkNumber':
        case 'sortNumber':
        case 'loadNumber':
        case 'landingNumber': {
          const reflect = {
            checkNumber: '安检',
            sortNumber: '分拣',
            loadNumber: '装车',
            landingNumber: '装机'
          }
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate,
              status: reflect[column.property]
            }
          })
          break
        }
        case 'checkIns':
          this.$router.push({
            path: '/advance',
            query: {
              FlightNO: row.FlightNO,
              startDate: row.FlightDate,
              endDate: row.FlightDate,
              checkIn: 1
            }
          })
          break
        default:
          break
      }
    }
  }
}
