<!--
 * @Author: your name
 * @Date: 2022-01-17 10:39:22
 * @LastEditTime: 2022-05-24 15:44:20
 * @LastEditors: your name
 * @Description: 行李视图
-->
<template>
  <div class="baggage-view">
    <div class="part1">
      <div class="title">
        <span>行李基本信息</span>
        <el-radio-group
          v-model="infoBtn"
          class="radioBtn"
          size="mini"
          fill="#FFFFFF"
          text-color="#28344D"
        >
          <el-radio-button
            v-for="item in infoRadios"
            :key="item"
            :label="item"
          />
        </el-radio-group>
      </div>
      <div class="part1_info">
        <el-row :gutter="12">
          <el-col
            v-for="(item, index) in baggageBasicInfoCols"
            :key="index"
            :span="[1, 4, 5].includes(index % 7) ? 4 : 3"
          >
            <span class="label">{{ item.label }}：</span><span
              class="content"
              :title="formattedBaggageInfo(item.prop)"
            >{{ formattedBaggageInfo(item.prop) }}</span>
          </el-col>
        </el-row>
      </div>
    </div>
    <div
      v-show="infoBtn === infoRadios[0]"
      class="part2"
    >
      <div class="part2_info">
        <div
          style="width: 120px"
          class="title"
        >行李跟踪信息</div>
        <div class="type normal">
          {{ baggageBasicInfo.BagStatus }}
        </div>
        <div class="step">
          <div class="baggage-track-chart">
            <div class="stepLine">
              <div
                :style="{ width: lineWidth }"
                class="stepLineBlue"
              />
            </div>
            <!-- <el-popover
              v-for="(item, index) in stepData"
              :key="index"
              :ref="'popover' + index"
              :value="popoverVisible(item)"
              :open-delay="500"
              placement="left-end"
              popper-class="popover-dark"
              trigger="manual"
            >
              <div class="pre-line">{{ messageTooltip(item.resourceFile) }}</div>
              <div
                slot="reference"
                :class="{ 'stepItem': true, activeItem: item.DealTime }"
                @mouseenter="itemMouseEnterHandler(item)"
                @mouseleave="itemMouseLeaveHandler(item)"
              >
                <span class="head">
                  <span>{{ item.NodeNameEN }}</span>
                </span>
                <span>{{ item.DealTime }}</span>
              </div>
            </el-popover> -->
            <div
              v-for="(item, index) in stepData"
              :key="index"
              :class="{ 'stepItem': true, activeItem: item.DealTime }"
              @mouseenter="itemMouseEnterHandler(item)"
              @mouseleave="itemMouseLeaveHandler(item)"
            >
              <span class="head">
                <!-- {{ item.airPort }} -->
                <!-- <span v-if="item.airPort && item.nodeName !== ''">-</span> -->
                <span>{{ item.NodeNameEN }}</span>
              </span>
              <span>{{ item.DealTime }}</span>
              <!-- <span>{{ item.time }}</span> -->
            </div>
          </div>
        </div>
      </div>
      <div class="btns">
        <img
          class="btn-square"
          src="../../../../assets/baggage/ic_export.png"
        >
        <img
          class="btn-square"
          src="../../../../assets/baggage/ic_setting.png"
          @click="show"
        >
      </div>
    </div>
    <div
      v-show="infoBtn == infoRadios[0]"
      class="part3"
    >
      <!-- <el-popover
        trigger="hover"
        placement="top-start"
        popper-class="popover-dark"
        :visible-arrow="false"
        :disabled="!messageTooltipVisible"
      >
        <div class="pre-line">{{ messageTooltip }}</div> -->
      <el-table
        ref="table"
        :data="baggageTableData"
        height="calc(100vh - 80px - 232px - 128px - 3 * 8px - 44px)"
        size="mini"
        border
        fit
        :header-cell-class-name="cellClass"
        :header-cell-style="{ color: '#101116' }"
        :cell-class-name="cellClass"
        :span-method="tableSpanMethod"
        @cell-mouse-enter="cellMouseEnterHandler"
        @cell-mouse-leave="cellMouseLeaveHandler"
      >
        <el-table-column
          v-for="item in tableColsCopy"
          :key="item.index"
          :prop="item.prop"
          :label="item.name"
          :align="item.align || 'center'"
          :width="item.width"
          show-overflow-tooltip
        >
          <template slot="header">
            <div class="cell-content">{{ item.name }}</div>
          </template>
          <template slot-scope="scope">
            <div class="cell-content">{{ scope.row[item.prop] }}</div>
          </template>
        </el-table-column>
      </el-table>
      <!-- </el-popover> -->
    </div>

    <div
      v-show="infoBtn === infoRadios[1]"
      class="part4"
    >
      <header class="head">
        <div class="title">行李跟踪信息</div>
        <div class="btns">
          <!-- <img
            class="btn-square"
            src="../../../../assets/baggage/ic_export.png"
          >
          <img
            class="btn-square"
            src="../../../../assets/baggage/ic_setting.png"
            @click="show"
          > -->
        </div>
      </header>
      <main class="main">
        <template v-if="messageList.length">
          <el-row
            :gutter="24"
            type="flex"
          >
            <el-col
              v-for="(message, index) in messageList"
              :key="index"
              :span="6"
            >
              <div class="card">
                <div class="message-date">{{ message.date }}</div>
                <div class="message-content">
                  {{ message.dataContent.replaceAll(/[\r\n]{2,}/g, '\n') }}
                  <!-- BSM <br>
              .V/1LHRB <br>
              .F/XX1640/08APR/PEK/Y <br>
              .O/ZZ941/08APR/DXB/E <br>
              .N/0666826758001 <br>
              .D/SELF//08APR/110023L//PEK30113 <br>
              .S/N/32L/C/030//Y/I <br>
              .W/K/l/0 <br>
              .P/1CUI/DI ENDBSM<br> -->
                </div>
              </div>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <el-empty
            :image-size="1"
            description="暂无数据"
          />
        </template>
      </main>
    </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: 'name',
              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/index.vue'
import { queryMap, myQuery } from '@/api/dataIntegration'
import tableColsMixin from '../../mixins/tableCols'

export default {
  name: 'BaggageView',
  components: {
    Dialog
  },
  mixins: [tableColsMixin],
  data() {
    return {
      departureAirport: '',
      landingAirport: '',
      queryData: {},
      baggageBasicInfoCols: [
        {
          label: '行李牌号',
          prop: 'bagNo'
        },
        {
          label: '航班号',
          prop: 'FlightNO'
        },
        {
          label: '企业或团队名称',
          prop: 'teamOrGroup'
        },
        {
          label: '值机位置',
          prop: 'checkInLocation'
        },
        {
          label: '特殊行李类型',
          prop: 'specialType'
        },
        {
          label: 'PNR编号',
          prop: 'PNR'
        },
        {
          label: '旅客姓名大写拼音',
          prop: 'name'
        },
        {
          label: '装载序列号',
          prop: 'loadSequenceIndex'
        },
        {
          label: '总件数',
          prop: 'totalNumber'
        },
        {
          label: '总重量',
          prop: 'totalWeight'
        },
        {
          label: '尺寸',
          prop: 'size'
        },
        {
          label: '外部特征描述',
          prop: 'externalCharacterization'
        },
        {
          label: '常旅客号',
          prop: 'frequentFlyerNumber'
        },
        {
          label: '常旅客级别',
          prop: 'frequentFlyerClass'
        },
        {
          label: '是否取消值机',
          prop: 'whetherToCancelTheCheckIn'
        },
        {
          label: '是否可装载',
          prop: 'isItLoadable'
        },
        {
          label: '是否可运输',
          prop: 'isItTransportable'
        },
        {
          label: '行李激活状态',
          prop: 'activeState'
        },
        {
          label: '无BSM状态',
          prop: 'noBSM'
        },
        {
          label: '中转标记',
          prop: 'transitSign'
        },
        {
          label: '速运标记',
          prop: 'expressSign'
        },
        {
          label: '破损标记',
          prop: 'brokenSign'
        },
        {
          label: '投诉标记',
          prop: 'complaintSign'
        },
        {
          label: '赔偿标记',
          prop: 'compensationSign'
        },
        {
          label: '异常状态',
          prop: 'bagExcType'
        }
      ],
      baggageBasicInfo: {},
      dialogVisibledele: false,
      active: 2,
      infoBtn: '跟踪信息',
      infoRadios: ['跟踪信息', '跟踪报文'],
      messageList: [
        // {
        //   content: `BSM
        //     .V/1LHRB
        //     .F/XX1640/08APR/PEK/Y
        //     .O/ZZ941/08APR/DXB/E
        //     .N/0666826758001
        //     .D/SELF//08APR/110023L//PEK30113
        //     .S/N/32L/C/030//Y/I
        //     .W/K/l/0
        //     .P/1CUI/DI ENDBSM`,
        //   date: '2022-04-25 12:42:38:00'
        // }
      ],
      // messageTooltipList: [],
      checkList: [],
      stepData: new Array(9).fill({}),
      tableCols: [
        {
          name: '航班号',
          prop: 'flightNo'
        },
        { name: '航班日期', prop: 'flightDate', width: 100 },
        {
          name: '起飞航站\n预计起飞时间',
          prop: 'departureAirport',
          width: 111
        },
        {
          name: '目的航站\n预计降落时间',
          prop: 'landingAirport',
          sortable: 'custom',
          width: 111
        },
        { name: '旅客仓位', prop: 'passengerCompartment', width: 70 },
        { name: '旅客座位号', prop: 'passengerSeatNumber' },
        { name: '值机序号', prop: 'passengerCheckInNumber', width: 70 },
        { name: '节点标识', prop: 'nodeCode', width: 100 },
        { name: '节点名称', prop: 'nodeName' },
        { name: '位置标识', prop: 'locationCode' },
        // { name: '位置码', prop: '',  },
        { name: '位置描述', prop: 'locationRemark' },
        { name: '读取时间', prop: 'dealTime', width: 158 },
        { name: '结果', prop: 'status' },
        { name: '次级代码', prop: 'secondaryCode', width: 70 },
        { name: '操作人', prop: 'AgentCode', width: 100 },
        { name: '设备ID', prop: 'DeviceCode' },
        { name: '发往位置', prop: 'toLocation' },
        { name: '发往位置描述', prop: 'toLocationMark', width: 110 },
        { name: '装载序号', prop: 'LoadSN' },
        { name: '容器编号', prop: 'U_Device_ID', width: 100 }
      ],
      baggageTableData: [],
      spanArr: [],
      pos: 0,
      hoveredRow: null,
      loopEvent: null,
      queryMessageLoop: null
    }
  },
  computed: {
    lineWidth() {
      for (let i = this.stepData.length - 1; i > -1; i--) {
        if (this.stepData[i].DealTime) {
          return (i * 100) / (this.stepData.length - 1) + '%'
        }
      }
      return 0
    },
    // messageTooltip() {
    //   return function (resourceFile) {
    //     const message = this.messageTooltipList.find(message => message.resourceFile === resourceFile)
    //     return message ? `${message.date}\n${message.dataContent.replaceAll(/[\r\n]{2,}/g, '\n')}` : ''
    //   }
    // },
    // popoverVisible() {
    //   return function (item) {
    //     return (
    //       (item.hover || item.tableHover) &&
    //       this.messageTooltipList.some(message => message.resourceFile === item.resourceFile)
    //     )
    //   }
    // },
    formattedBaggageInfo() {
      return function (prop) {
        const value = this.baggageBasicInfo[prop]
        if ((value ?? '') === '') {
          return ''
        } else if (prop === 'transitSign') {
          return Number(value) === 1 ? '中转' : '非中转'
        } else if (
          [
            'whetherToCancelTheCheckIn',
            'isItLoadable',
            'isItTransportable',
            'activeState',
            'noBSM',
            'expressSign',
            'brokenSign',
            'complaintSign',
            'compensationSign',
            'bagExcType'
          ].includes(prop)
        ) {
          return Number(value) === 1 || String(value) === 'Y' ? '是' : '否'
        } else {
          return value
        }
      }
    }
  },
  watch: {
    infoBtn(val) {
      const that = this
      if (val === '跟踪报文') {
        clearInterval(this.loopEvent)
        this.loopEvent = null
        this.baggageMessageQuery()
        this.queryMessageLoop = setInterval(function () {
          that.baggageMessageQuery()
        }, 5000)
      } else {
        clearInterval(this.queryMessageLoop)
        this.queryMessageLoop = null
        this.queryBaggageAll()
        this.loopEvent = setInterval(function () {
          that.queryBaggageAll()
        }, 3000)
      }
    },
    hoveredRow: {
      handler(row) {
        this.stepData.forEach(item => {
          item.tableHover = row && item.resourceFile === row.resourceFile
        })
      },
      deep: true
    }
  },
  mounted() {
    this.queryData = this._.cloneDeep(this.$route.query)
    // console.log(this.queryData)
    const that = this
    this.queryBaggageAll()
    this.loopEvent = setInterval(function () {
      that.queryBaggageAll()
    }, 3000)
  },
  updated() {
    this.$refs['table']?.doLayout()
  },
  beforeDestroy() {
    clearInterval(this.loopEvent)
    this.loopEvent = null
    clearInterval(this.queryMessageLoop)
    this.queryMessageLoop = null
  },
  methods: {
    // objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //   if (columnIndex < 4) {
    //     const _row = this.spanArr[rowIndex]
    //     const _col = _row > 0 ? 1 : 0
    //     return {
    //       rowspan: _row,
    //       colspan: _col
    //     }
    //   }
    // },
    initTableData(tableData) {
      const spanArr = []
      let pos = 0
      for (let i = 0; i < tableData.length; i++) {
        if (i === 0) {
          spanArr.push(1)
        } else {
          if (
            tableData[i]['flightNo'] === tableData[i - 1]['flightNo'] &&
            tableData[i]['flightDate'] === tableData[i - 1]['flightDate'] &&
            tableData[i]['departureAirport'] === tableData[i - 1]['departureAirport'] &&
            tableData[i]['landingAirport'] === tableData[i - 1]['landingAirport']
          ) {
            spanArr[pos] += 1
            spanArr.push(0)
          } else {
            spanArr.push(1)
            pos = i
          }
        }
      }
      this.spanArr = spanArr
      this.pos = pos
    },
    cellClass({ row, column, rowIndex, columnIndex }) {
      if (['departureAirport', 'landingAirport'].includes(column.property)) {
        return 'pre-line'
      }
    },
    tableSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (['flightNo', 'flightDate', 'departureAirport', 'landingAirport'].includes(column['property'])) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    itemMouseEnterHandler(item) {
      if (item.resourceFile) {
        // this.checkBaggageMessage(item.resourceFile)
        item.hover = true
      }
    },
    itemMouseLeaveHandler(item) {
      item.hover = false
    },
    cellMouseEnterHandler(row, column, cell, event) {
      if (row?.resourceFile) {
        // this.checkBaggageMessage(row.resourceFile)
      }
      this.hoveredRow = row
    },
    cellMouseLeaveHandler() {
      // this.hoveredRow = null
    },
    async checkBaggageMessage(resourceFile) {
      if (!this.messageTooltipList.some(message => message.resourceFile === resourceFile)) {
        const result = await this.queryMessage([resourceFile])
        this.messageTooltipList.push({
          ...result[0],
          resourceFile
        })
      }
    },
    // 行李详情基础信息
    queryBaggageBasicInfo(dataContent) {
      return myQuery(queryMap.baggageBasicInfoByID, ...dataContent)
    },
    // 行李详情追踪链
    queryBaggageTrack(dataContent) {
      return myQuery(queryMap.baggageTrackByID, ...dataContent)
    },
    // 行李详情表格
    queryBaggageDetails(dataContent) {
      return myQuery(queryMap.baggageDetailsByID, ...dataContent)
    },
    // 原始报文
    queryMessage(dataContent) {
      return myQuery(queryMap.message, ...dataContent)
    },
    async queryBaggageAll(queryData = this.queryData) {
      const { FlightNO, FlightDate, BagSN } = queryData
      const dataContent = [FlightNO, FlightDate, BagSN]
      try {
        const [
          baggageBasicInfo,
          // baggageTrack,
          baggageDetails
        ] = await Promise.all([
          this.queryBaggageBasicInfo(dataContent),
          // this.queryBaggageTrack(new Array(2).fill(dataContent).flat()),
          this.queryBaggageDetails(new Array(6).fill(dataContent).flat())
        ])
        if (baggageBasicInfo.length) {
          baggageBasicInfo[0].FlightNO = FlightNO
          this.baggageBasicInfo = baggageBasicInfo[0]
        }
        this.baggageTableData = baggageDetails.map((item, index) => {
          const { hover, tableHover } = this.stepData[index] ?? {}
          this.stepData.splice(index, 1, {
            NodeNameEN: item.nodeCode,
            DealTime: item.dealTime.replace('T', '\n'),
            resourceFile: item.resourceFile,
            hover: !!hover,
            tableHover: !!tableHover
          })

          if (item['dealTime'].split('T').length > 1) {
            item['dealTime'] = item['dealTime'].replace('T', ' ')
          }
          item['departureAirport'] = `${item['departureAirport']}\n${item['departureTime'].replace('T', '\n')}`
          item['landingAirport'] = `${item['landingAirport']}\n${item['landingTime'].replace('T', '\n')}`
          return item
        })
        this.initTableData(this.baggageTableData)
      } catch (error) {
        console.log('错误', error)
      }
    },
    async baggageMessageQuery() {
      const { FlightNO, FlightDate, BagSN } = this.queryData
      const dataContent = [FlightNO, FlightDate, BagSN]
      try {
        const result = await this.queryMessage(dataContent)
        this.messageList = result
      } catch (error) {
        console.log('出错了', error)
      }
    }
  }
}
</script>
<style lang="scss">
.radioBtn {
  padding: 5px;
  background: #000d2a;
  .el-radio-button__inner {
    background: #000d2a;
    color: #fff;
    border: none;
    font-weight: bold;
  }
  .el-radio-button:first-child .el-radio-button__inner {
    border: none;
  }
}
</style>
<style lang="scss" scoped>
.baggage-view {
  width: 100%;
  height: calc(100vh - 81px);
  overflow: hidden;
  background: #dfe3ea;
  padding: 8px 8px 0;
  .part1 {
    width: 100%;
    height: 232px;
    background: #041741;
    padding: 16px 30px;
    .title {
      font-size: 18px;
      font-weight: bold;
      color: #ffffff;
      width: 320px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
    }
    .part1_info {
      width: 100%;
      color: #fff;
      font-size: 14px;
      font-weight: 400;
      color: #ffffff;
      > .el-row > .el-col {
        height: 38px;
        line-height: 38px;
        display: flex;
        .label {
          flex-basis: 126px;
          text-align: right;
        }
        .content {
          flex: 1;
          margin: 0;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
  .part2 {
    margin: 8px 0;
    width: 100%;
    padding: 24px 30px;
    background: #ffffff;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .part2_info {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      .title {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
        margin-right: 42px;
      }
      .type {
        font-size: 18px;
        font-weight: bold;
        margin-right: 80px;
      }
      .warn {
        color: #df3559;
      }
      .normal {
        color: #519f6b;
      }
      .step {
        height: 80px;
        width: 1430px;
        position: relative;
        .baggage-track-chart {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          overflow-x: scroll;
          overflow-y: hidden;
          > span {
            z-index: 1;
          }
        }
        .stepLine {
          width: 100%;
          height: 20px;
          background: #afb4bf;
          position: absolute;
          top: 50%;
          margin-top: -10px;
          border-radius: 10px;
          .stepLineBlue {
            position: absolute;
            height: 100%;
            background: #041741;
            border-radius: 10px;
          }
        }
        .stepItem {
          width: 80px;
          height: 80px;
          background: #afb4bf;
          border-radius: 50%;
          text-align: center;
          font-weight: bold;
          color: #ffffff;
          font-size: 12px;
          display: flex;
          flex-direction: column;
          align-content: space-around;
          align-items: center;
          // padding-top: 19px;
          justify-content: center;
          .head {
            font-size: 14px;
          }
        }
        .activeItem {
          background: #041741;
        }
      }
    }
  }
  .part3 {
    width: 100%;
    // header-80px、part1-232px、part2-128px、间隙3*8px、底部44px
    height: calc(100vh - 80px - 232px - 128px - 3 * 8px - 44px);
    background: #ffffff;
    ::v-deep .el-table {
      width: 100%;
      // &.el-table--striped {
      //   .el-table__body tr.el-table__row--striped td.el-table__cell,
      //   .el-table__header .el-table__cell {
      //     background: #ffffff;
      //   }
      // }
      .el-table__cell {
        // background: #f0f3f7;
        padding: 0;
        .cell {
          padding: 0;
          word-spacing: 0;
          font-size: 14px;
          font-family: Helvetica, 'Microsoft YaHei';
          font-weight: 400;
          color: #303133;
          .cell-content {
            padding: 6px 0;
          }
        }
      }
      .el-table__body .el-table__cell .cell {
        padding: 6px 10px;
        .cell-content {
          display: inline;
          padding: 0;
        }
      }
    }
  }
  .part4 {
    width: 100%;
    height: calc(100vh - 80px - 232px - 2 * 8px - 44px);
    .head {
      padding: 16px 24px 11px 30px;
      background: transparent;
      display: flex;
      justify-content: space-between;
      .title {
        line-height: 30px;
        font-size: 18px;
        font-weight: bold;
        color: #303133;
      }
    }
    .main {
      height: calc(100% - 57px);
      overflow-y: auto;
      overflow-x: hidden;
      ::v-deep .el-row {
        flex-wrap: wrap;
        .card {
          width: 100%;
          min-height: 440px;
          padding: 24px 0 24px 32px;
          background: #ffffff;
          box-shadow: 0px 3px 2px 0px rgba(0, 0, 0, 0.29);
          margin-bottom: 24px;
          > .message-date {
            width: 160px;
            height: 26px;
            line-height: 14px;
            font-size: 14px;
            font-family: Helvetica;
            color: #afb4bf;
            border-bottom: 1px solid #afb4bf;
            margin-bottom: 18px;
          }
          > .message-content {
            white-space: pre-line;
            line-height: 24px;
            font-size: 14px;
            color: #303133;
          }
        }
      }
    }
  }
  .btns {
    height: 30px;
    display: flex;
    .btn-square {
      margin-left: 10px;
      width: 30px;
      cursor: pointer;
    }
  }
}
</style>

<style lang="scss">
.el-popover {
  &.popover-dark {
    background: #303133;
    color: #ffffff;
    border: none;
  }
  .pre-line {
    white-space: pre-line;
  }
}
.el-popper[x-placement^='top'].popover-dark .popper__arrow::after {
  border-top-color: #303133;
}
.el-popper[x-placement^='right'].popover-dark .popper__arrow::after {
  border-right-color: #303133;
}
.el-popper[x-placement^='bottom'].popover-dark .popper__arrow::after {
  border-bottom-color: #303133;
}
.el-popper[x-placement^='left'].popover-dark .popper__arrow::after {
  border-left-color: #303133;
}
</style>
