<template>
  <div class="shipranks-box">
    <el-table v-loading="isLoading" :data="newTableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
              ref="shipRanks"
              :height="tableHeight"
              @row-click="openShip"
              :header-cell-style="{'background-color': '#94A1CC',color: '#ffffff'}"
              :row-style="{ cursor: 'pointer' }">
      <el-table-column prop="shipnameEn"
                       :label="$t('message.areaList.shipName')"
                       width="150"
                       align="center"
                       show-overflow-tooltip
                       sortable>
      </el-table-column>
      <el-table-column prop="imo"
                       label="IMO"
                       width="120"
                       align="center"
                       sortable>
      </el-table-column>
      <el-table-column prop="mmsi"
                       label="MMSI"
                       width="120"
                       align="center"
                       sortable>
      </el-table-column>
      <el-table-column prop="shiptype" :label="$t('message.areaList.type')" width="120" align="center">
        <template slot-scope="scope">
          {{ language === 'zh' ? filterShipType(scope.row.shiptype) : filterShipType(scope.row.shiptype, true) }}
        </template>
      </el-table-column>
      <el-table-column prop="length"
                       label="船长"
                       width="120"
                       align="center"
                       sortable>
        <template slot-scope="scope"> {{ scope.row.length }}m</template>
      </el-table-column>
      <el-table-column prop="mmsi" :label="$t('message.areaList.nationality')" width="120" align="center">
        <template slot-scope="scope">
          <img style="width: 2.5rem; height: 1.5rem; border: none" :src="filterCountry(scope.row.mmsi.slice(0, 3))"/>
        </template>
      </el-table-column>
      <el-table-column prop="draught"
                       :label="$t('message.areaList.draft')"
                       width="120"
                       align="center"
                       sortable>
        <template slot-scope="scope"> {{ scope.row.draught / 10 }}m</template>
      </el-table-column>
      <el-table-column prop="sog"
                       :label="$t('message.areaList.sog')"
                       width="120"
                       align="center"
                       sortable>
        <template slot-scope="scope"> {{ scope.row.sog / 10 }}kn</template>
      </el-table-column>
      <el-table-column prop="destPort"
                       :label="$t('message.areaList.destPort')"
                       width="120"
                       show-overflow-tooltip>
      </el-table-column>
    </el-table>
    <div class="table-paging">
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[50, 100, 200, 400]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="tableData.length">
      </el-pagination>
    </div>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Watch} from 'vue-property-decorator'
import storeUtil from '@/util/store'
import MapUtil from '@/util/map'
import {DialogType as DialogType2, DialogType} from '@/util/temp-interface'
import DialogUtil from "@/util/new-dialog";
import ShipInfoTemp from "@/views/new-dialog/ShipInfoTemp.vue";
import HttpApi from "@/api";
import {SearchLogUtil} from "@/util/tool";

import {Loading} from 'element-ui';

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

@Component({})
export default class ShipRanks extends Vue {
  private language = window.localStorage.getItem('language')
  private visible = false
  private shipFun: any = storeUtil.getMapFun()
  private originAllShipRankList: any[] = []
  private isLoading = false
  private newTableData: any[] = storeUtil.getShipFleet()
  private tableData: any[] = storeUtil.getShipFleet()
  private currentPage = 1
  private pageSize = 50
  private tableHeight = 280

  public mounted() {
    window.addEventListener('setItemEvent', (e: any) => {
      if (e.key === 'language') {
        this.language = e.newValue
      }
    })
    const erd = elementResizeDetectorMaker()
    erd.listenTo((this.$refs.shipRanks as any).$parent.$el, () => {
      this.tableHeight = (this.$refs.shipRanks as any).$parent.$el.clientHeight - 40
    })
  }

  public async getShips() {
    const load = Loading.service({
      target: (this.$refs.shipRanks as any).$el
    })
    const ships: any = []
    await HttpApi.getShipRanks({}).then((res: any) => {
      res.forEach((item: any) => {
        if (item.idw !== -1 && item.followShipList && item.followShipList.length) {
          item.followShipList.forEach(async (item2: any) => {
            item2.groupName = item.name;
            item2.color = item.color;
            ships.push(item2)
          })
        }
      })
    })

    for (let i = 0; i < ships.length; i++) {
      const ship = ships[i];
      await HttpApi.getShipMessage({shipId: ship.shipId}).then((res) => {
        Object.keys(res[0]).forEach((item3: any) => {
          ship[item3] = res[0][item3]
        })
      })
    }
    load.close()

    this.tableData = ships
    this.newTableData = ships
    this.jiexiRanks(ships)
  }

  private handleSizeChange(val: any) {
    this.pageSize = val
  }

  private handleCurrentChange(val: any) {
    this.currentPage = val
  }

  private posShip(data: any) {
    if (data) {
      this.shipFun.setCenter([data.lon / 600000, data.lat / 600000])
      this.shipFun.addSelectByCoor([data.lon / 600000, data.lat / 600000])
    }
  }

  private async openShip(data: any) {
    let shipData: any = {}
    let docData = {}
    await HttpApi.getShipMessage({shipId: data.shipId}).then((res: any) => {
      const SearchLog = (this as any).$SearchLog
      let flag = true
      if (SearchLog.length) {
        for (let i = 0; i < SearchLog.length; i++) {
          const item = SearchLog[i]
          if (item.shipId === res[0].shipId) {
            flag = false
            break
          }
        }
      }

      if (flag) {
        SearchLogUtil.addSearchLog(res[0])
      }
      storeUtil.setShipData(res[0])
      shipData = res[0]
    })
    await HttpApi.getShipDoc({shipId: data.shipId}).then((res: any) => {
      if (res) {
        docData = res
      }
    })
    DialogUtil.showDialog(ShipInfoTemp, DialogType.SHIP_INFO, {
      dialogData: {
        title: shipData.shipnameEn,
        vueName: DialogType2.SHIP_INFO
      },
      infoData: {
        shipData: shipData,
        docData: docData
      },
      show: true
    })
  }

  /**
   * 通过船舶类型id解析船舶类型名称
   * @param typeId 船舶类型ID
   */
  private filterShipType(typeId: string, en?: boolean) {
    if (typeId) {
      let result = ''
      const data = storeUtil.getShipType()
      let isFind = false
      for (let i = 0; i < data.length; i++) {
        if (typeId === data[i].id) {
          isFind = true
          if (!en) {
            result = data[i].valueChs
          } else {
            result = data[i].valueEn
          }

          break
        }
      }
      if (!isFind) {
        if (!en) {
          result = '其他类型'
        } else {
          result = 'other'
        }
      }
      return result
    }
  }

  /**
   * 通过MMSI获取船舶国籍 编码
   * @param mmsi 船舶MMSI
   */
  private filterCountry(mmsi: string) {
    const data = storeUtil.getCountry()
    if (mmsi) {
      for (let i = 0; i < data.length; i++) {
        if (mmsi === data[i].id) {
          return require('../../../public/country-img/' + data[i].valueAbbr + '.png')
        }
      }
    }
  }

  @Watch('$store.state.shipRanksDialog', {
    immediate: true,
    deep: true
  })
  setData(data: any) {
    if (data) {
      this.visible = data.show
    }
  }

  /**
   * 获取船队数据
   * @private
   */
  private getShipRanks() {
    this.shipFun.addShip(this.originAllShipRankList, 11, storeUtil.getMapInstance())
  }

  private jiexiRanks(data: any) {
    const newShipList: any = []
    data.forEach((item: any) => {
      newShipList.push({
        y: item.shiptype,
        m: item.mmsi,
        h: item.heading,
        g: item.callsign,
        c: item.cog,
        o: item.imo,
        s: item.sog,
        v: item.aisNavStatus,
        l: item.length,
        p: item.destPort,
        b: item.breadth,
        r: item.eta,
        d: item.draught,
        t: item.posTime,
        i: item.shipId,
        n: item.lon,
        a: item.lat,
        e: item.shipnameEn,
        color: item.color,
        isFleet: true
      })
    })
    this.originAllShipRankList = JSON.parse(JSON.stringify(newShipList))

    this.getShipRanks()
  }

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

<style lang="scss" scoped>
::v-deep .el-dialog {
  top: 12.5rem;
  position: absolute;
  right: 1.25rem;

}

::v-deep .el-dialog__body {
  height: auto !important;
}

.shipranks-box {
  width: 100%;
  height: 100%;
  min-height: 300px;
  overflow-y: hidden;
  position: relative;

  .has-ship-num {
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 0;
  }

  .fleet-list {
    height: 280px;
    overflow-y: auto;

    .fleet-ship {
      display: flex;
      align-items: center;
      height: 30px;
      font-size: 16px;

      .order {
        width: 30px;
        text-align: left;
      }

      .ship-name {
        width: 60%;
        text-align: left;
      }

      .btn {
        width: 20%;
        display: flex;
        justify-content: center;

        .img {
          img {
            width: 20px;
            height: 20px;
          }
        }
      }
    }

    .fleet-ship:hover {
      cursor: pointer;
      opacity: 0.8;
    }
  }
}

.inline {
  display: inline-block;
  height: 0.625rem;
  width: 0.625rem;
  margin-right: 0.4375rem;
  border-radius: 0.625rem;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 0.875rem;
  padding-right: 0.5rem;
}

.color {
  color: blue;
}
</style>
