<!-- 港间航线页面 -->
<template>
  <div>
    <div class="port-btn-box">
      <el-button :class="isPort? '': 'no-choose'" @click="changePort">{{
          $t('message.routeQuery.portToPort')
        }}
      </el-button>
      <el-button :class="!isPort? '': 'no-choose'" @click="changePort">{{ $t('message.routeQuery.pointToPoint') }}
      </el-button>
    </div>
    <div class="port-route" v-if="isPort">
      <div class="port-param"
           :style="!(portRoutes.length > 0)? 'min-height: 8.125rem max-height: 12.5rem;': 'height: 21.875rem;'">
        <el-row>
          <div class="port-param-box" v-for="(item,index) in portParam" :key="index" style="margin-bottom: 0.125rem">
            <el-row>
              <el-col :span="5" style="border: 0.0625rem solid transparent;position:relative;">
                <div class="choose-region-box"
                     style="position: absolute;top: 1.25rem;right: 0.125rem;bottom: 0.125rem;margin-right: 0.3125rem">
                  <div style="display: flex;align-items: center;">
                    <div style="margin-right: 0.3125rem">
                      <i @click="changeOrder(index)" v-if="index !== portParam.length -1"
                         class="iconfont- icon-jiaohuan" style="font-size: 1.5rem">
                      </i>
                    </div>
                    <div v-if="portParam.length > 2 && index !== portParam.length -1"
                         class="choose-region"
                         :class="regionActive === (index + 1)? 'is-active': '' "
                         @click="chooseRegion(index + 1)">
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :span="14">
                <el-autocomplete :fetch-suggestions="querySearch"
                                 @select="(event) => handleSelect(event,item)"
                                 :placeholder="getPlaceholder(index)"
                                 :trigger-on-focus="false"
                                 :value-key="language === 'zh'? 'tempName' : 'nameEn'"
                                 clearable
                                 v-model="item.name"
                                 class="port-name-input">
                  <template slot-scope="{ item }">
                        <span style="margin-right: 0.625rem">
                            <img src="../../../public/img/mao_ico.png" alt="">
                        </span>
                    <span style="font-size: 0.875rem">
                            {{
                        language === 'zh' ? item.nameChs : item.nameEn
                      }}({{ language === 'zh' ? item.countryChs : item.countryEn }})
                        </span>
                  </template>
                </el-autocomplete>
              </el-col>
              <el-col :span="5" style="height:2.5rem;display: flex; align-items: center;justify-content: center">
                <div v-if="portParam.length >= 1">
                  <i v-if="portParam.length < 5 && index > 0" class="iconfont- icon-add"
                     @click="addPort"></i>
                  <i v-if="index > 0 && portParam.length > 2" class="iconfont- icon-delete"
                     @click="deletePort(index)"></i>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-row>
        <el-row style="display: flex;justify-content: center">
          <el-col :span="14">
            <el-button style="width: 100%" class="is-active" :loading="routeLoading" @click="queryRoute">
              {{ $t('message.routeQuery.search') }}
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <div class="port-result-box" v-if="portRoutes.length > 0">
            <div class="port-start-end-box">
              <div class="port-start-end-content">
                <div class="start-port-name">
                  <el-tooltip :content="startPort.name">
                    <span>{{$t('message.routeQuery.pol')}}：{{ subStringLen(startPort.name) }}</span>
                  </el-tooltip>
                </div>
                <div class="end-port-name">
                  <el-tooltip :content="endPort.name">
                    <span>{{$t('message.routeQuery.pod')}}：{{ subStringLen(endPort.name) }}</span>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </div>
          <div class="port-result"
               v-loading="resultLoading === item.mmsi + ''+  (index+1)"
               v-for="(item,index) in portRoutes"
               :style="'background: #ffffff' + (index === portParam.length -1)? 'border-radius: 0 0 0.3125rem 0.3125rem': ''"
               :key="index">
            <el-row style="width: 100%;">
              <el-col :span="24">
                <el-row style="height: 1.875rem;display: flex;align-items: center">
                  <el-col :span="12">
                    <div class="type-box">
                      <div style="width: 3px;height: 12px;background: #8392C5; margin-right: 5px"></div>
                      <span>{{
                          language === 'zh' ? item.vesselTypeNameCn : item.vesselTypeNameEn
                        }}</span>
                      <div class="full-box"
                           :style="item.isFullLoad === 1? 'background: #DB585B': 'background: #59C165'">
                        {{ getKong(item.isFullLoad) }}
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="6" class="center">
                    <el-switch v-model="item.showRouter" @change="getKK(item,(index + 1))"></el-switch>
                  </el-col>
                  <el-col :span="6" class="center">
                    <div style="font-size: 0.875rem;color: black">{{ item.legStartPostime }}</div>
                  </el-col>
                </el-row>
                <el-row style="width: 100%;margin-top: 0.3125rem;height: 1.875rem;display: flex;align-items: center">
                  <el-col :span="8" class="fl">
                    <el-tooltip placement="bottom"
                                :content="$t('message.routeQuery.duration')+getLetTime(item.legStartPostime, item.legEndPostime)">
                      <div class="center-data">
                        {{ $t('message.routeQuery.duration') }}
                        : <span :id="'lang-time-'+ index"
                                style="font-size: 0.875rem;color: black;margin-left: 0.3125rem">{{
                          getLetTime(item.legStartPostime, item.legEndPostime)
                        }}</span>
                      </div>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="6" class="fl center">
                    <el-tooltip placement="bottom"
                                :content="$t('message.routeQuery.mileage')+ item.sailDistance + 'nm'">
                      <div class="center-data">
                        {{ $t('message.routeQuery.mileage') }}：
                        <span style="font-size: 0.875rem;margin-left: 0.3125rem;color: black">{{
                            item.sailDistance
                          }}nm</span>
                      </div>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="10" class="fl center">
                    <el-tooltip placement="bottom"
                                :content="$t('message.routeQuery.averageSpeed') + item.averageSpeed + 'kn'">
                      <div class="center-data">
                        {{ $t('message.routeQuery.averageSpeed') }}：
                        <el-input class="aver-age-speed" @blur="changeSpeed(item,index)"
                                  v-model="item.averageSpeed"></el-input>
                        <span style="font-size: 0.875rem;color: black">kn</span>
                      </div>
                    </el-tooltip>
                  </el-col>
                </el-row>
                <el-row class="flex"
                        style="flex-grow: inherit;margin-top: 0.3125rem;flex-wrap: wrap;padding: 0 0.3125rem;display: flex;align-items: center">
                  <div v-for="(item2,index) in item.legCrossNodes" :key="index" class="fl">
                    <div class="strait"><span>{{ language === 'zh' ? item2.nameCn : item2.nameEn }}</span></div>
                  </div>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-row>
      </div>
    </div>
    <div class="point-box" v-else>
      <PointToPoint></PointToPoint>
    </div>
  </div>

</template>
<script lang="ts">
import {Component, Vue, Watch} from 'vue-property-decorator'
import HttpApi from '@/api'
import storeUtil from '@/util/store'
import PointToPoint from "@/views/on-map-view/PointToPoint.vue";

@Component({
  components: {
    PointToPoint
  }
})
export default class RouteQuery extends Vue {
  private regionActive = 1 // 设置起始港 和 目的港左边的连接icon 标识符
  private isFullLoad = 0 // 空载0 满载1
  private routeResult: any = {} // 航线查询结果
  private drawPathArray: any[] = [] // 存储画出轨迹的id
  private routeLoading = false // 搜索按钮加载
  private resultLoading = '' // 航线查询结果，加载
  private startPort: any = {} // 起始港口
  private endPort: any = {} // 结束港口
  private portParam: any[] = [{}, {}]
  private portRoutes: any[] = []
  private shipFun: any = storeUtil.getMapFun()
  private language = window.localStorage.getItem('language')
  private isPort = true

  public mounted() {
    window.addEventListener("setItemEvent", (e: any) => {
      if (e.key === 'language') {
        this.language = e.newValue
      }
    });
  }

  private changePort() {
    this.isPort = !this.isPort;
  }

  private cancel() {
    if (this.drawPathArray.length > 0) {
      this.shipFun.delPath()
    }
    this.shipFun.clearPoint()
  }

  private subStringLen(data: any) {
    if (data) {
      if (data.length > 20) {
        return data.substring(0, 20) + '...'
      } else {
        return data
      }
    }
  }

  private getKong(val: number) {
    if (val === 1) {
      return this.$t('message.routeQuery.full')
    } else {
      return this.$t('message.routeQuery.empty')
    }
  }

  private getLetTime(startTime: any, endTime: any) {
    const start = (new Date(startTime).getTime() / 1000)
    const end = (new Date(endTime).getTime() / 1000)
    const sumTime = end - start
    const day = parseInt(sumTime / 86400 + '')
    const hours = parseInt((sumTime - (day * 86400)) / 3600 + '')
    return day + 'd' + hours + 'h'
  }

  private changeSpeed(data: any, index: any) {
    const speed = data.averageSpeed
    const line = data.sailDistance
    const time = line / speed
    const day = parseInt(time / 24 + '')
    const h = parseInt(time - (day * 24) + '');
    (document.getElementById('lang-time-' + index) as HTMLElement).innerText = (day + 'd' + h + 'h')
  }

  private getTime(time: any) {
    const d = parseInt(time / 24 + '')
    const h = parseInt(time - (d * 24) + '')
    return `${d}d${h}h`
  }

  /**
   * 调整港口顺序
   * @private
   */
  private changeOrder(index: any) {
    let lastPort: any = this.portParam[index + 1]
    this.portParam[index + 1] = this.portParam[index]
    this.portParam[index] = lastPort
    this.$forceUpdate()
  }

  /**
   * 获取表单上的placeholder
   * @param index
   * @private
   */
  private getPlaceholder(index: number) {
    if (index === 0) {
      return this.$t('message.routeQuery.pol')
    } else if (this.portParam.length === 2 && index === 1) {
      return this.$t('message.routeQuery.pod')
    } else if (this.portParam.length > 2 && index > 0) {
      return `${this.$t('message.routeQuery.port')}${index}`
    }
  }

  /**
   * 输入返回建议
   * @private
   */
  private querySearch(str: string, cb: any) {
    HttpApi.getPort(str).then((res: any) => {
      const tempData = res
      if (tempData && tempData.length > 0) {
        tempData.forEach((res2: any) => {
          if (res2.nameChs) {
            res2.tempName = res2.nameChs
          } else {
            res2.tempName = res2.nameEn
          }
        })
      }
      cb(tempData)
    })
  }

  /**
   * 选中执行的方法
   * @private
   */
  private handleSelect(event: any, val: any) {
    val.id = event.portId
  }

  /**
   * 参数中添加一个港口
   * @private
   */
  private addPort() {
    this.portParam.push({})
    if (this.regionActive === 0) {
      this.regionActive = 1
    }
  }

  /**
   * 参数中删除一个港口
   * @private
   */
  private deletePort(index: any) {
    this.portParam.splice(index, 1)
    if (this.portParam.length === 2) {
      this.regionActive = 0
    }
    if ((index > 1) && (this.regionActive === index)) {
      this.regionActive = this.regionActive - 1
    }
  }

  /**
   * 查询推荐航线
   * @private
   */
  private async queryRoute() {
    if (this.regionActive === 0) {
      this.startPort.name = this.portParam[0].name
      this.startPort.id = this.portParam[0].id
      this.endPort.name = this.portParam[1].name
      this.endPort.id = this.portParam[1].id
    } else {
      this.startPort.name = this.portParam[this.regionActive - 1].name
      this.startPort.id = this.portParam[this.regionActive - 1].id
      this.endPort.name = this.portParam[this.regionActive].name
      this.endPort.id = this.portParam[this.regionActive].id
    }
    if (!this.startPort.id || !this.endPort.id) {
      this.$message.error('请输入正确的起始港或目的港')
      return
    }
    const data = {
      startPortId: this.startPort.id,
      endPortId: this.endPort.id
    }
    this.routeLoading = true
    this.drawPathArray.forEach((item: any, index: number) => {
      let a = item.id.indexOf('-index')
      const path = item.id.substring(a + 6, item.length);
      this.shipFun.delPath(path);
      this.drawPathArray.splice(index, 1)
    })
    HttpApi.getShipRouteSearch(data).then((res: any) => {
      if (res.code === '0') {
        if (res.data !== null) {
          this.routeResult = res.data
          this.portRoutes = res.data.routes !== null ? res.data.routes : []
          // s z j
          for (let i = 0; i < this.portRoutes.length; i++) {
            const data = this.portRoutes[i];
            if (i !== 0 && data.vesselTypeNameCn === '杂货') {
              this.portRoutes.unshift(data)
              this.portRoutes.splice(i + 1, 1)
            }
          }

          for (let i = 0; i < this.portRoutes.length; i++) {
            const data = this.portRoutes[i];
            if (i !== 0 && data.vesselTypeNameCn.indexOf('散货') !== -1) {
              this.portRoutes.unshift(data)
              this.portRoutes.splice(i + 1, 1)
            }
          }
          this.portRoutes.splice(this.portRoutes.length - 1, 1)
        } else {
          this.routeResult = null
          this.portRoutes = []
        }
        if (this.portRoutes.length > 0) {
          this.portRoutes.splice(6, this.portRoutes.length).forEach((item: any) => {
            item.showRouter = false
            const data = {
              legStartPortCode: item.legStartPortCode,
              legEndPortCode: item.legEndPortCode,
              mmsi: item.mmsi,
              legStartPostime: item.legStartPostime,
              legEndPostime: item.legEndPostime
            }
          })
          this.portRoutes[0].showRouter = true
          this.getKK(this.portRoutes[0], 1)
        } else {
          this.portRoutes = []
        }
        this.routeLoading = false
        if (this.portRoutes.length === 0) {
          this.$message.info('暂无可用航线')
        }
      }
    }).catch(() => {
      this.routeLoading = false
      this.$forceUpdate()
      this.$message.warning('获取航线失败')

    })
  }

  private chooseRegion(num: number) {
    this.regionActive = num
  }

  /**
   * 获取推荐航线的轨迹点
   * @param val
   * @param pIndex
   * @private
   */
  private getKK(val: any, pIndex: number) {
    this.$forceUpdate()
    let path = ''
    if (val.showRouter) {
      this.resultLoading = val.mmsi + '' + pIndex
      const data = {
        'withWeather': 0,
        'mmsi': val.mmsi,
        'sparse': 1,
        'startPortCode': 'string',
        'spareInterval': 10,
        'endPortCode': 'string',
        'startTime': val.legStartPostime,
        'endTime': val.legEndPostime,
        'filterDynamicType': [
          'string'
        ]
      }
      HttpApi.getStatusTrack(data).then((res: any) => {
        if (res.code === '0') {
          const points: any[] = []
          if (res.data.length > 0) {
            res.data.forEach((item: any, index: number) => {
              points.push({
                lon: item.lon,
                lat: item.lat,
                sog: parseInt(item.speed),
                mmsi: item.mmsi,
                direction: item.hdg,
                speed: item.sow === null ? item.sow : 0,
                time: new Date(item.postime).getTime() / 1000,
                draft: item.draught
              })
            })
          }
          const path = this.shipFun.addPath(points, storeUtil.getMapInstance())
          this.drawPathArray.push({
            id: val.mmsi + 'yc-' + pIndex + '-index' + path,
            points: points
          })
          this.resultLoading = ''
        }
      })
    } else {
      if (this.drawPathArray.length > 0) {
        this.drawPathArray.forEach((item: any, index) => {
          if (item.id.indexOf(val.mmsi + 'yc-' + pIndex + '-index') !== -1) {
            const pathId = item.id.split('-index')
            this.shipFun.delPathOne(pathId[1], item.points.length)
            this.drawPathArray.splice(index, 1)
            this.resultLoading = ''
            val.showRouter = false
          }
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">

.port-btn-box {
  display: flex;
  align-items: center;

  .no-choose {
    background: #FFFFFF !important;
    color: #333333 !important;
  }
}

.port-route {
  padding: 0.625rem 0;
  display: flex;
  width: 100%;

  .port-param {
    flex: 1;
    overflow-y: auto;
    float: left;

    .port-result {
      padding: 0.3125rem 1.25rem;
      margin-bottom: 0.625rem;

      &:hover {
        cursor: pointer;
      }

      .center-data {
        font-size: 0.75rem;

        .aver-age-speed {
          width: 5rem;
          margin-left: 0.3125rem;
          margin-right: 0.3125rem;
          color: black;

          ::v-deep.el-input__inner {
            height: 1.875rem !important;
          }
        }
      }
    }

    .is-active {
      //background: var(--theme-color);
      border-color: var(--theme-color);
      color: #FFFFFF;
      height: 1.875rem;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 0.625rem;
    }

    ::v-deep .el-input__inner {
      background: rgba(218, 218, 244, 1);
      color: #60556B;
    }

    &::-webkit-scrollbar {
      width: 0.5rem;
      height: 0.5rem;
    }

    &::-webkit-scrollbar-track {
      -webkit-box-shadow: inset 0 0 0.375rem rgba(0, 0, 0, 0.3);
      border-radius: 0.625rem; /*滚动条的背景区域的圆角*/
      background-color: var(--theme-color); /*滚动条的背景颜色*/
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 0.625rem; /*滚动条的圆角*/
      -webkit-box-shadow: inset 0 0 0.375rem rgba(0, 0, 0, .3);
      background-color: #ffffff; /*滚动条的背景颜色*/
    }

    .port-param-box {
      width: 100%;
      height: 2.5rem;

      .choose-region-box {
        z-index: 999;

        .choose-region {
          width: 1rem;
          height: 2.5rem;
          border: 0.1875rem solid rgba(255, 255, 255, 0.3);
          border-right: none;

          &:hover {
            border-color: var(--theme-color);
          }
        }

        &:hover {
          background-color: red !important;
        }

        .is-active {
          display: inherit;
          border-color: var(--theme-color);
        }
      }

      .port-name-input {
        width: 100%;
      }

      .icon-exchange1 {
        font-size: 1.875rem;
        color: #FFFFFF;
      }
    }
  }

  .port-result-box {
    padding: 0.625rem 1rem 0 1rem;
    margin-bottom: 10px;

    .result-sum {
      font-size: 0.875rem;
      color: black;
    }

    .port-start-end-box {
      width: 100%;
      height: 0.875rem;
      display: flex;
      align-items: center;
      border-radius: 0.3125rem 0.3125rem 0 0;

      .port-start-end-content {
        width: 100%;
        height: 1.875rem;
        position: relative;
        display: flex;
        align-items: center;

        .start-port-name {
          display: flex;
          align-items: center;
          padding: 0 0.625rem;
          border-radius: 50.3125rem;
          color: black;
        }

        .start-end-icon {
          width: 2.5rem;
          position: absolute;
          left: 50%;
          transform: translate(-50%, 0);
          display: flex;
          align-items: center;
          justify-content: center;

          i {
            color: var(--theme-color);
            transform: scale(3, 2);
          }
        }

        .end-port-name {
          padding: 0 0.625rem;
          border-radius: 0.3125rem;
          color: black;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }

      .arrive-route {
        position: relative;
        height: 1.875rem;

        .arrive-route-sum {
          position: absolute;
          left: 0;
        }

        .arrive-route-one {
          position: absolute;
          right: 0;
        }
      }
    }
  }

  .port-result {
    margin: 0 1rem;
    background: #FFFFFF;
    padding: 0.625rem 0.125rem;
    border: 1px solid #E9E9E9;
    border-radius: 0.375rem !important;

    ::v-deep .type-box {
      padding-left: 0.1875rem;
      padding-right: 0.1875rem;
      height: 1.376rem;
      width: auto !important;
      color: #333333;
      border-radius: 0.375rem;
      display: flex;
      align-items: center;
      justify-content: left;
      ext-overflow: -o-ellipsis-lastline;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    ::v-deep .el-switch.is-checked .el-switch__core {
      background: var(--theme-color);
      border-color: var(--theme-color);
    }

    ::v-deep .full-box {
      font-size: 0.75rem;
      height: 1.375rem;
      min-width: 1.375rem;
      padding-left: 0.125rem;
      text-align: center;
      padding-right: 0.125rem;
      border-radius: 0.375rem;
      color: #FFFFFF;
      display: inline-block;
      align-items: center;
      justify-content: center;
      margin-left: 10px;
    }

    &:nth-child(odd) {
      //background: rgba(44, 70, 155, 0.4) !important;
    }
  }

}

.strait {
  width: auto;
  height: 1.375rem;
  margin-bottom: 0.3125rem;
  //border: 0.0625rem solid var(--theme-color);
  //border-radius: 0.375rem;
  display: flex;
  font-size: 0.875rem;
  font-weight: 400;
  align-items: center;
  justify-content: center;
  padding: 0 0.625rem;
  margin-right: 0.625rem;
  background: #F1F3F9;
  border-radius: 14px;
  border: 1px solid #E1E3EC;
  color: #A4A8B9;
}

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