<template>
  <div class="battle-warp">
    <div class="map-card-wrap" :class="showType === 1 ? 'map' : ''">
      <div class="map-card-wrap__info" :class="showType === 1 ? 'map' : ''">
        <van-row class="map-card-wrap__info-box" :gutter="3" type="flex" justify="center">
          <van-col :span="6" class="item" v-for="(item, index) of cardList" :key="index">
            <div class="name">{{ item.name }}</div>
            <div class="value">{{ item.value }} <span class="unit">{{ item.unit }}</span></div>
          </van-col>
        </van-row>
        <div class="map-card-wrap__info-search">
          <van-dropdown-menu active-color="#1989fa">
            <van-dropdown-item v-model="tradeStatus" :options="tradeStatusList" @change="dropLoad" />
            <van-dropdown-item v-model="runStatus" :options="runStatusList" @change="dropLoad" />
          </van-dropdown-menu>
          <div><van-icon name="search" /></div>
        </div>
      </div>
    </div>
    <div class="list-icon" :class="showType === 1 ? 'list' : 'map'" @click="mapToListEvent">
      <div style="font-size: 14px;margin-top: 42px;">{{ showType === 1 ? '列表' : '地图' }}</div>
    </div>
    <el-bmap v-if="nextTickStatus && showType === 1" vid="bmap" :zoom="zoom" :center="center" class="bm-view" :style="mapStyle">
      <el-bmap-marker v-for="(marker, index) in markers" :key="index" :icon="marker.icon" :visible="marker.visible" :position="marker.position" :title="marker.title" :label="marker.label" :events="marker.events" :vid="index" :enable-dragging="marker.enableDragging"></el-bmap-marker>
    </el-bmap>
    <div v-else-if="nextTickStatus && showType === 2" class="list-wrap">
      <div class="list-wrap__item" v-for="(item, index) in truckList" :key="index">
        <div class="item-header">
          <div class="text-bold">{{ item.carNumber }}<span class="text-normal">({{ item.linked === 1 ? '其他' : '自营' }})</span></div>
          <div>今日里程<span class="color-blue">{{ item.mileage || '-' }}</span>公里</div>
        </div>
        <div class="item-info">
          <div class="label item-info__user" style="padding-left: 0" v-if="item.truckDriverList.length > 0">
            <div class="driver-wrap">
              <div v-for="(driver, driverIndex) in item.truckDriverList" :key="driverIndex" class="driver-list">{{ truckToDriverUser(driver) }}</div>
            </div>
            <div>{{ truckToDriverMobile(item.truckDriverList[0].driverName) }}</div>
          </div>
          <div class="label speed">
            <span>{{ item.speed || '-' }}</span>公里/小时
            <span class="status" :class="'status__' + item.speedStatus">{{ truckStatusList[item.speedStatus] }}</span>
          </div>
          <div class="label local">{{ item.currAddress || '-' }}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import 'vue-bmap-gl/dist/style.css'
import axios from 'axios'
// import { $districtList, $userFindConfigAreaList } from '@/service/user'
import { $gasdataGaugeAll } from '@/service/gasdata'
// import { currency, formateZeroToBar } from '@/utils/filters'
// import { MarkerWindow, AreaDataAnalysis } from './components'
// import { mapJsonData } from '@/mock/map'
export default {
  name: 'battle',
  // components: { MarkerWindow, AreaDataAnalysis },
  data() {
    return {
      map: null,
      showType: 1,
      mapStyle: {
        width: '100%',
        height: '100%'
      },
      center: [116.23228, 35.7127],
      zoom: 8,
      heading: 0,
      index: 1,
      timer: null,
      mapHeight: 400,
      cardList: [{
        name: '在线/总量',
        value: '0/0',
        unit: '辆'
      }, {
        name: '今日总里程',
        value: '0',
        unit: '公里'
      }, {
        name: '今日总耗能',
        value: '0',
        unit: '公斤'
      }, {
        name: '今日总减碳',
        value: '0',
        unit: '公斤'
      }],
      tradeStatus: '',
      tradeStatusList: [
        { text: '全经营类型', value: '' },
        { text: '自营', value: 0 },
        { text: '外协', value: 1 }
      ],
      runStatus: '',
      runStatusList: [
        { text: '全行驶状态', value: '' },
        { text: '行驶', value: 0 },
        { text: '静止', value: 1 },
        { text: '离线', value: 2 }
      ],
      truckStatusList: {
        0: '行驶中',
        1: '静止中',
        2: '离线中'
      },
      truckList: [],
      markers: [],
      nextTickStatus: true
    }
  },
  watch: {},
  computed: {},
  created() {
    this.dragendPointer()
    this.timer = setInterval(() => {
      this.dragendPointer()
    }, 60000)
  },
  mounted() {
    // 重置地图高度
    this.mapHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    async queryCurrAddress(location) {
      const data = await axios.post(process.env.VUE_APP_BAIDU_URL + '?output=json&ak=Zvd6FzmertUwjhZih5Zfq0D8uTUhvqsH&coordtype=wgs84ll&location=' + location).then(response => {
        return response.data
      })

      if (data.hasOwnProperty('result')) {
        return data.result.addressComponent
      } else {
        return '-'
      }
    },
    angle(start, end) {
      // 通过 a、b 确定角度所处的象限
      const a = start[0] - end[0]
      const b = start[1] - end[1]
      // eslint-disable-next-line camelcase
      const a_c = Math.abs(a)
      // eslint-disable-next-line camelcase
      const b_c = Math.abs(b)
      // 获取得三角形的斜边 Math.hypot();
      const c = Math.hypot(a_c, b_c)
      // 计算弧度
      // eslint-disable-next-line camelcase
      const radina = Math.acos(a_c / c)
      // 计算角度
      let angleVal = Math.floor(radina * 180 / Math.PI)
      // 处理最终需要旋转的角度
      if (a > 0) {
        // 第二、三象限
        if (b > 0) {
          // 三
          angleVal = 90 + 90 - angleVal
        } else {
          angleVal = -180 + angleVal
        }
      } else {
        // 一、四象限
        if (b > 0) {
          // 四
          // eslint-disable-next-line no-self-assign
          angleVal = angleVal
        } else {
          // 一
          angleVal = -angleVal
        }
      }
      return angleVal
    },
    mapToListEvent() {
      this.showType = this.showType === 1 ? 2 : 1
    },
    truckToDriverUser(driver) {
      // 解释司机个人信息
      const driverUserInfo = driver.driverName ? driver.driverName.split('/') : []
      return driverUserInfo.length >= 1 ? driverUserInfo[0] : '-'
    },
    truckToDriverMobile(info) {
      if (info.indexOf('/') !== -1) {
        const userinfo = info.split('/')

        return userinfo[1] || '-'
      } else {
        return '-'
      }
    },
    dropLoad() {
      this.dragendPointer()
    },
    dragendPointer() {
      const params = {}

      this.markers = []
      if (this.tradeStatus !== '') {
        params.linked = this.tradeStatus
      }
      if (this.runStatus !== '') {
        params.speedStatus = this.runStatus
      }
      $gasdataGaugeAll(params).then(response => {
        const data = response.carMonitorVos

        // 统计数据
        this.cardList[0].value = response.onLine + '/' + response.total
        this.cardList[1].value = response.mileage.toFixed(0)
        this.cardList[2].value = response.consumption
        this.cardList[3].value = response.carbon
        this.truckList = data

        data.forEach(async item => {
          this.markerInfo(item)
          // 根据金纬度获取地理位置信息
          const addressInfo = await this.queryCurrAddress(item.lat + ',' + item.lng)
          const currAddress = addressInfo.province + addressInfo.city + addressInfo.district + addressInfo.street

          if (item.hasOwnProperty('currAddress')) {
            item.currAddress = currAddress
          } else {
            this.$set(item, 'currAddress', currAddress)
          }
        })
      })
    },
    markerInfo(item) {
      const info = {
        icon: {},
        label: {},
        visible: true,
        enableDragging: false
      }

      info.label = {
        content: item.carNumber,
        offset: [-23, -25],
        style: {
          borderWidth: 0,
          padding: '3px 10px',
          borderRadius: '4px',
          boxShadow: '0px 0px 9px 1px rgba(28, 29, 33, 0.16)'
        }
      }
      info.icon = {
        url: require('@/assets/images/navigation/navigation@2x.png'),
        size: [20, 26]
      }
      info.position = [item.lng, item.lat]

      this.markers.push(info)
    }
  }
}
</script>
