<template>
  <div class="advance">
    <div class="advance__head flex">
      <div class="flex-wrap interfaceLog_head_time">
        <div class="manageTitle">高级查询</div>
        <el-date-picker v-model="carrierFlightsDate" 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('queryTable', '高级查询结果')">
            导出
          </button>
          <button class="btnAn">
            <router-link to="/newQuery">切换</router-link>
          </button>
        </div>
      </Search>
    </div>
    <!--表格-->
    <div class="advance__table">
      <Table :pageSize="999" style="height:100%" ref="queryTable" :tableTag="tableTag" />
    </div>
    <!--高级查询-->
    <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 === 'carrierFlightsDate'">
                    <el-date-picker v-model="carrierFlightsDate" 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 === '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="
                      ['canLoad', 'cantransportation'].includes(
                        item.prop
                      )
                    ">
                    <el-select v-model="form[item.prop]" size="small" clearable @keyup.esc.native="dialogFocus">
                      <el-option label="是" value="Y" />
                      <el-option label="否" value="N" />
                    </el-select>
                  </template>
                  <template v-else-if="item.prop === 'No_BSM'">
                    <el-select v-model="form.noBSM" 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 === 'activeState'">
                    <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 Table from '../newQuery/components/table.vue'
import { parseTime } from '@/utils/index'
import { exportToExcel } from '@/utils/table'

export default {
  name: 'AdvancedHome',
  components: { Search, Dialog, Table },
  data () {
    return {
      loading: false,
      colDialogFlag: false,
      gjFlag: false,
      tableData: [],
      page: -1,
      noMore: false,
      checkList: [],
      dealedTableDataAll: [],
      tableFlag: false,
      carrierFlightsDate: [
        parseTime(new Date(), '{y}-{m}-{d}'),
        parseTime(new Date(), '{y}-{m}-{d}'),
      ],
      dateRangePickerOptions: {
        onPick: this.dateRangePickHandler,
        disabledDate: this.dateRangeDisabled,
      },
      form: {
        carrierFlights: '', //航班号
        carrierFlightsDate: '', //航班日期
        outAirport: '', //起飞航站
        landAirport: '', //目的航站
        luggageNum: '', //行李牌号
        specialType: '', //特殊行李类型
        dataState: '', //取消值机
        activeState: '', //行李激活状态
        container_ID: '', //容器编号
        inflightNo: '', //进港航班号
        transferFlightNO: '', //离港航班号
        PNRNO: '', //PNR编号
        luggageCount: '', //总件数
        canLoad: '', //是否可装载
        cantransportation: '', //是否可运输
        No_BSM: '' //无BSM状态
      },
      formItems: [
        {
          prop: 'carrierFlightsDate',
          label: '航班日期',
          span: 16,
        },
        {
          prop: 'carrierFlights',
          label: '航班号',
          hintText: '示例：CA1234',
          hintVisible: false,
        },
        {
          prop: 'outAirport',
          label: '起飞航站',
          hintText: '示例：PEK',
          hintVisible: false,
        },
        {
          prop: 'landAirport',
          label: '目的航站',
          hintText: '示例：CTU',
          hintVisible: false,
        },
        {
          prop: 'luggageNum',
          label: '行李牌号',
          hintText: '示例：1234567890 或 CA123456',
          hintVisible: false,
        },
        {
          prop: 'specialType',
          label: '特殊行李类型',
        },
        {
          prop: 'dataState',
          label: '取消值机',
        },
        {
          prop: 'container_ID',
          label: '容器编号',
          hintText: '示例：AKE12345CA',
          hintVisible: false,
        },
        {
          prop: 'passengerName',
          label: '旅客姓名',
          hintText: '示例：ZHAOWEI',
          hintVisible: false,
        },
        {
          prop: 'PNRNO',
          label: 'PNR',
          hintText: '示例：PZR25X',
          hintVisible: false,
        },
        {
          prop: 'activeState',
          label: '行李激活状态',
        },
        {
          prop: 'inflightNo',
          label: '进港航班号',
          hintText: '示例：CA1234',
          hintVisible: false,
        },
        {
          prop: 'transferFlightNO',
          label: '离港航班号',
          hintText: '示例：CA1234',
          hintVisible: false,
        },
        {
          prop: 'canLoad',
          label: '是否可装载',
        },
        {
          prop: 'cantransportation',
          label: '是否可运输',
        },
        {
          prop: 'No_BSM',
          label: '无BSM状态',
        },
      ],
      baggageTypeList: [],
      dataContent: [],
      rules: {
        // 机器信息表单验证
        // flightNO: [
        //   { required: true, message: "请输入有效航班号", trigger: "blur" },
        // ],
      },
      tableDataFilters: {},
      filterValues: {},
      tableDataSortRules: {},
      spanArr: [],
      contactDot: 0,
      scrollTop: 0,
      dom: null,
      tableTag: {}
    }
  },
  methods: {
    dialogShow () {
      this.gjFlag = true
      this.$nextTick(() => {
        this.dialogFocus()
      })
    },
    dialogHide () {
      this.gjFlag = false
    },
    dialogFocus () {
      this.$refs['dialog'].focus()
    },
    dateRangePickHandler ({ maxDate, minDate }) {
      if (!maxDate) {
        this.pickedDate = minDate
      } else {
        this.pickedDate = null
      }
    },
    dateRangeDisabled (date) {
      if (this.pickedDate) {
        const diff = date - this.pickedDate,
          day = 24 * 60 * 60 * 1000
        return diff < -3 * day || diff > 2 * day
      }
      return false
    },
    resetTable () {
      this.tableTag = {}
    },
    // 查询
    getSearchData (val) {
      if (
        this.carrierFlightsDate[0] === '' ||
        this.carrierFlightsDate[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 (azNum.test(val) && top2.test(val) && val.length < 8) {
        // 字母加数字且前两位为字母则为航班号
        if (val.length <= 5) {
          const len = val.length
          const lenCx = 6 - len
          val = val.substring(0, 2) + '0'.repeat(lenCx) + val.substring(2, len)
          this.$refs['search'].input = val
        }
        this.form['carrierFlights'] = 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['luggageNum'] = val
        this.advancedSubmitHandler(true)
      } else {
        this.$message.error(
          '请先输入有效查询信息如航班号、行李牌号'
        )
      }
    },
    // 清除查询
    clearSearchData () {
      this.clearForm()
      this.resetTable()
    },
    // 清除表单
    clearForm () {
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
    },
    // 高级查询-确定
    advancedSubmitHandler (singleJump) {
      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)】 */
      if (!this.carrierFlightsDate?.length) {
        this.$message.error('请先选择要查询的时间')
        return
      }
      if (Object.values(this.form).every(value => value === '')) {
        this.$message.error('请先输入查询信息')
        return
      }
      const NEW_FORM = { ...this.form }
      const NEW_PUSH = [
        {
          column: 'carrierFlightsDate',
          comparator: '>=',
          connector: '',
          left: '(',
          right: ')',
          value: this.carrierFlightsDate[0]
        },
        {
          column: 'carrierFlightsDate',
          comparator: '<=',
          connector: '',
          left: '(',
          right: ')',
          value: this.carrierFlightsDate[1]
        }
      ]
      for (const key in NEW_FORM) {
        if (Object.hasOwnProperty.call(NEW_FORM, key)) {
          const _ele = NEW_FORM[key]
          if (_ele && _ele.length) {
            const _eleObject = {
              column: key,
              comparator: '=',
              connector: '',
              left: '(',
              right: ')',
              value: _ele
            }
            NEW_PUSH.push(_eleObject)
          }
        }
      }
      this.tableTag = {
        filter: NEW_PUSH
      }
      this.gjFlag = false
    },
    exportHandler: _.throttle(
      function (refName, tableName) {
        const table = this.$refs[refName].$el.cloneNode(true)
        const fileName = `${tableName}.xlsx`
        exportToExcel(table, tableName, fileName)
      },
      2000,
      { trailing: false }
    ),
  },
}
</script>

<style lang="scss" scoped>
.advance {
  padding: 24px;
  height: calc(100vh - 80px);
  &__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%;
  height: calc(100% - 56px);
}

.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>
