<template>
  <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="baggageView">
    <el-scrollbar style="height: 100%">
      <div v-infinite-scroll="load" class="baggageView-content">
        <div v-for="(item,index) in tableData" :key="index" class="baggageView-list">
          <div class="part2">
            <div class="part2_info">
              <div class="title">
                <div class="fightNo">{{ item.carrierFlights || item.inflightNo }}</div>
                <div class="fightDate">{{ item.carrierFlightsDate || item.inflightDate }}</div>
                <div class="fightLine">{{ item.outAirport }}{{ item.takeoff_terminal }} -- {{item.landAirport}}{{ item.target_terminal }}</div>
                <div class="fightTime">{{ item.takeTime }} -- {{ item.landTime }}</div>
              </div>
              <div class="baggage-track-chart">
                <div class="step-line">
                  <div v-for="(line, index) in 6" :key="index" :class="['step-line-segment', { 'step-line-active': activeStepLine(index,item.bagStatus) }]"></div>
                </div>
                <div v-for="(p, cindex) in item.bagStatus" :key="cindex" :class="{ 'step-item': true, 'active-item': p.timeValue }">
                  <div :class="activeStepLineDanger(cindex,item)" class="step-circle">
                    <span class="step-name">{{ p.nodeName }}</span>
                  </div>
                  <div v-if="p.timeValue || p.stateValue || p.loclValue || p.fourSecurity" class="step-info">
                    <div :class="statusClasses(p.stateValue)">{{ p.stateValue }}</div>
                    <span class="step-time">{{ p.timeValue }}</span>
                    <div class="step-location">{{ p.loclValue }}</div>
                    <div :class="statusClasses(p.fourSecurity)">{{ p.fourSecurity }}</div>
                  </div>
                  <div v-else class="step-info">无</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
import pf from '@/layout/mixin/publicFunc'
export default {
  name: 'BaggageView',
  mixins: [pf],
  props: {
    queryObj: {
      type: Object,
      default: () => { }
    },
    tagObj: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      stepNodes: [
        {
          nodeCode: 'CHECKIN',
          nodeName: '值机',
          timeProp: 'checkInDate',
          timeValue: '',
          loclProp: 'checkInLocation',
          loclValue: '',
          stateProp: 'checkState',
          stateValue: '',
        },
        {
          nodeCode: 'SECURITY',
          nodeName: '安检',
          timeProp: 'security_check_time',
          timeValue: '',
          loclProp: 'security_location',
          loclValue: '',
          stateProp: 'securityInspectionResults',
          stateValue: '',
        },
        {
          nodeCode: 'SORT',
          nodeName: '分拣',
          timeProp: 'sorting_time',
          timeValue: '',
          loclProp: 'sorting_location',
          loclValue: '',
          stateProp: 'sortState',
          stateValue: '',
        },
        {
          nodeCode: 'LOAD',
          nodeName: '装车',
          timeProp: 'loading_time',
          timeValue: '',
          loclProp: 'installationAddress',
          loclValue: '',
          stateProp: 'loadState',
          stateValue: '',
        },
        {
          nodeCode: 'INFL',
          nodeName: '装机',
          timeProp: 'installation_time',
          timeValue: '',
          loclProp: 'installation_location',
          loclValue: '',
          stateProp: 'normal',
          stateValue: '',
        },
        {
          nodeCode: 'UNLOAD',
          nodeName: '卸机',
          timeProp: 'unloadtime',
          timeValue: '',
          loclProp: 'unloadLocation',
          loclValue: '',
          stateProp: 'normal',
          stateValue: '',
        },
        {
          nodeCode: 'ARRIVED',
          nodeName: '到达',
          timeProp: 'arrivedtime',
          timeValue: '',
          loclProp: 'arrviedLocation',
          loclValue: '',
          stateProp: 'normal',
          stateValue: '',
        }
      ],
      tableData: [],
      tableDataCopy: [],
      page: 0,
      pageSize: 20,
      dataContent: {},
      loading: false,
      noMore: false
    }
  },
  computed: {
    activeStepLine () {
      return function (index, arrs) {
        return (arrs[index].stateValue || arrs[index].loclValue || arrs[index].timeValue) && (arrs[index + 1].stateValue || arrs[index + 1].loclValue || arrs[index + 1].timeValue)
      }
    },
    activeStepLineDanger () {
      return function (index, item) {
        function diffMinutes () {
          const { takeTime } = item
          const [hour, minutes] = takeTime?.split(':')
          if (minutes - 15 >= 0) {
            return `${hour}: ${minutes - 15 >= 10 ? minutes - 15 : '0' + (minutes - 15)}`
          } else {
            if (hour - 1 > 0) {
              return `${hour - 1}:${minutes - 15 + 60 >= 10 ? minutes - 15 + 60 : '0' + (minutes - 15 + 60)}`
            } else {
              return `23:${minutes - 15 + 60 >= 10 ? minutes - 15 + 60 : '0' + (minutes - 15 + 60)}`
            }
          }
        }
        const arrs = item.bagStatus
        const { stateProp, stateValue } = arrs[index]
        if (stateProp == 'securityInspectionResults' && stateValue == 'UCL') {
          if (arrs[index + 1].stateValue || arrs[index + 1].loclValue || arrs[index + 1].timeValue || arrs[index + 2].stateValue || arrs[index + 2].loclValue || arrs[index + 2].timeValue) {
            return 'step-circle-waring'
          } else {
            return 'step-circle-danger'
          }
        }
        // if (stateProp == 'securityInspectionResults' && !stateValue) {
        //   if (this.tableData.length >= 2 || arrs[index + 1].stateValue || arrs[index + 1].loclValue || arrs[index + 1].timeValue || arrs[index + 2].stateValue || arrs[index + 2].loclValue || arrs[index + 2].timeValue) {
        //     return 'step-circle-waring'
        //   }
        // }
      }
    },
    statusClasses () {
      return function (status) {
        const classes = ['step-status']
        if (typeof status === 'string') {
          if (status.includes('不正常') || status.includes('不通过')) {
            classes.push('step-status-abnormal')
          }
          else if (status.includes('正常') || status.includes('通过')) {
            classes.push('step-status-normal')
          }
          else {
            classes.push('step-status-abnormal')
          }
        }
        return classes
      }
    }
  },
  watch: {
    tagObj: {
      handler (obj) {
        this.dataContent = obj
        this.restTable()
        this.load()
      },
      deep: true
    },
    queryObj: {
      handler (obj) {
        this.tableDataCopy = []
        this.tableData = []
        this.dataContent = obj
        this.restTable()
        this.load()
      },
      deep: true
    },
  },
  created () {
    this.dataContent = this.queryObj
  },
  methods: {
    //获取行李信息
    async getLuggageList (id, dataContent = this.dataContent, page, pageSize) {
      try {
        this.loading = true
        const { code, returnData } = await this.getQueryList(id, dataContent, page, pageSize)
        if (code == 0) {
          if (returnData.length === 0) {
            this.page--;
            this.noMore = true;
            this.loading = false;
          }
          returnData.forEach(item => {
            item.bagStatus = _.cloneDeep(this.stepNodes)
          })
          this.tableDataCopy.push(...returnData)
          // this.tableDataCopy = _.uniqBy(this.tableDataCopy, 'ID')
          // this.tableDataCopy = this.tableDataCopy.sort((a, b) => Date.parse(a.carrierFlightsDate) - Date.parse(b.carrierFlightsDate))
          this.tableDataCopy.forEach(item => {
            item.bagStatus.map(p => {
              const { timeProp, loclProp, stateProp } = p
              if (item.hasOwnProperty(timeProp) || item.hasOwnProperty(loclProp) || item.hasOwnProperty(stateProp)) {
                p.timeValue = item[timeProp]
                p.loclValue = item[loclProp]
                p.stateValue = item[stateProp]
              }
            })
          })
          this.getBagTime(this.tableDataCopy)
          this.loading = false
        } else {
          this.page--
          this.loading = false
          this.$message.error("获取表格数据失败")
        }
      } catch (error) {
        this.loading = false;
        console.log(error)
      }
    },
    statusSecurity (item) {
      const { securityInspectionResults, security_location } = item
      const securityNums = ['XSA001', 'XSA003', 'XSB001', 'XSB004']
      // if (securityInspectionResults == 'CLR') return securityInspectionResults
      // if (securityInspectionResults == 'UCLR') return securityInspectionResults
      if (securityNums.includes(security_location)) return 'ULR'
      else return securityInspectionResults
    },
    restTable () {
      this.loading = false
      this.noMore = false
      this.page = 0
      this.tableData = []
    },
    load () {
      if (Object.keys(this.queryObj).length || Object.keys(this.tagObj).length) {
        if (this.noMore || this.loading) {
          return;
        }
        this.getLuggageList(SERVICE_ID.bagTableDqId, this.dataContent, ++this.page, this.pageSize);
      }
    },
    async getBagTime (arr) {
      const newArr = [...arr]
      const reqUrls = []
      newArr.forEach(item => {
        const { carrierFlights, carrierFlightsDate, outAirport, landAirport, bagStatus } = item
        const index = bagStatus.findIndex(citem => citem.stateProp == 'securityInspectionResults')
        if (index > -1) {
          bagStatus[index]['stateValue'] = this.statusSecurity(item)
          bagStatus[index]['fourSecurity'] = item.fourSecurity
        }
        const reqItem = this.getQueryList(SERVICE_ID.baggageTime, {
          carrierFlights,
          carrierFlightsDate,
          outAirport,
          landAirport
        })
        reqUrls.push(reqItem)
      })
      const allReqs = await Promise.allSettled(reqUrls)
      allReqs.forEach((item, index) => {
        const { status, value } = item
        if (status == 'fulfilled') {
          const { returnData } = value
          const newArray = [...returnData]
          if (newArray && newArray.length) {
            const itemObj = newArray[0]
            const newObj = {}
            const { actualTakeOffTime, estimateTakeOffTime, scheduleTakeOffTime, actualLandInTime, estimateLandInTime, scheduleLandInTime } = itemObj
            newObj.newTakeoff_time = actualTakeOffTime ? actualTakeOffTime : estimateTakeOffTime ? estimateTakeOffTime : scheduleTakeOffTime
            newObj.newLand_time = actualLandInTime ? actualLandInTime : estimateLandInTime ? estimateLandInTime : scheduleLandInTime
            newObj.takeTime = newObj.newTakeoff_time?.split('T').at(-1)
            newObj.landTime = newObj.newLand_time?.split('T').at(-1)
            newArr[index] = Object.assign(newArr[index], newObj)
          }
        }
      })
      this.tableData = _.orderBy([...newArr], ["carrierFlightsDate", "takeTime"], ["asc"]);
    }
  }
}
</script>

<style lang="scss" scoped>
.baggageView {
  height: 100%;
  &-list {
    height: 183px;
    border-bottom: 1px solid #dfe3ea;
    padding: 30px 32px 47px 32px;
    &:last-child {
      border-bottom: none;
    }
    .part2 {
      width: 100%;
      background: #ffffff;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: flex-start;
      .part2_info {
        flex: 1;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: flex-start;
        line-height: 42px;

        .title {
          width: 160px;
          margin-right: 30px;
          font-size: 14px;
          font-family: Helvetica;
          font-weight: 400;
          color: #101116;
          line-height: 1;
          .fightNo {
            font-size: 24px;
            font-family: Helvetica;
            font-weight: bold;
            margin-bottom: 8px;
          }
          .fightDate {
            margin-bottom: 15px;
          }
          .fightLine {
            margin-bottom: 8px;
          }
          .fightTime {
            margin-top: 13px;
          }
        }
        .type {
          font-size: 18px;
          font-weight: bold;
          margin-right: 20px;
          .warn {
            color: #df3559;
          }
          .normal {
            color: #519f6b;
          }
        }
        .airline {
          width: 120px;
          margin-right: 20px;
        }
        .baggage-track-chart {
          flex: 1;
          height: 124px;
          position: relative;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          width: 100%;
        }
        .step-line {
          width: calc(100% - 80px);
          height: 10px;
          position: absolute;
          top: 16px;
          right: 0;
          left: 0;
          margin: auto;
          display: flex;
          .step-line-segment {
            width: calc(100% / 6);
            height: 100%;
            background: #afb4bf;
            &.step-line-active {
              background: #2d67e3;
            }
          }
        }
        .step-item {
          width: 80px;
          height: 100%;
          text-align: center;
          font-size: 14px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: flex-start;
          z-index: 1;
          font-family: Helvetica, "Microsoft Yahei";
          .step-circle {
            width: 42px;
            height: 42px;
            border-radius: 50%;
            background: #aaacb2;
            .step-name {
              color: #ffffff;
              font-size: 14px;
              font-weight: bold;
            }
          }
          .step-info {
            margin-top: 8px;
            color: #101116;
            line-height: 22px;
            .step-status {
              &-normal {
                color: #4ab36f;
              }
              &-abnormal {
                color: #e9af4b;
              }
            }
            .step-time {
              white-space: pre-line;
              font-size: 12px;
              line-height: 20px;
            }
          }
          &.active-item .step-circle {
            background: #2d67e3;
          }
          .step-circle-danger {
            background: #ff3303 !important;
          }
          .step-circle-waring {
            background: #2d67e3;
          }
        }
      }
      .btns {
        margin-top: 6px;
      }
    }
  }
}
</style>