<template>
  <div class="area-ship-info">
    <div v-show="!isStatistic">
      <div class="headSelect">
        <span class="title">{{ $t('message.areaList.shipType') }}:</span>
        <el-select class="select-small"
                   v-model="chooseShipType"
                   filterable
                   :placeholder="$t('message.areaList.all')"
                   size="small"
                   clearable>
          <el-option v-for="(item, index) in shipTypeOptions"
                     :key="index"
                     :label="language === 'zh' ? item.label: item.labelEn"
                     :value="item.value"></el-option>
        </el-select>
        <span class="title">{{ $t('message.areaList.shipFlag') }} :</span>
        <el-select class="select-small"
                   size="small"
                   v-model="chooseShipFlag"
                   filterable
                   :placeholder="$t('message.areaList.all')"
                   clearable>
          <el-option v-for="(item, index) in shipFlagOptions"
                     :key="index"
                     :label="item.valueChs?item.valueChs: item.valueEn"
                     :value="item.valueAbbr">
          </el-option>
        </el-select>
        <span class="title">{{ $t('message.areaList.shipLength') }}:</span>
        <el-select class="select-small"
                   size="small"
                   v-model="chooseShipLen"
                   filterable
                   :placeholder="$t('message.areaList.all')"
                   clearable>
          <el-option v-for="(item, index) in shipLengthOptions"
                     :key="index"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
        <el-button @click="flitership()"><span>{{ $t('message.areaList.select') }}</span></el-button>
      </div>
      <el-table v-loading="isLoading" :data="newTableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                ref="arealist"
                :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="newTableData.length">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

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

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

@Component({
  props: {
    data: {
      type: Object,
      required: true
    }
  }
})
export default class AreaList extends Vue {
  private projectName = window.localStorage.getItem('pgName') ? '/' + window.localStorage.getItem('pgName') : ''
  private language = window.localStorage.getItem('language')
  private shipTypes: Map<string, any> = new Map<string, any>()
  private shipTypesColor: Map<string, string> = new Map<string, string>()
  private currentPage = 1
  private pageSize = 50
  private tableHeight = 280
  private shipTypeOptions = [
    {
      value: '1',
      label: '货船',
      labelEn: 'Cargo Ship'
    },
    {
      value: '2',
      label: '油船',
      labelEn: 'Tanker'
    },
    {
      value: '3',
      label: '渔船',
      labelEn: 'Fishing vessel'
    },
    {
      value: '4',
      label: '客船',
      labelEn: 'Passenger'
    },
    {
      value: '5',
      label: '拖船',
      labelEn: 'Towing Vessel'
    },
    {
      value: '6',
      label: '工程船',
      labelEn: 'Engineering Ship'
    },
    {
      value: '7',
      label: '公务执法船',
      labelEn: 'Official Ship'
    },
    {
      value: '8',
      label: '其他船',
      labelEn: 'Other'
    }
  ]
  private shipFlagOptions: any[] = []
  private shipLengthOptions: any[] = [
    {
      value: '1',
      label: '50m以下'
    },
    {
      value: '2',
      label: '50-100m'
    },
    {
      value: '3',
      label: '100-200m'
    },
    {
      value: '4',
      label: '200m以上'
    }
  ]
  private chooseShipType = ''
  private chooseShipFlag = ''
  private chooseShipLen = ''
  private newTableData: any[] = []
  private isStatistic = false
  private tableData: any[] = []
  private shipTypeData: any[] = []
  private shipFlagData = new Map()

  private isLoading = false

  @Watch('data', {deep: true, immediate: true})
  dataChange(area: any) {
    this.openPortDialog(area)
  }

  public created() {
    this.shipTypes.set('cargo', {nameCh: '货船', nameEn: 'cargo'})
    this.shipTypes.set('tanker', {nameCh: '油船', nameEn: 'tanker'})
    this.shipTypes.set('fishing', {nameCh: '渔船', nameEn: 'fishing'})
    this.shipTypes.set('tug', {nameCh: '拖船', nameEn: 'tug'})
    this.shipTypes.set('offshore', {nameCh: '工程船', nameEn: 'offshore'})
    this.shipTypes.set('official', {nameCh: '公务船', nameEn: 'official'})
    this.shipTypes.set('other', {nameCh: '其他', nameEn: 'other'})
    this.shipTypes.set('passenger', {nameCh: '客船', nameEn: 'passenger'})

    this.shipTypesColor.set('cargo', '#065880')
    this.shipTypesColor.set('tanker', '#743675')
    this.shipTypesColor.set('fishing', '#fc8a2a')
    this.shipTypesColor.set('tug', '#bd3154')
    this.shipTypesColor.set('offshore', '#2fb3cc')
    this.shipTypesColor.set('official', '#8d1d55')
    this.shipTypesColor.set('other', '#53cf90')
    this.shipTypesColor.set('passenger', '#ffc24d')
  }

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

    const erd = elementResizeDetectorMaker()
    erd.listenTo((this.$refs.arealist as any).$parent.$el, () => {
      this.tableHeight = (this.$refs.arealist as any).$parent.$el.clientHeight - 80
    })
  }

  private async openPortDialog(data: any) {
    let load: any
    this.$nextTick(() => {
      load = Loading.service({
        target: (this.$refs.arealist as any).$el
      })
    })

    const shipFun: any = storeUtil.getMapFun()
    const mapInstance: any = storeUtil.getMapInstance()
    shipFun.setZoom(7)
    let area = data.area
    let rgn = ''
    area.forEach((item: any) => {
      rgn += `${parseInt(Number(item.lon) * 600000 + '')} ${parseInt(
        Number(item.lat) * 600000 + ''
      )},`
    })
    rgn = rgn.substring(0, rgn.lastIndexOf(','))

    let lon = data.cLon / 600000
    let lat = data.cLat / 600000
    shipFun.setCenter([lon, lat])
    shipFun.delPath()
    shipFun.addarea(area)

    const params = {
      rgn: rgn,
      dataSize: 999999,
      age: 120
    }

    await HttpApi.getAreaData(params).then((res: any) => {
      if (res) {
        this.isLoading = false
        const shipData = res.latesAndAisList
        const nowZoom = mapInstance.getView().getZoom()
        // shipFun.clearallship()
        // shipFun.addShip(shipData, nowZoom, mapInstance)
        let shipList: any[] = []
        let shipTypes = new Map()
        this.shipFlagData.clear()
        for (let i = 0; i < res.latesAndAisList.length; i++) {
          const element = res.latesAndAisList[i]
          // 计算国旗统计
          let countryNumber = this.shipFlagData.get(element.f)
          if (countryNumber) {
            this.shipFlagData.set(element.f, countryNumber + 1)
          } else {
            this.shipFlagData.set(element.f, 1)
          }
          // 计算类型统计
          let shipType = this.getShipType(element.y)
          let shipTypeNum = shipTypes.get(shipType)
          if (shipTypeNum) {
            shipTypes.set(shipType, shipTypeNum + 1)
          } else {
            shipTypes.set(shipType, 1)
          }
          shipList[i] = {
            shiptype: element.y,
            mmsi: element.m,
            heading: element.h,
            callsign: element.g,
            cog: element.c,
            imo: element.o,
            sog: element.s,
            aisNavStatus: element.v,
            length: element.l,
            destPort: element.p,
            breadth: element.b,
            eta: element.r,
            draught: element.d,
            posTime: element.t,
            shipId: element.i,
            lon: element.n,
            lat: element.a,
            shipnameEn: element.e,
            shipCountry: element.f
          }
        }
        this.tableData = shipList
        this.newTableData = Object.assign(this.tableData)
        // 船舶类型饼图
        this.shipTypeData = []
        shipTypes.forEach((value, key1) => {
          let type: any = {}
          type[key1] = value
          this.shipTypeData.push(type)
        })

        let country = storeUtil.getCountry()
        this.tableData.forEach((element: any) => {
          this.shipFlagOptions.push(
            country.filter((e: any) => {
              return element.mmsi.slice(0, 3) === e.id
            })[0]
          )
        })
        this.removeEmptyArrayEle(this.shipFlagOptions)
        this.unique(this.shipFlagOptions)
      }
    })
    load.close()
  }

  private getShipType(value: any) {
    let shipType = ''
    //船舶类型定义
    let shipItemType = Number(value)
    if (shipItemType >= 70 && shipItemType <= 79) { // 货船
      shipType = 'cargo'
    } else if (shipItemType >= 80 && shipItemType <= 89) { // 油船
      shipType = 'tanker'
    } else if (shipItemType === 30) { // 渔船
      shipType = 'fishing'
    } else if ((shipItemType >= 60 && shipItemType <= 69) || shipItemType === 37) { // 客船
      shipType = 'passenger'
    } else if (shipItemType === 52) { // 拖船
      shipType = 'tug'
    } else if (shipItemType === 31 || shipItemType === 32 || shipItemType === 33 || shipItemType === 34 || shipItemType === 53) { // 工程船
      shipType = 'offshore'
    } else if (shipItemType === 35 || shipItemType === 50 || shipItemType === 51 || shipItemType === 55 || shipItemType === 58 || shipItemType === 59) { // 公务执法船
      shipType = 'official'
    } else {
      shipType = 'other'
    }
    return shipType
  }

  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
    })
  }

  private setFontSize(size: number) {
    const screenWidth = window.screen.width
    if (screenWidth !== 1080) {
      const scala = screenWidth / 1080
      return (size * scala) + 'px'
    } else {
      return size + 'px'
    }
  }

  private filterCountryName(value: any, en?: boolean) {
    let name = null
    storeUtil.getCountry().forEach((item: any) => {
      if (item.valueAbbr === value) {
        if (!en) {
          name = item.valueChs
        } else {
          name = item.valueEn
        }

      }
    })
    return name
  }

  /**
   * 通过船舶类型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')
        }
      }
    }
  }

  private flitership() {
    let type = this.chooseShipType
    let length = this.chooseShipLen
    let nationa = this.chooseShipFlag
    let resultData: any[] = []
    if (type || length || nationa) {
      if (type) {
        if (resultData.length === 0) {
          switch (type) {
            case '1':
              this.tableData.forEach((item: any) => {
                  if (/^[7].*/.test(item.shiptype)) {
                    resultData.push(item)
                  }
                }
              )
              break
            case '2':
              this.tableData.forEach((item: any) => {
                if (/^[8].*/.test(item.shiptype)) {
                  resultData.push(item)
                }
              })
              break
            case '3':
              this.tableData.forEach((item: any) => {
                if (item.shiptype === '30') {
                  resultData.push(item)
                }
              })
              break
            case '4':
              this.tableData.forEach((item: any) => {
                if (/^[6].*/.test(item.shiptype) || item.shiptype === 37) {
                  resultData.push(item)
                }
              })
              break
            case '5':
              this.tableData.forEach((item: any) => {
                if (item.shiptype === '52') {
                  resultData.push(item)
                }
              })
              break
            case '6':
              this.tableData.forEach((item: any) => {
                if (item.shiptype in [31, 32, 33, 34, 53]) {
                  resultData.push(item)
                }
              })
              break
            case '7':
              this.tableData.forEach((item: any) => {
                if (item.shiptype in [35, 50, 51, 55, 58, 59]) {
                  resultData.push(item)
                }
              })
              break
            case '8':
              this.tableData.forEach((item: any) => {
                if (!((item.shiptype in [35, 50, 51, 55, 58, 59]) ||
                  (item.shiptype in [35, 50, 51, 55, 58, 59]) ||
                  (item.shiptype === '52') ||
                  (/^[6].*/.test(item.shiptype)) ||
                  (item.shiptype === 37) ||
                  (item.shiptype === 30) ||
                  (/^[8].*/.test(item.shiptype)) ||
                  (/^[7].*/.test(item.shiptype)))) {
                  resultData.push(item)
                }
              })
              break
          }
        } else {
          switch (type) {
            case '1':
              for (let i = 0; i < resultData.length; i++) {
                if (!(/^[7].*/.test(resultData[i].shiptype))) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '2':
              for (let i = 0; i < resultData.length; i++) {
                if (!(/^[8].*/.test(resultData[i].shiptype))) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '3':
              for (let i = 0; i < resultData.length; i++) {
                if (!(resultData[i].shiptype !== '30')) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '4':
              for (let i = 0; i < resultData.length; i++) {
                if (!(/^[6].*/.test(resultData[i].shiptype)) || (resultData[i].shiptype !== 37)) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '5':
              for (let i = 0; i < resultData.length; i++) {
                if (resultData[i].shiptype !== '52') {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '6':
              for (let i = 0; i < resultData.length; i++) {
                if ([31, 32, 33, 34, 53].indexOf(resultData[i].shiptype) !== -1) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '7':
              for (let i = 0; i < resultData.length; i++) {
                if ([35, 50, 51, 55, 58, 59].indexOf(resultData[i].shiptype) !== -1) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '8' :
              for (let i = 0; i < resultData.length; i++) {
                const item = resultData[i]
                if (((item.shiptype in [35, 50, 51, 55, 58, 59]) ||
                  (item.shiptype in [35, 50, 51, 55, 58, 59]) ||
                  (item.shiptype === '52') ||
                  (/^[6].*/.test(item.shiptype)) ||
                  (item.shiptype === 37) ||
                  (item.shiptype === 30) ||
                  (/^[8].*/.test(item.shiptype)) ||
                  (/^[7].*/.test(item.shiptype)))) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
          }
        }
      }
      if (length) {
        if (resultData.length > 0) {
          switch (length) {
            case '1':
              for (let i = 0; i < resultData.length; i++) {
                if (resultData[i].length > 50) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '2':
              for (let i = 0; i < resultData.length; i++) {
                if (resultData[i].length > 100 || resultData[i].length < 50) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '3':
              for (let i = 0; i < resultData.length; i++) {
                if (resultData[i].length > 200 || resultData[i].length < 100) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
            case '4':
              for (let i = 0; i < resultData.length; i++) {
                if (resultData[i].length < 200) {
                  resultData.splice(i, 1)
                  i--
                }
              }
              break
          }
        } else {
          switch (length) {
            case '1':
              this.tableData.forEach((item: any) => {
                if (item.length < 50) {
                  resultData.push(item)
                }
              })
              break
            case '2':
              this.tableData.forEach((item: any) => {
                if (item.length < 100 && item.length >= 50) {
                  resultData.push(item)
                }
              })
              break
            case '3':
              this.tableData.forEach((item: any) => {
                if (item.length < 200 && item.length >= 100) {
                  resultData.push(item)
                }
              })
              break
            case '4':
              this.tableData.forEach((item: any) => {
                if (item.length > 200) {
                  resultData.push(item)
                }
              })
              break
          }
        }
      }
      if (nationa) {
        if (resultData.length === 0) {
          this.tableData.forEach((item: any) => {
            if (item.shipCountry === nationa) {
              resultData.push(item)
            }
          })
        } else {
          resultData.forEach(() => {
            for (let i = 0; i < resultData.length; i++) {
              if (resultData[i].shipCountry !== nationa) {
                resultData.splice(i, 1)
                i--
              }
            }
          })
        }
      }
      this.newTableData = resultData
    } else {
      this.newTableData = this.tableData
    }
  }

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

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

// 去除undefined
  private removeEmptyArrayEle(arr: any) {
    for (let i = 0; i < arr.length; i++) {
      if (!arr[i]) {
        arr.splice(i, 1)
        i = i - 1
      }
    }
    return arr
  }

//国籍去重
  private unique(arr: any) {
    for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        if (arr[i].valueChs === arr[j].valueChs) {
          arr.splice(j, 1)
          j--
        }
      }
    }
    return arr
  }

  private cancel() {
    const shipFun: any = storeUtil.getMapFun()
    shipFun.clearArea();
    // shipFun.clearallship();
  }
}
</script>

<style lang="scss" scoped>
$dialog-color: #2c469b;
$dialog-simplecolor: #9bb1e3;
.area-ship-info {
  width: 100%;
  height: 100%;
  min-height: 300px;
  overflow-y: hidden;

  .tab-btn {
    display: flex;
    //align-items: center;

    .btn-item {

      .el-button {
        min-width: 6rem;
        height: 2.375rem;
        border-radius: 0;
        margin: 0 !important;
        padding: 0;
        background: #FFFFFF !important;
        color: #606266 !important;
        border: 0.06rem solid #d8d8d8 !important;
      }

      .j-box {
        width: 6rem;
        height: 0.8125rem;
        display: flex;
        justify-content: center;
        position: relative;
        flex-shrink: 0;
        flex-grow: 0;

        img {
          width: 1rem;
          height: 0.8125rem;
          position: absolute;
          top: -0.125rem;
        }
      }

      .is-active {
        background: var(--aside-bg) !important;
        color: #FFFFFF !important;
        border: none !important;
      }
    }
  }

  .statistic-echarts {
    width: 100%;
    height: calc(100% - 3.75rem) !important;

    .ship-type {
      width: 50%;
      height: 20.1rem;
    }

    .ship-flag {
      width: 50%;
      height: 20.1rem;
    }
  }

  .headSelect {
    height: 1.875rem !important;
    display: flex;
    margin-bottom: 0.94rem;
    align-items: center;

    .title {
      min-width: 2.5rem;
      height: 100%;
      display: flex;
      align-items: center;
      flex-shrink: 0;
      flex-grow: 0;
    }

    .el-select {
      width: 6.25rem !important;

      ::v-deep .el-input__inner {
        height: 1.875rem !important;
        display: flex;
        align-items: center;
      }
    }

    .el-button {
      margin-left: 0.625rem;
      width: 5rem;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.el-table .el-table__cell {
  padding: 0 !important;
}
</style>
