<template>
  <div style="width: 100%;height: 100%;min-height: 400px">
    <div v-if="!isHistory">
      <div style="display: flex;margin-bottom: 10px">
        <el-button @click="changeTime(1)">7天</el-button>
        <el-button @click="changeTime(2)">一个月</el-button>
        <el-button @click="changeTime(3)">3个月</el-button>
        <el-button @click="changeTime(4)">12个月</el-button>
      </div>
      <el-row style="display: flex;align-items: center">
        <el-col :span="14" class="track-btn">
          <el-date-picker clear-icon="el-icon-error"
                          v-model="locusStartDate"
                          placement="bottom"
                          type="datetime">
          </el-date-picker>
          <span>-</span>
          <el-date-picker clear-icon="el-icon-error"
                          v-model="locusEndDate"
                          type="datetime"
                          placement="bottom">
          </el-date-picker>
        </el-col>
        <!--        <el-col :span="5">-->
        <!--          <el-button style="height: 2.5rem;width:  6.5rem" v-loading="searchLoading" @click="search(1)">-->
        <!--            <span>{{ $t('message.trackRecord.history') }}</span>-->
        <!--          </el-button>-->
        <!--        </el-col>-->
        <el-col :span="5">
          <el-button style="height: 2.5rem;width: 6.5rem;" v-loading="search2Loading" @click="search(2)">
            <span>{{ $t('message.trackRecord.history') }}</span></el-button>
        </el-col>
      </el-row>
    </div>
    <div class="track-history-box">
      <el-table @row-click="selectTableDataCell"
                :data="tableData"
                ref="trackTable"
                :empty-text="$t('message.trackRecord.noData')"
                style="width: 100%"
                :height="tableHeight"
                :header-cell-style="{'background-color': '#94A1CC',color: '#ffffff'}"
                :row-style="{ cursor: 'pointer', padding: '0' }">
        <el-table-column prop="shipnameEn"
                         :label="$t('message.trackRecord.voyageList')"
                         width="120"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="startTime"
                         :label="$t('message.trackRecord.startTime')"
                         width="160"
                         align="center">
        </el-table-column>
        <el-table-column prop="endTime"
                         :label="$t('message.trackRecord.endTime')"
                         align="center"
                         width="160">
        </el-table-column>
        <el-table-column align="center">
          <template slot="header">
            <el-button
              style="background: rgba(238, 44, 44,0.7)!important;color: #FFFFFF!important;border: none!important;width: 5rem"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click.native.stop="deleteTableData">
              <span>{{ $t('message.trackRecord.delete') }}</span>
            </el-button>
          </template>
          <template slot-scope="scope">
            <el-button style="color: red; cursor: pointer;border: none"
                       @click.native.stop="delectShipLocus(scope.$index, tableData)">
              <span>{{ $t('message.trackRecord.delete') }}</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Watch} from 'vue-property-decorator'
import storeUtil from '@/util/store'
import MessageUtil from '@/util/message'
import HttpApi from '@/api'
import {getBeforeTime, getNowTime} from '@/util/date'
import dayjs from "dayjs";
import bus from "@/util/bus"

const elementResizeDetectorMaker = require('element-resize-detector')

@Component({
  props: {
    shipData: {
      type: Object,
      required: true,
      default: {}
    },
    isHistory: {
      type: Boolean,
      required: false
    }
  }
})
export default class TrackRecord extends Vue {
  private visible = false
  private locusStartDate = ''
  private locusEndDate = ''
  private tableData: any[] = []
  private shipPathList: any[] = []
  private isShowPath = false
  private ship: any = null
  private shipFun: any = storeUtil.getMapFun()
  private searchLoading = false
  private search2Loading = false
  private tableHeight = 250

  /**
   * 获取船舶信息参数
   * @param data
   */
  @Watch('shipData', {
    immediate: true,
    deep: true
  })
  dataChange(data: any) {
    if (data) {
      this.ship = data
    }
  }

  @Watch('isHistory', {
    deep: true,
    immediate: true
  })
  historyChange(data: any) {
    if (data) {
      this.tableData = this.$store.state.shipHistoryLog
    }
  }

  private changeTime(val: number) {
    const nowTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    switch (val) {
      case 1: {
        const startTime = dayjs(nowTime).subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss');
        this.locusEndDate = nowTime
        this.locusStartDate = startTime
      }
        break
      case 2: {
        const startTime = dayjs(nowTime).subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss');
        this.locusEndDate = nowTime
        this.locusStartDate = startTime
      }

        break
      case 3: {
        const startTime = dayjs(nowTime).subtract(3, 'month').format('YYYY-MM-DD HH:mm:ss');
        this.locusEndDate = nowTime
        this.locusStartDate = startTime
      }
        break
      case 4: {
        const startTime = dayjs(nowTime).subtract(12, 'month').format('YYYY-MM-DD HH:mm:ss');
        this.locusEndDate = nowTime
        this.locusStartDate = startTime
      }
        break
    }
  }

  public mounted() {
    const erd = elementResizeDetectorMaker()
    erd.listenTo((this.$refs.trackTable as any).$parent.$el, () => {
      this.tableHeight = (this.$refs.trackTable as any).$parent.$el.clientHeight - 90
    })
    this.changeTime(1)
  }
  public beforeDestroy() {
    //销毁时显示所有车船
    bus.$emit('showAllData')
  }
  /**
   * 搜索历史轨迹
   * @private
   */
  private search(level: number) {
    if (this.ship === null) {
      MessageUtil.warring('请选中船舶再进行查询')
      return
    }
    let start = new Date(this.locusStartDate)
    let end = new Date(this.locusEndDate)
    const timestamp = (end.getTime() - start.getTime())
    const days = timestamp / 1000 / (3600 * 24)
    if (this.tableData && this.tableData.length) {
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i]
        if ((item.startTime === this.locusStartDate) &&
          (this.locusEndDate === item.endTime) &&
          (this.ship.shipnameEn === item.shipnameEn)) {
          MessageUtil.info('轨迹列表中已存在该时间段内的轨迹信息')
          return
        }
      }
    }
    let startTime = parseInt(Number(new Date(this.locusStartDate).getTime()) / 1000 + '')
    let endTime = parseInt(Number(new Date(this.locusEndDate)) / 1000 + '')
    const param: any = {
      shipId: this.ship.shipId,
      startTime: startTime,
      endTime: endTime
    }
    if (level === 1) {
      if (days < 30) {
        this.searchLoading = true
        HttpApi.getHistoryTrack(param).then((res: any) => {
          if (res.length) {
            let pathId = this.showShipPath(res)
            this.tableData.unshift({
              id: this.ship.shipId,
              shipnameEn: this.ship.shipnameEn,
              startTime: dayjs(this.locusStartDate).format('YYYY-MM-DD HH:mm:ss'),
              endTime: dayjs(this.locusEndDate).format('YYYY-MM-DD HH:mm:ss')
            });
            (this as any).$HistoryLog.push({
              id: this.ship.shipId,
              shipnameEn: this.ship.shipnameEn,
              startTime: this.locusStartDate,
              endTime: this.locusEndDate,
              points: res
            })
            this.shipFun.clearallship()
            this.searchLoading = false
          } else {
            MessageUtil.info('暂无当前船舶轨迹信息')
            this.searchLoading = false
          }
        })
      } else {
        MessageUtil.info('普通查询只能查询30天内的数据')
      }

    } else if (level === 2) {
      const start2 = new Date(startTime * 1000)
      const end2 = new Date(endTime * 1000)
      let startTime2 = ''
      let endTime2 = ''
      const month = (start2.getMonth() + 1)
      const endMonth = (end2.getMonth() + 1)
      const day = (start2.getDate())
      const endDay = (end2.getDate())
      if (month < 10) {
        startTime2 = start2.getFullYear() + '0' + month
      } else {
        startTime2 = start2.getFullYear() + '' + month
      }

      if (day < 10) {
        startTime2 = startTime2 + '0' + '' + day
      } else {
        startTime2 = startTime2 + '' + day
      }

      if (endMonth < 10) {
        endTime2 = end2.getFullYear() + '0' + endMonth
      } else {
        endTime2 = end2.getFullYear() + '' + endMonth
      }

      if (endDay < 10) {
        endTime2 = endTime2 + '0' + '' + endDay
      } else {
        endTime2 = endTime2 + '' + endDay
      }

      if (days < 366) {
        const params = {
          shipId: this.ship.shipId,
          startDate: startTime2,
          endDate: endTime2,
          interval: 1
        }
        this.search2Loading = true
        HttpApi.getShipHistoryInterval(params).then((res: any) => {
          if (res && res.length) {
            this.showShipPath(res)
            this.tableData.unshift({
              id: this.ship.shipId,
              shipnameEn: this.ship.shipnameEn,
              startTime: dayjs(this.locusStartDate).format('YYYY-MM-DD HH:mm:ss'),
              endTime: dayjs(this.locusEndDate).format('YYYY-MM-DD HH:mm:ss'),
              historyList: res
            });
            (this as any).$HistoryLog.push({
              id: this.ship.shipId,
              shipnameEn: this.ship.shipnameEn,
              startTime: this.locusStartDate,
              endTime: this.locusEndDate,
              points: res
            })
            this.shipFun.clearallship()
            this.search2Loading = false
          } else {
            this.$alert('暂无当前船舶轨迹信息', '提示', {
              showConfirmButton: false,
              closeOnClickModal: true
            })
            this.search2Loading = false
          }
        })
      } else {
        this.$alert('高级查询只能查询时间间隔为一年的数据', '提示', {
          showConfirmButton: false,
          closeOnClickModal: true
        })
      }
    }
  }

  private showShipPath(value: any, num?: any) {
    let start = value[0]
    let Startposition = num ? [start.lon, start.lat] : [start.lon / 600000, start.lat / 600000]
    if (!num) {
      value.forEach((e: any) => {
        e.lon = e.lon / 600000
        e.lat = e.lat / 600000
      })
    }
    this.shipPathList = value
    this.isShowPath = true
    this.shipFun.setZoom(11)
    this.shipFun.delSelect()
    this.shipFun.setCenter(Startposition)
    // setTimeout(() => {
    //   this.shipFun.setZoom(11.1)
    // })

    let pathId = ''
    if (this.isShowPath) {
      this.shipFun.delPath()
      return this.shipFun.addPath(this.shipPathList, storeUtil.getMapInstance())
    }
  }

  private selectTableDataCell(row: any) {
    this.shipFun.delPath()
    this.showShipPath(row.historyList, 1)
  }

  private delectShipLocus(index: any, data: any) {
    if (this.tableData.length) {
      this.tableData.splice(index, 1)
      this.shipFun.delPath()
    }
  }

  private deleteTableData() {
    if (this.tableData.length) {
      this.tableData = []
      this.shipFun.delPath()
    }
  }

  private cancel() {
    this.shipFun.delPath()
  }
}
</script>

<style scoped lang="scss">

::v-deep .track-btn {
  display: flex;
  align-items: center;
  width: 97%;

  ::v-deep .el-date-editor {
    width: 13.75rem !important;

    input {
      width: 100%;
    }
  }

  .el-button {
    width: 6rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--aside-gbc);
    color: var(--aside-font-color);
  }
}

.track-history-box {
  margin-top: 0.525rem;
  height: calc(100% - 120px);
  width: 100%;
}

.el-table {
  ::v-deep.el-table__header-wrapper {
    th {
      padding: 0;
      border: none;

      .cell {
        height: 2.8125rem !important;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  ::v-deep .el-table__body-wrapper {
    tbody {
      tr {
        td {
          height: 2.5rem !important;
          padding: 0 !important;
        }
      }
    }
  }
}

</style>
