<template>
  <div class="advance">
    <div class="advance__head flex">
      <div class="flex-wrap interfaceLog_head_time">
        <div class="manageTitle">高级查询</div>
        <!-- <div class="interfaceLog_head_time_start mr10">
          <el-date-picker
            v-model="flightDate[0]"
            class="input-shadow"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期时间"
            @change="startDateChangeHandler"
          />
        </div>
        <div class="interfaceLog_head_time_end">
          <el-date-picker
            v-model="flightDate[1]"
            class="input-shadow"
            size="small"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束日期时间"
            @change="endDateChangeHandler"
          />
        </div> -->
        <el-date-picker
          v-model="flightDate"
          size="small"
          type="daterange"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="dateRangePickerOptions"
          :clearable="false"
        />
      </div>
      <Search
        ref="search"
        class="advanced-search"
        :is-title="false"
        :is-slot="true"
        :search-tooltip="'请输入航班号（示例：CA1234）或行李牌号（示例：1234567890）'"
        @getSearchData="getSearchData"
        @clearSearchData="clearSearchData"
      >
        <div class="flex-wrap">
          <button
            class="btnAn"
            @click="dialogShow"
          >
            高级查询
          </button>
          <button
            class="btnAn"
            @click="exportHandler('table', '高级查询结果')"
          >
            导出
          </button>
          <button
            class="btnAn"
            @click="toNewAdvance"
          >
            切换
          </button>
          <!-- <div
            class="setting"
            @click="show"
          /> -->
        </div>
      </Search>
    </div>
    <!--表格-->
    <div
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      class="advance__table"
    >
      <el-table
        ref="table"
        v-el-table-infinite-scroll="load"
        max-height="100%"
        class="table"
        :data="dealedTableData"
        border
        stripe
        fit
        height="calc(100vh - 158px)"
        style="width: 100%"
        show-summary
        :summary-method="summaryRow(dealedTableData.length)"
        :header-cell-class-name="headerCellClass"
        :row-class-name="tableRowClassName"
        :cell-class-name="cellClass"
        :span-method="objectSpanMethod"
        @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>
    <!--列设置-->
    <!-- <Dialog
      :flag="dialogFlag"
      class="dialog-check-group"
    >
      <div class="dialog-wrapper">
        <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> -->
    <!--高级查询-->
    <Dialog
      width="900px"
      :flag="gjFlag"
    >
      <div
        ref="dialog"
        class="advanced-dialog"
        :tabindex="0"
        @keyup.enter="advancedSubmitHandler(false)"
        @keyup.self.esc="gjFlag = false"
      >
        <div class="title">高级查询</div>
        <div class="content">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="100px"
          >
            <el-row :gutter="20">
              <el-col
                v-for="item in formItems"
                :key="item.prop"
                :span="item.span || 8"
              >
                <el-form-item
                  :label="item.label"
                  :prop="item.prop"
                >
                  <template v-if="item.prop === 'flightDate'">
                    <el-date-picker
                      v-model="flightDate"
                      size="small"
                      type="daterange"
                      value-format="yyyy-MM-dd"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :picker-options="dateRangePickerOptions"
                      :clearable="false"
                      @keyup.esc.native="dialogFocus"
                    />
                  </template>
                  <template v-else-if="item.prop === 'status'">
                    <el-select
                      v-model="form.status"
                      size="small"
                      filterable
                      default-first-option
                      clearable
                      @keyup.esc.native="dialogFocus"
                    >
                      <el-option
                        v-for="(option, index) in statusList"
                        :key="index"
                        :label="option.statusName"
                        :value="option.statusCode"
                      />
                    </el-select>
                  </template>
                  <template v-else-if="item.prop === 'specialType'">
                    <el-select
                      v-model="form.specialType"
                      size="small"
                      class="multiple-select"
                      multiple
                      collapse-tags
                      filterable
                      allow-create
                      default-first-option
                      clearable
                      @keyup.esc.native="dialogFocus"
                    >
                      <el-option
                        v-for="option in baggageTypeList"
                        :key="option.specialType"
                        :label="option.specialType"
                        :value="option.specialType"
                      />
                    </el-select>
                  </template>
                  <template v-else-if="item.prop === 'unLoad'">
                    <el-select
                      v-model="form.unLoad"
                      size="small"
                      clearable
                      @keyup.esc.native="dialogFocus"
                    >
                      <el-option
                        label="已翻减"
                        :value="1"
                      />
                      <el-option
                        label="待翻减"
                        :value="0"
                      />
                    </el-select>
                  </template>
                  <template
                    v-else-if="
                      ['checkIn', 'active', 'transferIn', 'canceled'].includes(
                        item.prop
                      )
                    "
                  >
                    <el-select
                      v-model="form[item.prop]"
                      size="small"
                      clearable
                      @keyup.esc.native="dialogFocus"
                    >
                      <el-option
                        label="是"
                        :value="1"
                      />
                      <el-option
                        label="否"
                        :value="0"
                      />
                    </el-select>
                  </template>
                  <template v-else-if="item.prop === 'noBSM'">
                    <el-select
                      v-model="form.noBSM"
                      size="small"
                      clearable
                      @keyup.esc.native="dialogFocus"
                    >
                      <el-option
                        label="是"
                        :value="0"
                      />
                      <el-option
                        label="否"
                        :value="1"
                      />
                    </el-select>
                  </template>
                  <template v-else-if="item.prop === 'loadType'">
                    <el-select
                      v-model="form.loadType"
                      size="small"
                      clearable
                      @keyup.esc.native="dialogFocus"
                    >
                      <el-option
                        label="容器"
                        :value="0"
                      />
                      <el-option
                        label="散装"
                        :value="1"
                      />
                    </el-select>
                  </template>
                  <template v-else>
                    <el-popover
                      v-model="item.hintVisible"
                      placement="right"
                      trigger="manual"
                    >
                      <span>{{ item.hintText }}</span>
                      <el-input
                        :ref="'input-' + item.prop"
                        slot="reference"
                        v-model="form[item.prop]"
                        size="small"
                        @focus="item.hintVisible = true"
                        @blur="item.hintVisible = false"
                        @keyup.esc.native="dialogFocus"
                      />
                    </el-popover>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="foot right t30">
          <el-button
            size="medium"
            class="r24"
            type="primary"
            @click="advancedSubmitHandler(false)"
            >确定</el-button
          >
          <el-button
            size="medium"
            @click="dialogHide"
            >取消</el-button
          >
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import Search from '@/components/SearchWithTooltip'
import Dialog from '@/layout/components/Dialog'
import { parseTime } from '@/utils/index'
import { TempQuery, myQuery } from '@/api/temp'
import { mapGetters } from 'vuex'
import TableHeaderCell from '@/components/TableHeaderCell'
import { setTableFilters, throttledExportToExcel } from '@/utils/table'

export default {
  name: 'AdvancedHome',
  components: { Search, Dialog, TableHeaderCell },
  data() {
    return {
      loading: false,
      colDialogFlag: false,
      gjFlag: false,
      tableData: [],
      page: -1,
      noMore: false,
      checkList: [],
      tableCols: [
        {
          prop: 'flightNO',
          label: '航班号',
          desc: '指航班编号',
          fixed: 'left',
          filterable: true,
          sortable: true,
        },
        {
          prop: 'flightDate',
          label: '航班日期',
          desc: '指航班计划起飞日期（机票上的静态数据）',
          fixed: 'left',
          width: 110,
          filterable: true,
          sortable: true,
        },
        {
          prop: 'departureTime',
          label: '起飞时间',
          desc: '指航班预计起飞时间，动态数据，仅显示最新结果',
          width: 150,
        },
        {
          prop: 'sourceAirport',
          label: '起飞站',
          desc: '指航班执飞航段的起飞航站，以航站英文三字码显示',
          filterable: true,
          sortable: true,
        },
        {
          prop: 'targetAirport',
          label: '目的地',
          desc: '指航班执飞航段的目的航站，以航站英文三字码显示',
          filterable: true,
          sortable: true,
        },
        {
          prop: 'passengerNameUpcase',
          label: '旅客姓名',
          desc: '指旅客姓名的拼音大写',
          width: 150,
          filterable: true,
          sortable: true,
        },
        {
          prop: 'bagSN',
          label: '行李牌号',
          desc: '指行李的10位数字行李牌号码',
          width: 110,
          filterable: true,
          sortable: true,
        },
        {
          prop: 'specialType',
          label: '特殊行李类型',
          desc: '指有别于普通托运行李的特殊行李分类，包括（装笼动物、机组行李、易碎行李、VIP行李等），参考BSM报文.E项说明',
          width: 115,
          filterable: true,
          sortable: true,
        },
        {
          prop: 'deleted',
          label: '删除',
          desc: '指旅客是否取消值机托运，根据BSM报文状态是否有DEL判断，已删除的行李记录为斜体灰色字体',
          filterable: true,
          sortable: true,
        },
        {
          prop: 'activated',
          label: '激活',
          desc: '指托运行李是否被激活，参照BSM报文.S项说明',
          filterable: true,
          sortable: true,
        },
        {
          prop: 'bagWeight',
          label: '重量',
          desc: '指托运行李的重量，参照BSM报文.W项说明',
        },
        {
          prop: 'latestStatus',
          label: '最新状态',
          desc: '指托运行李的当前查询时间所在的节点状态',
          width: 110,
          filterable: true,
          sortable: true,
        },
        {
          prop: 'bagLocation',
          label: '最新位置',
          desc: '指托运行李的当前查询时间所在的节点状态的识读位置代号',
          width: 110,
          filterable: true,
          sortable: true,
        },
        {
          prop: 'U_Device_ID',
          label: '容器编号',
          desc: '指集装器ID信息',
          width: 110,
          filterable: true,
          sortable: true,
        },
        {
          prop: 'preFlightNO',
          label: '中转进航班',
          desc: '指有中转行李转出的进港航班号',
          width: 110,
          filterable: true,
          sortable: true,
        },
        {
          prop: 'transferFlightNO',
          label: '中转出航班',
          desc: '指有中转行李转入的离港航班号',
          width: 110,
          filterable: true,
          sortable: true,
        },
      ],
      flightDate: [
        parseTime(new Date(), '{y}-{m}-{d}'),
        parseTime(new Date(), '{y}-{m}-{d}'),
      ],
      dateRangePickerOptions: {
        onPick: this.dateRangePickHandler,
        disabledDate: this.dateRangeDisabled,
      },
      form: {
        flightNO: '',
        destination: '',
        departureStation: '',
        baggageNO: '',
        specialType: [],
        loadType: '',
        U_Device_ID: '',
        passengerName: '',
        PNR: '',
        checkInSequence: '',
        transferArrival: '',
        transferDeparture: '',
        unLoad: '',
        checkIn: '',
        active: '',
        transferIn: '',
        canceled: '',
        status: '',
        noBSM: '',
      },
      formItems: [
        {
          prop: 'flightDate',
          label: '航班日期',
          span: 16,
        },
        {
          prop: 'status',
          label: '当前状态',
        },
        {
          prop: 'flightNO',
          label: '航班号',
          hintText: '示例：CA1234',
          hintVisible: false,
        },
        {
          prop: 'departureStation',
          label: '起飞站',
          hintText: '示例：PEK',
          hintVisible: false,
        },
        {
          prop: 'destination',
          label: '目的地',
          hintText: '示例：CTU',
          hintVisible: false,
        },
        {
          prop: 'baggageNO',
          label: '行李牌号',
          hintText: '示例：1234567890 或 CA123456',
          hintVisible: false,
        },
        {
          prop: 'specialType',
          label: '特殊行李类型',
        },
        {
          prop: 'loadType',
          label: '装载类型',
        },
        {
          prop: 'U_Device_ID',
          label: '容器编号',
          hintText: '示例：AKE12345CA',
          hintVisible: false,
        },
        {
          prop: 'passengerName',
          label: '旅客姓名',
          hintText: '示例：ZHAOWEI',
          hintVisible: false,
        },
        {
          prop: 'PNR',
          label: 'PNR',
          hintText: '示例：PZR25X',
          hintVisible: false,
        },
        {
          prop: 'checkInSequence',
          label: '值机序号',
          hintText: '示例：001',
          hintVisible: false,
        },
        {
          prop: 'transferArrival',
          label: '中转进航班',
          hintText: '示例：CA1234',
          hintVisible: false,
        },
        {
          prop: 'transferDeparture',
          label: '中转出航班',
          hintText: '示例：CA1234',
          hintVisible: false,
        },
        {
          prop: 'unLoad',
          label: '翻减状态',
        },
        // {
        //   prop: 'checkIn',
        //   label: '已值机'
        // },
        {
          prop: 'active',
          label: '已激活',
        },
        {
          prop: 'transferIn',
          label: '中转行李',
        },
        {
          prop: 'canceled',
          label: '已取消',
        },
        {
          prop: 'noBSM',
          label: '无BSM',
        },
      ],
      statusList: [
        {
          statusName: '值机',
          statusCode: '值机',
        },
        {
          statusName: '安检',
          statusCode: '安检',
        },
        {
          statusName: '分拣',
          statusCode: '分拣',
        },
        {
          statusName: '装车',
          statusCode: '装车',
        },
        {
          statusName: '装机',
          statusCode: '装机',
        },
        {
          statusName: '到达',
          statusCode: '到达',
        },
        {
          statusName: '卸机',
          statusCode: '卸机',
        },
        // {
        //   statusName: '已中转',
        //   statusCode: '已中转'
        // }
      ],
      baggageTypeList: [],
      dataContent: [],
      rules: {
        // 机器信息表单验证
        // flightNO: [
        //   { required: true, message: "请输入有效航班号", trigger: "blur" },
        // ],
      },
      tableDataFilters: {},
      filterValues: {},
      tableDataSortRules: {},
      spanArr: [],
      contactDot: 0,
      scrollTop: 0,
      dom: null,
    }
  },
  computed: {
    ...mapGetters(['clickedCells', 'queryForm']),
    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])
    },
  },
  watch: {
    $route: {
      handler({ path, query }) {
        if (path === '/advance') {
          this.queryChangeHandler(query)
        }
      },
      deep: true,
    },
    flightDate: {
      handler(val) {
        if (val === null) {
          this.flightDate = ['', '']
        }
      },
      deep: true,
    },
    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'] &&
              item['passengerNameUpcase'] ===
                arr[index - 1]['passengerNameUpcase'] &&
              item['checkInNO'] === arr[index - 1]['checkInNO'] &&
              item['bagWeight'] === arr[index - 1]['bagWeight']
            ) {
              this.spanArr[contactDot] += 1
              this.spanArr.push(0)
            } else {
              this.spanArr.push(1)
              contactDot = index
            }
          }
        })
      },
      deep: 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, '')
      }
    })
  },
  mounted() {
    this.baggageTypeQuery()
    this.queryChangeHandler(this.$route.query)
    const that = this
    this.dom = this.$refs.table.bodyWrapper
    this.dom.addEventListener('scroll', () => {
      that.scrollTop = this.dom.scrollTop
    })
  },
  activated() {
    this.dom.scrollTop = this.scrollTop
    // else if (this.queryForm) {
    //   Object.keys(this.form).forEach(key => {
    //     this.form[key] = this.queryForm[key]
    //   })
    //   this.flightDate = this.queryForm.flightDate
    //   this.advancedSubmitHandler()
    // }
  },
  updated() {
    // table数据更新
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  deactivated() {
    this.loading = false
  },
  beforeDestroy() {
    this.loading = false
    //
    // if (this.$route.matched.filter(item => item.name && item.meta.title).length > 1) {
    //   this.$store.dispatch('app/setQueryForm', {
    //     ...this.form,
    //     flightDate: this.flightDate
    //   })
    // } else {
    //   this.$store.dispatch('app/setQueryForm', null)
    // }
  },
  methods: {
    load() {
      if (this.noMore || this.loading || this.page < 0) {
        return
      }
      this.advancedQuery(this.dataContent)
    },
    resetTable() {
      this.page = 0
      this.noMore = false
      this.tableData = []
    },
    dialogShow() {
      this.gjFlag = true
      this.$nextTick(() => {
        this.dialogFocus()
      })
    },
    dialogHide() {
      this.gjFlag = false
    },
    toNewAdvance() {
      this.$router.push('/advance/advanceNew')
    },
    dialogFocus() {
      this.$refs['dialog'].focus()
    },
    queryChangeHandler(query) {
      let queryFlag = false
      const { startDate, endDate, singleJump } = query
      const queryEntries = Object.entries(query)
      if (queryEntries.length) {
        this.clearForm()
      }
      queryEntries.forEach(([key, value]) => {
        if (
          !['startDate', 'endDate', 'singleJump'].includes(key) &&
          (value ?? '') !== ''
        ) {
          queryFlag = true
          this.form[key] = [
            'unLoad',
            'checkIn',
            'active',
            'transferIn',
            'canceled',
            'noBSM',
          ].includes(key)
            ? Number(value)
            : value
        }
      })
      if (startDate) {
        this.$set(this.flightDate, 0, startDate)
      }
      if (endDate) {
        this.$set(this.flightDate, 1, endDate)
      }
      if (queryFlag) {
        this.advancedSubmitHandler(singleJump)
      }
    },
    // startDateChangeHandler(val) {
    //   this.flightDate[0] = val ?? ''
    //   if (!val || !this.flightDate[1]) {
    //     return
    //   }
    //   const startDate = new Date(val)
    //   const endDate = new Date(this.flightDate[1])
    //   if (startDate > endDate) {
    //     this.flightDate.splice(1, 1, '')
    //     this.$message.info('结束时间不能早于开始时间，请重新选择')
    //   } else if (endDate - startDate > 2 * 24 * 60 * 60 * 1000) {
    //     this.flightDate.splice(1, 1, '')
    //     this.$message.info('时间跨度不能超过三天，请重新选择')
    //   }
    // },
    // endDateChangeHandler(val) {
    //   this.flightDate[1] = val ?? ''
    //   if (!val || !this.flightDate[0]) {
    //     return
    //   }
    //   const startDate = new Date(this.flightDate[0])
    //   const endDate = new Date(val)
    //   if (startDate > endDate) {
    //     this.flightDate.splice(0, 1, '')
    //     this.$message.info('开始时间不能晚于结束时间，请重新选择')
    //   } else if (endDate - startDate > 2 * 24 * 60 * 60 * 1000) {
    //     this.flightDate.splice(0, 1, '')
    //     this.$message.info('时间跨度不能超过三天，请重新选择')
    //   }
    // },
    dateRangePickHandler({ maxDate, minDate }) {
      if (!maxDate) {
        this.pickedDate = minDate
      } else {
        this.pickedDate = null
      }
    },
    dateRangeDisabled(date) {
      return this.pickedDate
        ? Math.abs(date - this.pickedDate) > 2 * 24 * 60 * 60 * 1000
        : false
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (['passengerNameUpcase', 'bagWeight'].includes(column.property)) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col,
        }
      }
    },
    // 给表头单元格加上 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.deleted === 'DEL') {
        classes.push('bgl-deleted')
      }
      return classes.join(' ')
    },
    cellClass({ row, column, rowIndex, columnIndex }) {
      const classes = []
      if (
        [
          'flightNO',
          //  'passengerNameUpcase',
          'bagSN',
          'U_Device_ID',
          'preFlightNO',
          'transferFlightNO',
        ].includes(column.property) &&
        row[column.property] &&
        row[column.property] !== 'FBULK'
      ) {
        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',
          // 'passengerNameUpcase',
          'bagSN',
          'U_Device_ID',
          'preFlightNO',
          'transferFlightNO',
        ].includes(column.property) &&
        row[column.property] &&
        row[column.property] !== 'FBULK'
      ) {
        this.$store.dispatch('keepAlive/addClickedCell', {
          row,
          columnProp: column.property,
          pageName: 'advance',
        })
        switch (column.property) {
          case 'flightNO':
            this.$router.push({
              path: '/advance/flightView',
              query: {
                flightNO: row.flightNO,
                flightDate: row.flightDate,
              },
            })
            break
          // case 'passengerNameUpcase':
          //   this.$store.dispatch('app/setPassengerQueryParams', {
          //     flightNO: row.flightNO,
          //     flightDate: row.flightDate,
          //     passengerName: row.passengerNameUpcase,
          //   })
          //   this.$store.dispatch('app/togglePassengerDialogFlag', true)
          //   break
          case 'bagSN':
            this.$router.push({
              path: '/advance/baggageView',
              query: {
                flightNO: row.flightNO,
                flightDate: row.flightDate,
                bagSN: row.bagSN,
              },
            })
            break
          case 'U_Device_ID':
            this.$router.push({
              path: '/advance/containerView',
              query: {
                flightNO: row.flightNO,
                flightDate: row.flightDate,
                departureAirport: row.sourceAirport,
                landingAirport: row.targetAirport,
                containerID: row.U_Device_ID,
              },
            })
            break
          case 'transferFlightNO':
            this.$router.push({
              path: '/advance/flightView',
              query: {
                flightNO: row.transferFlightNO,
                flightDate: row.transferFlightDate,
              },
            })
            break
          case 'preFlightNO':
            this.$router.push({
              path: '/advance/flightView',
              query: {
                flightNO: row.preFlightNO,
                flightDate: row.preFlightDate,
              },
            })
            break
          default:
            break
        }
      }
    },
    tableFormat(row, column, cellValue) {
      switch (column.property) {
        case 'departureTime':
          return (cellValue ?? '').replace('T', ' ')
        case 'deleted':
          return cellValue === 'DEL' ? cellValue : ''
        case 'activated':
          return cellValue === 1 ? '激活' : '未激活'
        default:
          return cellValue ?? ''
      }
    },
    // 查询
    getSearchData(val) {
      if (
        this.flightDate[0] === '' ||
        this.flightDate[1] === '' ||
        val === ''
      ) {
        this.$message.error('请先输入完整查询信息')
        return
      }
      this.clearForm()
      // 点击搜索后清除跳转携带的查询信息
      this.$route.query && this.$router.replace(this.$route.path)
      // let searchData = {dataContent:[this.time[0],this.time[1],val]}
      const az = /^[a-zA-Z]+$/
      const azNum = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]*$/
      // const top2 = /^[a-zA-Z]{2}\w*$/
      const top2 = /^([a-zA-Z][0-9])|([0-9][a-zA-Z])|([a-zA-Z]{2})/
      const bagNum = /^[0-9]{10}$/
      const bagNo = /^[a-zA-Z]{2}[0-9]{6}$/
      // const bagNumCA = /^CA[0-9]{6}$/
      const bagNumShort = /^[0-9a-zA-Z][a-zA-Z][0-9]{6}$/
      // 纯字母则为旅客姓名
      if (az.test(val)) {
        this.form['passengerName'] = val
        this.advancedSubmitHandler(true)
      } else if (azNum.test(val) && top2.test(val) && val.length < 8) {
        // 字母加数字且前两位为字母则为航班号
        this.form['flightNO'] = val
        this.advancedSubmitHandler(true)
      } else if (
        bagNum.test(val) ||
        bagNo.test(val) ||
        (bagNumShort.test(val) &&
          Object.keys(AIRPORT_ID).includes(val.slice(0, 2).toUpperCase()))
      ) {
        // 纯数字且位数等于10则为行李牌号
        this.form['baggageNO'] = val
        this.advancedSubmitHandler(true)
      } else {
        this.$message.error(
          '请先输入有效查询信息如航班号、旅客姓名首字母、行李牌号'
        )
      }
    },
    // 清除查询
    clearSearchData() {
      this.clearForm()
      this.resetTable()
    },
    // 清除表单
    clearForm() {
      Object.keys(this.form).forEach(key => {
        this.form[key] = ['specialType'].includes(key) ? [] : ''
      })
    },
    // 高级查询-确定
    advancedSubmitHandler(singleJump) {
      function digitFormat(num) {
        if (num) {
          num = '000' + num
          return num.slice(-3)
        } else {
          return ''
        }
      }
      function baggageFormat(baggageNO) {
        // const bagNumCA = /^CA[0-9]{6}$/
        const bagNumShort = /^[0-9a-zA-Z][a-zA-Z][0-9]{6}$/
        if (
          bagNumShort.test(baggageNO) &&
          Object.keys(AIRPORT_ID).includes(baggageNO.slice(0, 2).toUpperCase())
        ) {
          return Array.from(
            { length: 10 },
            (_, i) =>
              `${i}${
                AIRPORT_ID[baggageNO.slice(0, 2).toUpperCase()]
              }${baggageNO.slice(2)}`
          ).join()
        }
        return baggageNO || null
      }
      this.resetTable()
      /* 参数顺序
      【航班开始日期，航班结束日期，航班号，航班号，行李牌号，行李牌号，起飞站，起飞站，目的站，目的站，特殊行李类型，特殊行李类型，旅客姓名大写拼音，旅客姓名大写拼音，
      PNR，PNR，值机号，值机号，中转进航班，中转进航班，中转出航班，中转出航班，容器编号，容器编号，
      是否已翻减（null/OFF/其他），是否已翻减（null/OFF/其他），是否值机（null/0/1），是否值机（null/0/1），
      是否激活（null/0/1），是否激活（null/0/1），是否中转（null/0/1），是否中转（null/0/1），是否取消行李（null/0/1)，是否取消行李（null/0/1)】 */
      this.dataContent = []
      if (!this.flightDate?.length) {
        this.$message.error('请先选择要查询的时间')
        return
      }
      if (Object.values(this.form).every(value => value === '')) {
        this.$message.error('请先输入查询信息')
        return
      }
      this.dataContent.push(...this.flightDate)
      const {
        flightNO,
        baggageNO,
        departureStation,
        destination,
        specialType,
        passengerName,
        PNR,
        checkInSequence,
        transferArrival,
        transferDeparture,
        loadType,
        U_Device_ID,
        unLoad,
        checkIn,
        active,
        transferIn,
        canceled,
        status,
        noBSM,
      } = this.form
      this.setDataContent(
        flightNO,
        baggageFormat(baggageNO),
        departureStation,
        destination,
        specialType.map(v => v.replaceAll(',', '/')).join(),
        passengerName,
        PNR,
        digitFormat(checkInSequence),
        transferArrival,
        transferDeparture,
        U_Device_ID,
        unLoad,
        checkIn,
        active,
        transferIn,
        canceled,
        status,
        noBSM,
        loadType
      )
      this.advancedQuery(this.dataContent, singleJump)
      this.gjFlag = false
    },
    setDataContent(...dataContent) {
      dataContent.forEach(target => {
        target = typeof target === 'string' ? target.trim() : target
        if ((target ?? '') !== '') {
          this.dataContent.push(target, target)
        } else {
          this.dataContent.push(null, null)
        }
      })
    },
    // 数据查询
    async advancedQuery(dataContent, singleJump) {
      this.loading = true
      try {
        const {
          code,
          returnData: { listValues: result, needPage },
        } = await TempQuery({
          id: SERVICE_ID.advancedQueryId,
          needPage: ++this.page,
          dataContent,
        })
        if (Number(code) !== 0) {
          this.page--
          this.loading = false
          this.$message.error('获取数据失败')
          return
        }
        if (needPage === this.page && result.length) {
          if (singleJump) {
            if (result.length === 1) {
              this.$router.push({
                path: '/advance/baggageView',
                query: {
                  bagSN: result[0].bagSN,
                  flightNO: result[0].flightNO,
                  flightDate: result[0].flightDate,
                },
              })
            } else {
              const onlyFlight = result.reduce((pre, curr) => {
                if (
                  pre === null ||
                  (curr.flightNO &&
                    curr.flightDate &&
                    curr.flightNO === pre.flightNO &&
                    curr.flightDate === pre.flightDate)
                ) {
                  return {
                    flightNO: curr.flightNO,
                    flightDate: curr.flightDate,
                  }
                } else {
                  return {}
                }
              }, null)
              if (onlyFlight.flightNO) {
                this.$router.push({
                  path: '/advance/flightView',
                  query: onlyFlight,
                })
              }
            }
          }
          this.tableData = [...this.tableData, ...result]
          setTableFilters(this.tableData, this.tableDataFilters)
        } else {
          if (this.page === 1) {
            this.$message.info('未查询到匹配结果')
          }
          this.page--
          this.noMore = true
        }
      } catch (error) {
        this.page--
      }
      this.loading = false
    },
    // 特殊行李类型下拉选项查询
    async baggageTypeQuery() {
      try {
        const result = await myQuery(SERVICE_ID.baggageTypeId)
        this.baggageTypeList = result
      } catch (error) {
        this.$message.error('失败')
      }
    },
    // 统计行数
    summaryRow(num) {
      return function () {
        return ['合计', `共${num}件`]
      }
    },
    exportHandler(refName, tableName) {
      if (!this.tableData.length) {
        this.$message.info('无数据')
        return
      }
      const table = this.$refs[refName].$el.cloneNode(true)
      const fileName = `${tableName}.xlsx`
      throttledExportToExcel(table, tableName, fileName)
    },
  },
}
</script>

<style lang="scss" scoped>
.advance {
  padding: 8px;
  &__head {
    line-height: 32px;
    margin-top: 8px;
    margin-bottom: 16px;
    .btnAn:not(:last-child) {
      margin-right: 12px;
    }
    .setting {
      height: 32px;
      width: 32px;
      cursor: pointer;
      background-size: 100% 100%;
      background: url('../../../assets/baggage/ic_setting.png') no-repeat;
      margin-left: 12px;
      position: relative;
      top: 2px;
    }
    .mr10 {
      margin-right: 10px;
    }
    ::v-deep .interfaceLog_head_time {
      .el-input__prefix {
        left: 10px;
        color: #101116;
      }
      .el-input--prefix .el-input__inner {
        padding-left: 50px;
      }
    }
  }
}
.advance__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-deleted {
        background: #d2d6df;
        td {
          background: #d2d6df;
          font-style: italic;
        }
      }
    }
  }
}
.el-table tbody tr:hover > td {
  background-color: red !important;
}

.el-table__body tr.hover-row.current-row > td,
.el-table__body tr.hover-row.el-table__row--striped.current-row > td,
.el-table__body tr.hover-row.el-table__row--striped > td,
.el-table__body tr.hover-row > td {
  background-color: red;
}

.advanced-dialog::v-deep .el-form > .el-row > .el-col {
  &:nth-child(1) .el-date-editor {
    width: 100%;
  }
  .multiple-select
    .el-select__tags
    > span
    > .el-tag:first-child
    > .el-select__tags-text {
    width: 35px;
  }
}
</style>
