<!--
 * @Author: zk
 * @Date: 2022-01-17 10:39:22
 * @LastEditTime: 2022-06-22 17:39:49
 * @LastEditors: your name
 * @Description: 离港01
-->
<template>
  <div class="departure-one">
    <!--功能区-表单-->
    <div ref="formWrap" class="terminal-form-wrap">
      <el-form ref="form" :inline="true" :model="formData" :rules="rules" class="form">
        <div class="form-left">
          <el-form-item prop="currentAirport">
            <!-- <el-cascader
            v-model="formData.currentAirport"
            style="width:144px;margin-left:10px"
            placeholder="全部机场"
            size="small"
            :options="currentAirportList"
            :props="currentAirportProps"
            collapse-tags
            clearable
            filterable
            @change="setCurrentAirport"
          /> -->
            <el-select v-model="formData.currentAirport" class="input-shadow" size="small" filterable placeholder="请选择机场" @change="airPortChange">
              <el-option v-for="(item, index) in AirportList" :key="index" :label="item.planDepartureApt" :value="item.planDepartureApt" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              class="input-shadow"
              style="width:216px;"
              size="small"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="开始时间"
              @change="startDateChangeHandler"
            />
          </el-form-item>
          <el-form-item prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              class="input-shadow"
              style="width:216px;"
              size="small"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="结束时间"
              @change="endDateChangeHandler"
            />
          </el-form-item> -->
          <el-form-item prop="flightDate" label="航班日期">
            <el-date-picker v-model="formData.flightDate" size="small" type="daterange" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="dateRangePickerOptions" @change="dateChangeHandler" />
          </el-form-item>
          <el-form-item>
            <div class="box-item">
              <p>预计装载总数：</p>
              <li v-for="(item, index) in orderNum" :key="index" :class="{ 'number-item': !isNaN(item), 'mark-item': isNaN(item) }">
                <span v-if="!isNaN(item)">
                  <i ref="numberItem">0123456789</i>
                </span>
                <span v-else class="comma">{{ item }}</span>
              </li>
            </div>
          </el-form-item>
        </div>
        <div class="form-right" @keyup.enter="onSubmit(0)">
          <el-form-item prop="search">
            <el-popover :value="popoverVisible" placement="bottom" trigger="manual">
              <span>请输入航班号（示例：CA1234）或行李牌号（示例：1234567890）</span>
              <el-input slot="reference" v-model="formData.search" class="input-shadow" style="width: 240px; margin-left: 105px" size="small" placeholder="请输入内容" prefix-icon="el-icon-search" clearable @focus="popoverVisible = true" @blur="popoverVisible = false" />
            </el-popover>
          </el-form-item>
          <el-form-item>
            <el-button class="btn-shadow" size="mini" type="primary" @click="onSubmit(0)">搜索</el-button>
          </el-form-item>
          <el-form-item v-is="['i_timeIcon']">
            <TimeZoneSelector />
          </el-form-item>
          <el-form-item>
            <img class="btn-img btn-shadow" src="../../../../assets/baggage/ic_setting.png" @click="show">
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!--表格-->
    <div v-loading="loading" class="terminal-table" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
      <el-table ref="table" class="table" :height="computedTableHeight" :data="dealedTableData" :header-cell-class-name="headerCellClass" :row-class-name="tableRowClassName" :cell-class-name="cellClass" show-summary :summary-method="summaryMethod" border stripe fit @cell-click="cellClickHandler">
        <el-table-column v-for="col in tableColsCopy" :key="col.prop" :prop="col.prop" :label="col.label" :width="col.width" :fixed="col.fixed" :formatter="tableFormat">
          <template #header>
            <el-tooltip :content="col.disc" 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>
    <!--列设置-->
    <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: '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">确定</el-button>
          <el-button size="medium" @click="hide">取消</el-button>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import Dialog from '@/layout/components/Dialog'
import TimeZoneSelector from '@/components/TimeZoneSelector'
import terminalMixin from '../../mixins/terminal'
import formMixin from '../../mixins/form'
import tableColsMixin from '../../mixins/tableCols'
import timeZoneMixin from '../../mixins/timeZone'
import { getQuery } from '@/api/flight'
import TableHeaderCell from '@/components/TableHeaderCell'
import { setTableFilters } from '@/utils/table'

export default {
  name: 'DepartureTerminalView',
  components: { Dialog, TimeZoneSelector, TableHeaderCell },
  mixins: [terminalMixin, formMixin, tableColsMixin, timeZoneMixin],
  data () {
    return {
      orderNum: ['0', '0', '0', '0', '0', '0'], // 默认总数
      popoverVisible: false,
      // 初始表头
      tableCols: [
        {
          prop: 'flightNO',
          label: '航班号',
          disc: '指航班编号',
          width: 80,
          fixed: 'left',
          filterable: true,
          sortable: true
        },
        {
          prop: 'flightDate',
          label: '执飞日期',
          disc: '指航班计划起飞日期（不变的，机票上），不是预计起飞日期（预计起飞时间可能多个），也不是实际起飞日期（实际起飞等于最后预计）',
          width: 105,
          fixed: 'left',
          filterable: true,
          sortable: true
        },
        {
          prop: 'planDepartureTime',
          label: '预计起飞时间',
          disc: '指航班预计起飞时间，数据是变化的，仅显示最新结果',
          width: 150,
          filterable: true,
          sortable: true
        },
        {
          prop: 'targetAirport',
          label: '目的站',
          disc: '指航班执飞航段的目的航站，以航站三字码显示',
          filterable: true,
          sortable: true
        },
        {
          prop: 'departureBuild',
          label: '航站楼',
          disc: '指航班执飞航段的目的航站楼',
          filterable: true,
          sortable: true
        },
        {
          prop: 'bordingGate',
          label: '登机口',
          disc: '指航班的登机口代码，数据是变化的，仅显示最新信息',
          filterable: true,
          sortable: true
        },
        {
          prop: 'standForDepartrue',
          label: '停机位',
          disc: '指航班的停机位代码，数据是变化的，仅显示最新信息',
          filterable: true,
          sortable: true
        },
        {
          prop: 'checkInTravellerNumber',
          label: '托运旅客',
          disc: '指航班已办理行李托运业务的旅客人数，含取消托运的旅客人数',
        },
        {
          prop: 'checkInNumber',
          label: '值机数',
          disc: '指已办理值机托运的行李数量，含取消托运的行李数量，含未激活',
        },
        {
          prop: 'unActive',
          label: '未激活',
          disc: '指最后的 BSM 报文“.S”中行李状态为“I”的行李数量，含取消托运的行李数量',
        },
        {
          prop: 'preLoad',
          label: '预计装载',
          disc: '指已办理值机托运的行李数量，不含取消托运的行李数量，不包含未激活',
        },
        {
          prop: 'checkNumber',
          label: '安检',
          disc: '指进行安检的行李数量，含取消托运的行李数量',
        },
        {
          prop: 'sortNumber',
          label: '分拣',
          disc: '指已分拣完成的行李数量，含取消托运的行李数量',
        },
        {
          prop: 'loadNumber',
          label: '装车',
          disc: '指已在分拣口装车完成的行李数量，含取消托运的行李数量',
        },
        {
          prop: 'landingNumber',
          label: '装机',
          disc: '指装机完成的行李数量，不含取消托运的行李数量',
        },
        {
          prop: 'tounLoad',
          label: '待翻减',
          disc: '指旅客在办理行李托运后，旅客取消该行李的托运并且行李此时已经过装车节点，而没有完成翻减的行李数量（须翻减总数减去已翻减数）',
        },
        {
          prop: 'unLoad',
          label: '已翻减',
          disc: '指旅客在办理行李托运后，旅客取消该行李的托运并且行李此时已经过装车节点，且已完成翻减的行李数量',
        },
        {
          prop: 'noCheckInNumber',
          label: '取消托运',
          disc: '指旅客在办理行李托运后，又取消托运的行李总数量',
        },
        {
          prop: 'noBSM',
          label: '无BSM',
          disc: '行李有处理信息（BPM）但无值机信息(BSM)的行李数量',
        },
        {
          prop: 'warning',
          label: '风险预警',
          disc: '指依据航班信息中预计起飞时间和当前时间差，与根据分拣到停机位设置的报警阈值对比，超过阈值的为风险行李，本项显示风险预警行李数量',
        },
        {
          prop: 'exceptions',
          label: '离港异常',
          disc: '指航班关闭货仓门后，应装而未装的行李数量',
        },
        {
          prop: 'midIn',
          label: '中转进行李',
          disc: '指从其他航班中转到当前航班的行李数量',
        }
      ],
      tableDataSortRules: {
        flightCanceled: 'ascending'
      },
      loading: false,
      AirportList: [],
      loopEvent: null,
      leaveCount: 0,
      baggageCount: 0,
      hasSetTableScroll: false
    }
  },
  mounted () {
    this.getAirPortData()
  },
  beforeDestroy () {
    if (this.loopEvent) {
      clearInterval(this.loopEvent)
      this.loopEvent = null
    }
  },
  computed: {
    singleDay () {
      return this.startDate === this.endDate
    }
  },
  methods: {
    resetLoopEvent () {
      this.loading = true
      this.hasSetTableScroll = false
      if (this.loopEvent) {
        clearInterval(this.loopEvent)
      }
      this.getTableData()
      const that = this
      this.loopEvent = setInterval(function () {
        that.getTableData()
      }, 3000)
    },
    airPortChange () {
      this.resetLoopEvent()
    },
    dateChangeHandler () {
      this.resetLoopEvent()
    },
    async getAirPortData () {
      try {
        const res = await getQuery({
          id: DATACONTENT_ID.departureAirMainId,
          dataContent: []
        })
        if (Number(res.code) === 0) {
          this.AirportList = this._.orderBy(res.returnData.listValues, o => o.planDepartureApt)
          this.formData.currentAirport = 'PEK'
          this.resetLoopEvent()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    tableRowClassName ({ row, rowIndex }) {
      const classes = []
      if (row.flightStatus === 'DLY') {
        classes.push('bgl-delayed')
      }
      if (row.flightStatus === 'CAN') {
        classes.push('bgl-canceled')
      }
      if (row.hasTakenOff === 0) {
        classes.push('bgl-hui')
        if (rowIndex === this.leaveCount - 1) {
          classes.push('redBorder')
        }
      }
      return classes.join(' ')
    },
    headerCellClass ({ row, column }) {
      const classes = []
      if (['warning', 'exceptions', 'midIn'].includes(column.property)) {
        classes.push('bgl-huang')
      }
      const rule = this.tableDataSortRules[column.property]
      if (rule) {
        classes.push(rule)
      }
      return classes.join(' ')
    },
    // 获取表单下拉框数据
    // getFormData(params) {
    //   this.relatedAirportQuery({
    //     ...params,
    //     type: 'OUT'
    //   })
    //   this.outgoingAirlineQuery(params)
    //   this.craftTypeQuery(params)
    //   this.flightAttrQuery(params)
    // },
    // 获取表格数据
    async getTableData () {
      if (!this.formData.currentAirport || !this.startDate || !this.endDate) {
        return
      }
      const arr = [this.formData.currentAirport, this.startDate, this.endDate]
      try {
        const res = await getQuery({
          id: DATACONTENT_ID.departureTableMainId,
          dataContent: [...arr, ...arr, ...arr]
        })
        if (Number(res.code) === 0) {
          this.initTableData(res.returnData.listValues)
        } else {
          console.log(res.message)
        }
        this.loading = false
      } catch (error) {
        if (this.loopEvent) {
          clearInterval(this.loopEvent)
          this.loopEvent = null
        }
        this.loading = false
        console.log('出错了', error)
      }
    },
    initTableData (tableData) {
      this.leaveCount = 0
      this.baggageCount = 0
      tableData.forEach(item => {
        item['flightCanceled'] = item['flightStatus'] === 'CAN' ? 1 : 0
        if (item['hasTakenOff'] === 0 && !item['flightCanceled']) {
          this.leaveCount++
        }
        item['landingNumber'] = item['loadNumber']
        this.baggageCount = this.baggageCount + item.preLoad
      })
      this.tableData = this._.sortBy(tableData, ['hasTakenOff', 'planDepartureTime'])
      setTableFilters(this.tableData, this.tableDataFilters)
      this.toOrderNum(this.baggageCount)
      // setInterval(() => {
      //   this.baggageCount = this.baggageCount+1;
      //    // 这里输入数字即可调用
      // }, 2000);
      this.$nextTick(() => {
        this.setTableScroll()
      })
    },
    setTableScroll () {
      if (!this.singleDay || this.hasSetTableScroll || this.leaveCount === 0) {
        return
      }
      const table = this.$refs['table'].$el
      const scrollParent = table.querySelector('.el-table__body-wrapper')
      if (scrollParent.scrollHeight <= scrollParent.offsetHeight) {
        return
      }
      const lastRow = table.querySelectorAll('.el-table__body tr')[this.leaveCount - 1]
      setTimeout(() => {
        const scrollMid = lastRow.offsetTop + lastRow.offsetHeight - scrollParent.offsetHeight / 2
        const scrollMax = scrollParent.scrollHeight - scrollParent.offsetHeight
        if (scrollMid > 0) {
          const scrollHeight = Math.min(scrollMid, scrollMax)
          scrollParent.scrollTo(0, scrollHeight)
        }
      }, 0)
      this.hasSetTableScroll = true
    },
    setNumberTransform () {
      const numberItems = this.$refs.numberItem // 拿到数字的ref，计算元素数量
      const numberArr = this.orderNum.filter(item => !isNaN(item))
      // 结合CSS 对数字字符进行滚动,显示订单数量
      for (let index = 0; index < numberItems.length; index++) {
        const elem = numberItems[index]
        elem.style.transform = `translate(-50%, -${numberArr[index] * 10}%)`
      }
    },

    toOrderNum (num) {
      num = num.toString()
      if (num.length < 6) {
        num = '0' + num // 如未满八位数，添加"0"补位
        this.toOrderNum(num) // 递归添加"0"补位
      } else if (num.length >= 6) {
        this.orderNum = num.split('') // 将其便变成数据，渲染至滚动数组
      } else {
        // 订单总量数字超过八位显示异常
        this.$message.warning('总量数字过大')
      }
      this.setNumberTransform()
    }
  }
}
</script>

<style lang="scss" scoped>
.terminal-form-wrap {
  padding-top: 11px;
  padding-left: 5px;
  ::v-deep .form {
    display: flex;
    justify-content: space-between;
    .form-left {
      flex: 1;
    }
    .form-right {
      flex: 0 1 498px;
    }
    .el-form-item {
      margin-bottom: 0px;
      margin-right: 8px;
      button,
      input,
      optgroup,
      select,
      textarea {
        font-family: Helvetica, "Microsoft YaHei";
        font-size: 14px;
      }
      .el-switch__label {
        color: #303133;
      }
      .el-form-item__error {
        z-index: 10;
      }
    }
    .btn-img {
      position: relative;
      top: 6px;
    }
  }
  .box-item {
    position: relative;
    height: 50px;
    font-size: 18px;
    line-height: 32px;
    text-align: center;
    list-style: none;
    color: #2d7cff;
    writing-mode: vertical-lr;
    text-orientation: upright;
    /*文字禁止编辑*/
    -moz-user-select: none; /*火狐*/
    -webkit-user-select: none; /*webkit浏览器*/
    -ms-user-select: none; /*IE10*/
    -khtml-user-select: none; /*早期浏览器*/
    user-select: none;
    /* overflow: hidden; */
    p {
      line-height: 32px;
      writing-mode: horizontal-tb !important;
      text-orientation: none !important;
      /*文字禁止编辑*/
      -moz-user-select: none; /*火狐*/
      -webkit-user-select: none; /*webkit浏览器*/
      -ms-user-select: none; /*IE10*/
      -khtml-user-select: none; /*早期浏览器*/
      user-select: none;
      margin-top: 5px;
    }
  }
  /* 默认逗号设置 */
  .mark-item {
    width: 10px;
    height: 32px;
    margin-right: 5px;
    line-height: 10px;
    font-size: 18px;
    position: relative;
    & > span {
      position: absolute;
      width: 100%;
      bottom: 0;
      writing-mode: vertical-rl;
      text-orientation: upright;
    }
  }
  /*滚动数字设置*/
  .number-item {
    width: 41px;
    height: 42px;
    /* 背景图片 */
    background: url(/images/text-bg-blue.png) no-repeat center center;
    background-size: 100% 100%;
    // background: #ccc;
    list-style: none;
    margin-right: 5px;
    // background:rgba(250,250,250,1);
    border-radius: 4px;
    border: 3px solid rgb(221, 221, 221);
    & > span {
      position: relative;
      display: inline-block;
      margin-right: 10px;
      width: 100%;
      height: 100%;
      writing-mode: vertical-rl;
      text-orientation: upright;
      overflow: hidden;
      & > i {
        font-style: normal;
        position: absolute;
        top: 11px;
        left: 50%;
        transform: translate(-50%, -1%);
        transition: transform 1s ease-in-out;
        letter-spacing: 10px;
      }
    }
  }
  .number-item:last-child {
    margin-right: 0;
  }
}
.terminal-table {
  width: 100%;
  ::v-deep .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;
      }
      .has-gutter {
        tr {
          .bgl-huang {
            background: #fcf0b1;
          }
        }
      }
    }
    .el-table__body-wrapper,
    .el-table__fixed-body-wrapper {
      tr.bgl-hui {
        td {
          background: #d2d6df;
        }
        &.redBorder {
          position: relative;
          &::after {
            content: "";
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 2px;
            background: #e83f82;
          }
        }
      }
      tr.bgl-delayed td {
        background: #fcf0b1;
      }
      tr.bgl-canceled td {
        background: #f7babe;
      }
      td.cell-tounLoad {
        background: lightcoral !important;
        position: relative;
        &::after {
          content: "";
          display: block;
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          border: 2px dashed red;
        }
      }
      .el-table__cell.is-hidden > * {
        visibility: visible;
      }
    }
  }
}
</style>
