<template>
  <div class="weather-dialog-box">
    <div class="weather-content">
      <div class="weather-header" style="display: flex;align-items: center">
        <div style="display: flex;align-items: center;flex-shrink: 0">
          <div class="title"><span>{{ $t('message.weather.marineWeather') }}</span></div>
          <el-button class="btn" @click="resetWeather">
            <span>{{ $t('message.weather.reset') }}</span>
          </el-button>
        </div>
        <el-button class="tf-btn" v-if="weather === 'tf'" @click="openWeatherImg">
          {{ $t('message.weather.legend') }}
        </el-button>
      </div>
      <div class="item">
        <el-radio-group @change="addWeather" v-model="weather">
          <!--温度-->
          <el-radio label="wd"><span>{{ $t('message.weather.temperature') }}</span></el-radio>
          <!--气压-->
          <el-radio label="qy"><span>{{ $t('message.weather.airPressure') }}</span></el-radio>
          <!--风场-->
          <el-radio label="fc"><span>{{ $t('message.weather.wind') }}</span></el-radio>
          <!--洋流-->
          <el-radio label="yl"><span>{{ $t('message.weather.current') }}</span></el-radio>
          <!--台风-->
          <el-radio label="tf"><span>{{ $t('message.weather.typhoon') }}</span></el-radio>
        </el-radio-group>
      </div>
    </div>
    <div class="tf-list" v-if="istf">
      <div v-if="!isOpenImg" style="width: 535px">
        <el-table ref="tfTable" :data="typhoonData" border height="420"
                  :row-style="rowStyle" :cell-style="{padding: 0}" :header-cell-style="{padding: '9px 0'}">
          <el-table-column prop="name"  :label="$t('message.typhoon.name')" sortable align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="beginTime" :label="$t('message.typhoon.start')" sortable width="140" align="center">
          </el-table-column>
          <el-table-column prop="endTime" :label="$t('message.typhoon.end')" sortable width="140" align="center">
          </el-table-column>
          <el-table-column :label="$t('message.typhoon.operate')" width="100" align="center">
            <template slot-scope="scope">
              <el-button class="show-typhoon" v-if="!scope.row.isShow"
                         @click="toggleTyphoon(scope.row, true)">{{ $t('message.weather.view') }}
              </el-button>
              <el-button class="show-typhoon" v-else
                         @click="toggleTyphoon(scope.row,false)">{{ $t('message.weather.close') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

  </div>
</template>

<script lang="ts">
import {Component, Vue, Watch} from 'vue-property-decorator'
import storeUtil from '@/util/store'
import * as dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import HttpApi from '@/api'
import DialogUtil from "@/util/new-dialog";
import {DialogType} from "@/util/temp-interface";
import WeatherImgTemp from '@/views/new-dialog/WeatherImgTemp.vue'

dayjs.extend(utc)
Component.registerHooks(['activated', 'beforeDestroy', 'deactivated'])

@Component({})
export default class Weather extends Vue {
  private dialogData: any = {}
  private visible = false
  private weather = '1'
  private isPro = true // 判断是否生产环境
  private typhoonData: any[] = [] // 台风列表数据
  private forecastIsShow = true;
  private mapFun = (storeUtil.getMapFun() as any)
  private istf = false
  private isOpenImg = false
  private scrollTop = 0 // 表格的滚动条位置

  @Watch('$store.state.weatherDialog', {immediate: true})
  getData(data: any) {
    if (data) {
      if (data && data.show) {
        this.visible = true
      }
      this.dialogData = data
    }
  }

  private openImg(flag: boolean) {
    this.isOpenImg = !flag
    if (flag) {
      this.scrollTop = (this.$refs as any).tfTable.$el.querySelector('.el-table__body-wrapper').scrollTop
    } else {
      setTimeout(() => {
        (this.$refs as any).tfTable.$el.querySelector('.el-table__body-wrapper').scrollTop = this.scrollTop;
      }, 200)
    }
  }

  private openWeatherImg() {
    DialogUtil.showDialog(WeatherImgTemp, DialogType.WEATHER_IMG, {
      dialogData: {
        title: this.$t('message.weather.legend'),
        vueName: DialogType.WEATHER_IMG
      },
      infoData: {
        data: {}
      },
      show: true
    })
  }

  private rowStyle(row: any) {
    let style = {height: "40px", color: ''};
    if (row.row.isCurrent === 1) {
      style.color = 'red';
    }
    return style;
  }

  private addWeather() {
    let isproStr = ''
    if (this.isPro) {
      isproStr = 'https://api3.myships.com'
    }

    this.mapFun.clearJfWeatherIsobar();
    this.mapFun.clearJfParticle()
    switch (this.weather) {
      case 'wd':
        this.istf = false
        this.mapFun.loadTemp(isproStr + '/jfcfdt/meteo-open/s01/' + this.formatTime() + '/3857/{z}/{y}/{x}/temp-surface.png')
        break
      case 'qy':
        this.istf = false
        this.mapFun.loadPressure(isproStr + '/jfcfdt/meteo-open/s01/' + this.formatTime() + '/3857/{z}/{y}/{x}/pressure-surface.png');
        //气压等值线
        this.mapFun.loadIsobar(isproStr + '/jfcfdt/meteo-open/s01/' + this.formatTime() + '/pressure-surface-4326-isoline.json')
        break
      case 'fc':
        this.istf = false
        this.mapFun.loadWind(isproStr + '/jfcfdt/meteo-open/s01/' + this.formatTime() + '/3857/{z}/{y}/{x}/wind-surface.png');
        this.mapFun.loadNineParticleWind(isproStr + '/jfcfdt/meteo-open/s01/' + this.formatTime() + '/wind-surface-3857.png')
        break
      case 'yl':
        this.istf = false
        this.mapFun.loadSeacurrents(isproStr + '/jfcfdt/meteo-open/s02/' + this.formatTime() + '/3857/{z}/{y}/{x}/seacurrents-surface.png');
        this.mapFun.loadNineParticleSeacurrents(isproStr + '/jfcfdt/meteo-open/s02/' + this.formatTime() + '/seacurrents-surface-3857.png')
        break
      case 'tf': {
        this.istf = true
        let coords24 = [{lon: 127, lat: 34}, {lon: 127, lat: 22}, {lon: 119, lat: 18}, {lon: 119, lat: 11}, {
          lon: 113,
          lat: 2.4
        }, {lon: 105, lat: 0}];
        let coords48 = [{lon: 132, lat: 34}, {lon: 132, lat: 15}, {lon: 120, lat: 0}, {lon: 105, lat: 0}];
        //绘制警戒线
        this.mapFun.drawLine("24", coords24, "#e53881", 2, "24小时预警线");
        this.mapFun.drawLine("48", coords48, "#e53881", 2, "48小时预警线", true);
        this.mapFun.showjjx()
        this.getTyphoonList()
      }
        break
    }
  }

  private toggleTyphoon(row: any, isShow: boolean) {
    row.isShow = isShow;
    if (isShow) {
      let tData = {
        hyTyphoonId: row.hyTyphoonId,
        seq: row.name,
        code: row.typhoonCode,
        pubTime: row.beginTime
      };
      this.drowTyphoon(tData);
    } else {
      this.closeOneTyphoon(row.hyTyphoonId);
    }
  }

  private closeOneTyphoon(code: string) {
    this.mapFun["delTyphoon"](code);
  }

  private async drowTyphoon(param: any) {
    let typeoonDetailList: any = await HttpApi.getTyphoonInfo(param.hyTyphoonId);
    if (typeoonDetailList.code === '0') {
      let data = this.jsonFormatting(typeoonDetailList.data);
      let lon = typeoonDetailList.data[typeoonDetailList.data.length - 1].lon;
      let lat = typeoonDetailList.data[typeoonDetailList.data.length - 1].lat;
      this.mapFun["setCenter"]([lon, lat]);
      this.mapFun["setZoom"](5);
      param.data = data;
      //tdata数据 1000000 是圈大小 1 是风圈变换速度 id 用于区别不同台风  === 1068：经过多次调试值，原值1000，
      this.mapFun["showTyphoon"](param, 1068, 0.5, param.hyTyphoonId);
    }
  }

  private jsonFormatting(objList: any) {
    let data: any[] = [];
    let itemForecastlist: any = [];
    for (const item of objList) {
      let obj: any = {
        time: item.typhoonTime,
        lon: item.lon,
        lat: item.lat,
        windSpeed: item.maxWindGust,
        airPressure: item.airPressure,
        maxWindSpeed: item.maxWindGust,
        maxRadius7: item.rad_nwq34kt,
        maxRadius10: item.rad_nwq50kt,
        radius7: item.rad_nwq34kt,
        radius10: {
          "ne": item.rad_nwq34kt,
          "nw": item.rad_nwq34kt,
          "se": item.rad_nwq34kt,
          "sw": item.rad_nwq34kt
        },//radius10设置默认值  原值：item.rad_nwq50kt
        direction: item.moveDirection,
        forcast: [],
        speed: Number(item.moveSpeed) //Math.round(Number(item.moveSpeed)*3.6*100)/100 //米/每秒 转为 千米/小时 四舍五入
      };
      let itemForeca = item.forecastlist;
      if (item.forecastlist && item.forecastlist.length > 0) {
        itemForecastlist = item.forecastlist;
      } else {
        let itemForecastItems: any = [];
        for (const itemForecastItem of itemForecastlist) {
          if (new Date(item.typhoonTime + ':00:00').getTime() < new Date(itemForecastItem.typhoonTime + ':00:00').getTime()) {
            itemForecastItems.push(itemForecastItem);
          }
        }
        itemForeca = itemForecastItems;
      }
      for (const item1 of itemForeca) {
        let obj1: any = {
          time: item1.typhoonTime,
          lon: item1.lon,
          lat: item1.lat,
          windSpeed: item1.maxWindGust,
          airPressure: item1.airPressure,
          maxWindSpeed: item.maxWindGust,
          maxRadius7: item.rad_nwq34kt,
          maxRadius10: item.rad_nwq50kt,
          radius7: item1.rad_nwq34kt,
          radius10: {
            "ne": item.rad_nwq34kt,
            "nw": item.rad_nwq34kt,
            "se": item.rad_nwq34kt,
            "sw": item.rad_nwq34kt
          },//radius10设置默认值,暂时为rad_nwq34kt值  原值：item.rad_nwq50kt
          direction: item1.moveDirection,
          forcast: [],
          speed: Number(item.moveSpeed) //Math.round(Number(item.moveSpeed)*100)/100 //米/每秒 转为 千米/小时 四舍五入
        };
        obj.forcast.push(obj1)
      }
      data.push(obj);
    }
    return data;
  }

  private getTyphoonList() {
    HttpApi.getTyphoonList().then((res: any) => {
      if (res.code === '0') {
        this.initHistoryTyphoon(res.data)
      }
    })
  }

  private initHistoryTyphoon(typhoonList: any) {
    for (const item of typhoonList) {
      let beginTime = this.dateFormat(item.beginTime);
      let endTime = this.dateFormat(item.endTime);
      let data = {
        name: item.ename,
        typhoonCode: item.typhoonCode,
        beginTime: beginTime,
        endTime: endTime,
        isCurrent: item.isCurrent,

        hyTyphoonId: item.hyTyphoonId,
        seq: item.name ? item.name : item.ename,
        code: item.typhoonCode,
        pubTime: item.beginTime,
        isShow: item.isCurrent
      };
      if (item.dataSource === "ngfs") {
        data.isShow = 0;
        this.typhoonData.push(data)
      }
    }
  }

  private dateFormat(str: string) {
    if (str) {
      return str.substr(0, 13)
    } else {
      return ""
    }
  }

  private resetWeather() {
    this.weather = '';
    this.istf = false;
    (storeUtil.getMapFun() as any).clearJfWeather();
    //删除九方气象等值线
    (storeUtil.getMapFun() as any).clearJfWeatherIsobar();
    (storeUtil.getMapFun() as any).clearJfParticle();

    for (let i = 0; i < this.typhoonData.length; i++) {
      let item = this.typhoonData[i];
      //if(item.checked){
      item.isShow = 0;
      //}
    }
    (storeUtil.getMapFun() as any)["hideTyphoon"]();

  }

  private formatTime() {
    const time = new Date()
    const year: any = time.getUTCFullYear()
    const month: any = time.getUTCMonth() + 1 > 9 ? (time.getUTCMonth() + 1) : '0' + (time.getUTCMonth() + 1)
    const day: any = time.getUTCDate() > 9 ? time.getUTCDate() : '0' + time.getUTCDate()
    const hours: any = time.getUTCHours()
    let hour = '000'
    if (hours <= 3) {
      hour = '000'
    } else if (hours <= 6) {
      hour = '003'
    } else if (hours <= 9) {
      hour = '006'
    } else if (hours <= 12) {
      hour = '009'
    } else if (hours <= 15) {
      hour = '012'
    } else if (hours <= 18) {
      hour = '015'
    } else if (hours <= 21) {
      hour = '018'
    } else if (hours <= 24) {
      hour = '021'
    }
    return year + '/' + month + '/' + day + '/' + hour
  }

  private cancel() {
    this.resetWeather()
    this.mapFun.hidejjx()
  }
}
</script>

<style scoped lang="scss">
.show-typhoon {
  width: 60px;
  height: 28px;
  border-radius: 6px;
  padding: 1px 0 0 0;
  font-size: 12px;
  font-weight: 400;
  margin-right: 0 !important;
  background: #FFFFFF !important;
  color: var(--theme-color) !important;

  &:hover {
    background: rgba(45, 70, 155, 0.15) !important;
  }
}

.weather-dialog-box {
  width: 100%;

  ::v-deep .el-dialog {
    position: absolute;
    top: 6.25rem;
    right: 1.25rem;

  }

  .weather-content {
    width: 100%;

    .weather-header {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .btn {
        background: #FFFFFF !important;
        border: 1px solid #2D469B !important;
        color: #2D469B !important;
        width: 77px;
        height: 26px;
        margin-left: 20px;
      }

      .tf-btn {
        background: #FFFFFF !important;
        border: 1px solid #2D469B !important;
        color: #2D469B !important;
        height: 26px;
        margin-left: 20px;
      }
    }

    .item {
      height: 1.875rem;
      display: flex;
      justify-content: left;
      align-items: center;

      .title {
        margin-right: 1.25rem;
        width: 6.25rem;
        flex-shrink: 0;
      }
    }

    //.btn {
    //  width: 100%;
    //  height: 1.75rem;
    //  display: flex;
    //  justify-content: right;
    //
    //  .el-button {
    //    width: 3.5rem;
    //    height: 100%;
    //    display: flex;
    //    align-items: center;
    //    justify-content: center;
    //    border-radius: 1.25rem;
    //  }
    //}
  }
}

.tftl {
  padding: 20px;
  border-radius: 10px;
  background: rgba(27, 26, 72, 0.75);
  text-align: center;

  .img {
    width: 337px;
    height: 400px;
  }
}
</style>
