<!--
 * @Author: zk
 * @Date: 2022-01-17 10:39:22
 * @LastEditTime: 2022-05-24 18:05:27
 * @LastEditors: your name
 * @Description: 进港01
-->
<template>
  <div class="arrival-one">
    <!--功能区-表单-->
    <div class="arrival-form">
      <el-form
        ref="form"
        :inline="true"
        :model="formData"
        :rules="rules"
        class="form"
      >
        <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"
            size="small"
            filterable
            placeholder="请选择机场"
            @change="airPortChange"
          >
            <el-option
              v-for="(item, index) in AirportList"
              :key="index"
              :label="item.PlanLandingApt"
              :value="item.PlanLandingApt"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            style="width: 216px"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="开始时间"
            @change="setStartDate"
          />
        </el-form-item>
        <el-form-item prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            style="width: 216px"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="结束时间"
            @change="setEndDate"
          />
        </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
          style="float: right"
          @keyup.enter="onSubmit(1)"
        >
          <el-form-item prop="search">
            <el-input
              v-model="formData.search"
              style="width: 240px; margin-left: 105px"
              size="small"
              placeholder="请输入内容"
              prefix-icon="el-icon-search"
              clearable
              @clear="inputClear"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              size="small"
              type="primary"
              @click="onSubmit(1)"
            >搜索</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-switch
              v-model="formData.switch"
              style="margin-left: 40px"
              active-text="显示中转"
            />
          </el-form-item> -->
          <el-form-item v-is="['i_timeIcon']">
            <TimeZoneSelector />
          </el-form-item>
          <el-form-item>
            <img
              class="btn-img"
              src="../../../../assets/baggage/ic_setting.png"
              @click="show"
            >
          </el-form-item>
          <!-- <el-form-item>
            <el-button
              class="btn-square setBtn"
              type="primary"
              icon="el-icon-s-tools"
              size="mini"
              @click="show"
            />
          </el-form-item> -->
        </div>
      </el-form>
    </div>
    <!--表格-->
    <div
      v-loading="loading"
      class="arrival-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="calc(100vh - 177px)"
        :data="filteredTableData"
        :header-cell-class-name="headerCellClassName"
        :row-class-name="tableRowClassName"
        :cell-class-name="cellClass"
        show-summary
        :summary-method="summaryMethod"
        border
        stripe
        fit
        @cell-click="cellClick"
      >
        <el-table-column
          v-for="(item, index) in tableColsCopy"
          :key="index"
          :prop="item.prop"
          :label="item.label"
        >
          <el-table-column
            v-for="(col, i) in item.children"
            :key="i"
            :prop="col.prop"
            :label="col.label"
            :width="col.width"
          >
            <template #header>
              <el-tooltip
                :content="col.label"
                placement="top"
              >
                <div class="table-header-cell">
                  <span>{{ col.label }}</span>
                  <template v-if="tableDataFilters[col.prop]">
                    <el-popover
                      placement="bottom"
                      trigger="click"
                      @show="popoverShowHandler(col.prop)"
                      @hide="popoverHideHandler"
                    >
                      <i
                        slot="reference"
                        :class="['filter-arrow', 'el-icon-arrow-down', arrowClass(col.prop)]"
                      />
                      <el-form>
                        <el-form-item :label="col.label">
                          <el-select
                            v-model="filterValues[col.prop]"
                            size="small"
                            placeholder="筛选"
                            default-first-option
                            filterable
                            clearable
                          >
                            <el-option
                              v-for="(option, optionIndex) in tableDataFilters[col.prop]"
                              :key="option.value + optionIndex"
                              :value="option.value"
                              :label="option.text"
                            />
                          </el-select>
                        </el-form-item>
                      </el-form>
                    </el-popover>
                  </template>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
        </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 { getQuery } from '@/api/flight'
import { setTableFilters } from '@/utils/table'

export default {
  name: 'DepartureTerminalView',
  components: { Dialog, TimeZoneSelector },
  mixins: [terminalMixin, formMixin, tableColsMixin],
  data() {
    return {
      orderNum: ['0', '0', '0', '0', '0', '0'], // 默认总数
      // 初始表头
      tableCols: [
        {
          prop: 'flightInfo',
          label: '航班信息',
          children: [
            {
              prop: 'FlightNO',
              label: '航班号',
              width: 80
            },
            {
              prop: 'FlightDate',
              label: '执飞日期',
              width: 105
            },
            {
              prop: 'arrivalTime',
              label: '到港时间',
              width: 150
            },
            {
              prop: 'departureTerminal',
              label: '起飞航站'
            },
            {
              prop: 'arrivalTerminal',
              label: '到达航站'
            },
            {
              prop: 'luggageCarousel',
              label: '行李转盘'
            },
            {
              prop: 'parkingSpace',
              label: '停机位'
            }
          ]
        },
        {
          prop: 'originAirportBaggageInfo',
          label: '始飞站行李信息',
          children: [
            {
              prop: 'checkIns',
              label: '值机'
            },
            {
              prop: 'projectedLoad',
              label: '预计装载'
            },
            {
              prop: 'loadedQuantity',
              label: '已装载'
            }
          ]
        },
        {
          prop: 'arrvivalBaggageInfo',
          label: '到达行李信息',
          children: [
            {
              prop: 'numberOfDestinationArrivals',
              label: '到达'
            },
            {
              prop: 'endPointNotReached',
              label: '未到达'
            },
            {
              prop: 'specialQuantity',
              label: '特殊'
            },
            {
              prop: 'numberOfClaims',
              label: '理赔'
            }
          ]
        },
        {
          prop: 'uninstallInfo',
          label: '卸载状态',
          children: [
            {
              prop: 'uninstalled',
              label: '已卸载'
            },
            {
              prop: 'numberToBeUninstalled',
              label: '待卸载'
            }
          ]
        },
        {
          prop: 'terminationdBaggageInfo',
          label: '终止行李',
          children: [
            {
              prop: 'terminateArrivalQuantity',
              label: '到达'
            },
            {
              prop: 'terminateUnreachedQuantity',
              label: '未到达'
            }
          ]
        },
        {
          prop: 'transferBaggageInfo',
          label: '转运行李',
          children: [
            {
              prop: 'quantityShipped',
              label: '已交运'
            },
            {
              prop: 'undeliveredQuantity',
              label: '未交运'
            }
          ]
        },
        {
          prop: 'baggageDistributionInfo',
          label: '行李分布',
          children: [
            {
              prop: 'numberOfContainers',
              label: '容器'
            },
            {
              prop: 'numberOfBulk',
              label: '散装'
            }
          ]
        }
      ],
      AirportList: [],
      FlightNOFilterOptions: [],
      FlightDateFilterOptions: [],
      asarrivalTimeFilterOptions: [],
      departureTerminalFilterOptions: [],
      arrivalTerminalFilterOptions: [],
      luggageCarouselFilterOptions: [],
      parkingSpaceFilterOptions: [],
      numberOfContainersFilterOptions: [],
      tableDataFilters: {
        FlightNO: [],
        FlightDate: [],
        asarrivalTime: [],
        departureTerminal: [],
        arrivalTerminal: [],
        luggageCarousel: [],
        parkingSpace: [],
        numberOfContainers: []
      },
      filterValues: {
        FlightNO: '',
        FlightDate: '',
        asarrivalTime: '',
        departureTerminal: '',
        arrivalTerminal: '',
        luggageCarousel: '',
        parkingSpace: '',
        numberOfContainers: ''
      },
      loopEvent: null,
      leaveCount: 0,
      baggageCount: 0,
      colShowFilter: ''
    }
  },
  computed: {
    arrowClass() {
      return function (prop) {
        let classString = ''
        if (this.colShowFilter === prop) {
          classString += ' arrow-active'
        }
        if (Object.entries(this.tableDataFilters).find(([key, arr]) => this.filterValues[prop])) {
          classString += ' arrow-blue'
        }
        return classString
      }
    },
    // filterOptions() {
    //   return function (prop) {
    //     if (Object.keys(this.filterValues).includes(prop)) {
    //       return this[`${prop}FilterOptions`]
    //     } else {
    //       return false
    //     }
    //   }
    // },
    filteredTableData() {
      return this.tableData.filter(item => {
        let flag = true
        Object.entries(this.filterValues).forEach(([key, value]) => {
          if (value !== '' && item[key] !== value) {
            flag = false
          }
        })
        return flag
      })
    }
  },
  created() {
    this.getAirPortData()
  },
  mounted() {
    const that = this
    this.loopEvent = setInterval(function () {
      that.getTableData()
    }, 3000)
  },
  beforeDestroy() {
    clearInterval(this.loopEvent)
  },
  methods: {
    airPortChange() {
      this.getTableData()
    },
    // 选择机场
    async getAirPortData() {
      try {
        const res = await getQuery({
          id: 67,
          dataContent: []
        })
        if (Number(res.code) === 0) {
          this.AirportList = this._.orderBy(res.returnData, o => o.PlanLandingApt)
          this.formData.currentAirport = 'PEK'
          this.getTableData()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    popoverShowHandler(prop) {
      this.colShowFilter = prop
    },
    popoverHideHandler() {
      this.colShowFilter = ''
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.hasTakenOff === 0) {
        if (rowIndex === this.leaveCount - 1) {
          return 'bgl-hui redBorder'
        } else {
          return 'bgl-hui'
        }
      }
    },
    headerCellClassName({ row, column }) {
      if (
        column.property === 'transfer_all' ||
        column.property === 'departureAnomaly' ||
        column.property === 'riskWarning'
      ) {
        return 'bgl-huang'
      }
    },
    // 获取表单下拉框数据
    // getFormData(params) {
    //   this.relatedAirportQuery({
    //     ...params,
    //     type: 'OUT'
    //   })
    //   this.outgoingAirlineQuery(params)
    //   this.craftTypeQuery(params)
    //   this.flightAttrQuery(params)
    // },
    // 获取表格数据
    async getTableData() {
      if (!this.formData.currentAirport) {
        return
      }
      const arr = [this.formData.currentAirport, this.formData.startDate, this.formData.endDate]
      try {
        const res = await getQuery({
          id: 38,
          dataContent: [...arr, ...arr, ...arr]
        })
        if (Number(res.code) === 0) {
          this.initTableData(res.returnData)
        } else {
          console.log(res.message)
        }
      } catch (error) {
        clearInterval(this.loopEvent)
        console.log('出错了', error)
      }
    },
    initTableData(tableData) {
      this.leaveCount = 0
      this.baggageCount = 0
      tableData.forEach(item => {
        if (item.hasTakenOff === 0) {
          this.leaveCount++
        }
        // item["waitfanj"] = item["noCheckInNumber"] - item["unLoad"];
        this.baggageCount = this.baggageCount + item.projectedLoad
      })
      this.tableData = this._.sortBy(tableData, ['FlightDate', 'PlanDepartureTime'])
      setTableFilters(this.tableData, this.tableDataFilters)
      this.toOrderNum(this.baggageCount)
      // const tableDataFilters = setTableFilters(this.tableData, [
      //   'FlightNO',
      //   'FlightDate',
      //   'asarrivalTime',
      //   'departureTerminal',
      //   'arrivalTerminal',
      //   'luggageCarousel',
      //   'parkingSpace',
      //   'numberOfContainers'
      // ])
      // Object.entries(tableDataFilters).forEach(([key, arr]) => {
      //   arr.forEach((item, index) => {
      //     this.$set(this[`${key}FilterOptions`], index, item)
      //   })
      // })
      // setInterval(() => {
      //   this.baggageCount = this.baggageCount+1;
      //    // 这里输入数字即可调用
      // }, 2000);
    },
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    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>
.arrival-form {
  padding-top: 11px;
  padding-left: 5px;
  ::v-deep .form {
    .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;
      }
      .el-button {
        &.btn-square {
          width: 30px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 5px;
        }
      }
    }
    .btn-img {
      cursor: pointer;
      position: relative;
      top: 6px;
    }
  }
  .box-item {
    position: relative;
    height: 32px;
    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;
  }
}
.arrival-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 {
      .cell {
        font-weight: bold;
        color: #101116;
      }
      .has-gutter {
        tr {
          .bgl-huang {
            background: #fcf0b1;
          }
        }
      }
    }
    .el-table__body-wrapper {
      tr.bgl-hui {
        background: #d2d6df;
        td {
          background: #d2d6df;
        }
        &.redBorder {
          position: relative;
          &::after {
            content: '';
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 2px;
            background: #e83f82;
          }
        }
      }
    }
  }
}
.filter-arrow {
  cursor: pointer;
  transition: 0.3s transform;
  &.arrow-active {
    transform: rotate(-180deg);
  }
  &.arrow-blue {
    color: #2d7cff;
    font-weight: bold;
  }
}
.el-select-dropdown__item.hover {
  background: #d2d6df;
}
</style>
