<template>
  <div class="search-box" v-if="funSwitch.open">
    <el-input ref="searchInput" v-model="searchValue" :placeholder="$t('message.search.info')" clearable @clear="clear"
              @focus="searchFocus"
              @input="querySearchAsync">
    </el-input>
    <div class="search-list" id="menu-search-list" v-if="isShowSearchList">
      <div class="search-ship-box">
        <div class="ship-info" v-for="(item,index) in searchResult.ship" :key="index" @click="chooseInfo(item,'ship')">
          <img src="../../../public/img/ship_ico.png">&nbsp;
          <div>{{ $t('message.search.shipName') }}:&nbsp;{{ item.name }}</div>&nbsp;&nbsp;&nbsp;&nbsp;
          <div>{{ $t('message.search.mmsi') }}:&nbsp;{{ item.mmsi }}</div>&nbsp;&nbsp;&nbsp;&nbsp;
          <div>{{ $t('message.search.lastUpdated') }}:&nbsp;{{ countTime(item.posTime) }}</div>
        </div>
      </div>
<!--      <el-divider></el-divider>-->
<!--      <div class="search-port-box">-->
<!--        <div class="port-info" v-for="(item,index) in searchResult.port" :key="index" @click="chooseInfo(item,'port')">-->
<!--          <img src="../../../public/img/mao_ico.png" alt="">&nbsp;-->
<!--          <span>{{ `${item.nameEn}[${item.countryEn}]` }}</span>-->
<!--        </div>-->
<!--      </div>-->
    </div>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Watch} from 'vue-property-decorator'
import HttpApi from "@/api";
import {SearchLogUtil} from "@/util/tool";
import storeUtil from "@/util/store";
import DialogUtil from "@/util/new-dialog";
import ShipInfoTemp from "@/views/new-dialog/ShipInfoTemp.vue";
import {DialogType as DialogType2} from "@/util/temp-interface";
import PortQueryTemp from "@/views/new-dialog/PortQueryTemp.vue";
import {dateForNow} from "@/util/date";
import {countryName, portName} from "@/util/format";
import {search} from '@/util/fun-switch'
import $ from 'jquery'
import MessageUtil from "@/util/message";
import {bind} from "xe-utils";

@Component({})
export default class Search extends Vue {
  private searchValue = ''
  private funSwitch = search
  private placeholder = ''
  private searchShip = true
  private selectData: any = {}
  private searchResult: any = {}
  private isShowSearchList = false
  private projectName = window.localStorage.getItem('pgName') ? '/' + window.localStorage.getItem('pgName') : location.origin

  @Watch('$route.query', {deep: true, immediate: true})
  urlChange(data: any) {
    if (this.funSwitch.urlMMSI) {
      if (data && data.mmsi) {
        this.$nextTick(() => {
          this.searchValue = data.mmsi
          this.querySearchAsync(data.mmsi).then(() => {
            if (this.searchResult.ship.length && this.searchResult.ship.length === 1) {
              this.chooseInfo(this.searchResult.ship[0], 'ship')
            } else if (this.searchResult.ship.length > 1) {
              (document.getElementById('select-ships') as HTMLElement).click()
              this.selectData = data
            } else {
              MessageUtil.info('没有找到这个MMSI的船舶')
            }
          })
        })
      }
    }
  }

  /**
   * 更具关键字查询港口或者是船舶
   * @param data
   * @private
   */
  private async querySearchAsync(data: any) {
    if (!data) {
      return
    }
    let result: any = []
    const ship = new Promise((resolve, reject) => {
      HttpApi.searchBoathouse({keyword: data}).then((res: any) => {
        resolve(res)
      })
    })
    // const port = new Promise((resolve, reject) => {
    //   HttpApi.getPort(data).then((res: any) => {
    //     if (data !== '') {
    //       resolve(res)
    //     } else {
    //       resolve([])
    //     }
    //   })
    // })
    await Promise.all([ship]).then(([ship]) => {
      result.ship = ship;
      // result.port = port;
    })
    this.searchResult = result
    this.isShowSearchList = true
  }

  private clear() {
    console.log('清空')
    this.isShowSearchList = false
  }

  private searchFocus(e: any) {
    this.querySearchAsync(e.target.value)
  }

  /**
   * 选择船舶的时候执行的方法
   * @param data
   * @private
   */
  private async chooseInfo(data: any, f: string) {
    if (data) {
      if (f === 'ship' && this.funSwitch.ship) {
        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, DialogType2.SHIP_INFO, {
          dialogData: {
            title: shipData.shipnameEn,
            vueName: DialogType2.SHIP_INFO
          },
          infoData: {
            shipData: shipData,
            docData: docData
          },
          show: true
        })
        this.isShowSearchList = false
      } else {
        let port: any
        await HttpApi.getPortInfo(data.portId).then((res: any) => {
          port = res
          Object.assign(port, data)
        });
        (storeUtil.getMapFun() as any).clearallPort();
        (storeUtil.getMapFun() as any).delSelect()
        this.$store.commit('setShowPort', false)
        Search.addPortToMap(port)
        DialogUtil.showDialog(PortQueryTemp, DialogType2.PORT_QUERY, {
          dialogData: {
            title: `${data.nameChs}-${data.nameEn}`,
            vueName: DialogType2.PORT_QUERY
          },
          infoData: {
            portInfo: port
          },
          show: true
        })
        this.isShowSearchList = false
      }
    }
  }

  /**
   * 改变搜索条件执行的方法
   * @private
   */
  private changeSearch() {
    this.searchShip = !this.searchShip
    this.searchResult = []
    this.selectData = ''
    this.placeholder = `${this.searchShip ? this.$t('message.search.shipName') + '\xa0' + '\\' + '\xa0' + this.$t('message.search.mmsi') + '\xa0' + '\\' + '\xa0' + this.$t('message.search.imo') : this.$t('message.search.portName')}`
  }

  /**
   * 当选择港口的时候将港口添加到地图上
   * @param data
   * @private
   */
  private static addPortToMap(data: any) {
    let itemLon = data.lon / 600000
    let itemLat = data.lat / 600000;
    (storeUtil.getMapFun() as any).setCenter([itemLon, itemLat])
    let itemLonStr = itemLon < 0 ? Math.abs(Math.floor(itemLon * 100) / 100) + 'W' : Math.floor(itemLon * 100) / 100 + 'E'
    let itemLatStr = itemLat < 0 ? Math.abs(Math.floor(itemLat * 100) / 100) + 'S' : Math.floor(itemLat * 100) / 100 + 'N'
    let portInfo: any = {
      id: data.portId,
      nameCn: data.nameCn,
      nameEn: data.nameEn,
      code: data.unlocode,
      latLonStr: itemLonStr + ' ' + itemLatStr,
      lon: itemLon,
      lat: itemLat
    };
    (storeUtil.getMapFun() as any).showPort(portInfo)
  }

  private countTime(data: any) {
    return dateForNow(data)
  }

  private getPortName(data: any) {
    return portName(data)
  }

  private getCountryName(data: any) {
    return countryName(data)
  }

  public mounted() {
    this.searchResult = []
    this.selectData = ''
    this.placeholder = `${this.searchShip ? this.$t('message.search.shipName') + '\xa0' + '\\' + '\xa0' + this.$t('message.search.mmsi') + '\xa0' + '\\' + '\xa0' + this.$t('message.search.imo') : this.$t('message.search.portName')}`
    window.addEventListener("setItemEvent", (e: any) => {
      if (e.key === 'language') {
        this.placeholder = `${this.searchShip ? this.$t('message.search.shipName') + '\xa0' + '\\' + '\xa0' + this.$t('message.search.mmsi') + '\xa0' + '\\' + '\xa0' + this.$t('message.search.imo') : this.$t('message.search.portName')}`
      }
    });
    window.addEventListener('click', () => {
      this.isShowSearchList = false
    })
  }
}
</script>

<style scoped lang="scss">
.search-box {
  width: 100%;
  height: 3.125rem;
  display: flex;
  padding: 0 1.25rem;
  box-sizing: border-box;
  align-items: center;

  ::v-deep .el-input__inner {
    color: #FFFFFF !important;
    height: 30px !important;
  }

  .search-list {
    padding: 10px;
    position: absolute;
    top: 120px;
    background: #FFFFFF;
    z-index: 1000;
    border-radius: 20px;

    .search-ship-box {
      max-height: 300px;
      overflow-y: auto;

      &::-webkit-scrollbar {
        display: none
      }

      .ship-info {
        //border-bottom: 1px solid #ccc;
        height: 35px;
        box-sizing: border-box;
        padding: 10px 10px;
        display: flex;
        align-items: center;

        img {
          width: 15px;
          height: 15px
        }
      }

      .ship-info:hover {
        cursor: pointer;
        background: rgba(118, 115, 240, 0.1);
      }
    }
  }

  .search-port-box {
    max-height: 300px;
    overflow-y: auto;

    &::-webkit-scrollbar {
      display: none
    }

    .port-info {
      //border-bottom: 1px solid #ccc;
      height: 35px;
      box-sizing: border-box;
      padding: 10px 10px;
      display: flex;
      align-items: center;

      img {
        width: 15px;
        height: 15px
      }
    }

    .port-info:hover {
      cursor: pointer;
      background: rgba(118, 115, 240, 0.1);
    }
  }
}

.el-divider {
  margin: 10px 0;
}

::v-deep .el-input__icon {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
