<template>
  <div class="nodeMap-contenter">
    <!-- 地图 -->
    <div class="map-cont">
      <a-row class="map-title" :getter="24">
        <span>智享亿家生活垃圾分类网点地图</span>
        <a-icon @click="isFullscreenMap" :style="{fontSize:'30px',padding: '7px',float: 'right', cursor: 'pointer'}" :type="isMapFull ?'fullscreen-exit':'fullscreen'" />
      </a-row>
      <!-- 地图容器 -->
      <div id="container" :style="{height: mapHeight}">
      </div>
      <div class="map-footer">
        <a-row :getter="[24,24]">
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <div class="map-data">
              <a-icon type="team" :style="{color:'#83ace1',fontSize:'20px',padding:'5px',backgroundColor:'#FFF',borderRadius:'8px'}" />
              <span>&nbsp;&nbsp;用户总数 {{ userTotal }} 个</span>
            </div>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <div class="map-data">
              <a-icon type="rest" :style="{color:'#83ace1',fontSize:'20px',padding:'5px',backgroundColor:'#FFF',borderRadius:'8px'}" />
              <span>&nbsp;&nbsp;智能收集箱 {{ deviceTotal }} 台</span>
            </div>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <div class="map-data">
              <a-icon type="shop" :style="{color:'#83ace1',fontSize:'20px',padding:'5px',backgroundColor:'#FFF',borderRadius:'8px'}" />
              <span>&nbsp;&nbsp;智能兑换亭 {{ sellerTotal }} 台</span>
            </div>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <div class="map-data">
              <a-icon type="hdd" :style="{color:'#83ace1',fontSize:'20px',padding:'5px',backgroundColor:'#FFF',borderRadius:'8px'}" />
              <span>&nbsp;&nbsp;智能兑换机 {{ machineTotal }} 台</span>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>

    <div v-show="!isMapFull" class="data-cont">
      <!-- 实时轮播数据 -->
      <a-row :gutter="[24,24]">
        <a-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="16"
          :xxl="16">
          <div class="switper-cont">
            <div class="data-title">实时投递数据</div>
            <div class="chart-box data-form">
              <div class="swipter-title">
                <a-row :gutter="0">
                  <a-col style="padding: 0px 2px;text-align: center;" :span="6">投递时间</a-col>
                  <a-col style="padding: 0px 2px;text-align: center;" :span="4">投递用户</a-col>
                  <a-col style="padding: 0px 2px;text-align: center;" :span="6">投递网点</a-col>
                  <a-col style="padding: 0px 2px;text-align: center;" :span="5">投递分类</a-col>
                  <a-col style="padding: 0px 2px;text-align: center;" :span="3">投递重量(g)</a-col>
                </a-row>
              </div>
              <vue-seamless-scroll :data="deliveryLogData" :class-option="classOption" class="seamless-warp">
                <a-spin class="loading" :spinning="deliverySpinning" tip="Loading..." />
                <div class="swipter-data" v-for="item in deliveryLogData" :key="item.id">
                  <a-row :gutter="0">
                    <a-col style="padding: 0px 2px;text-align: center;" :span="6">{{ item.deliveryTime }}</a-col>
                    <a-col style="padding: 0px 2px;text-align: center;" :span="4">{{ item.customerMobile }}</a-col>
                    <a-col
                      :title="item.stationName"
                      style="padding: 0px 2px;text-align: center;white-space: nowrap;
				  				  					text-overflow: ellipsis;
				  				  					overflow: hidden;
				  				  					word-break: break-all;"
                      :span="6">
                      {{ item.stationName }}
                    </a-col>
                    <a-col style="padding: 0px 2px;text-align: center;" :span="5">{{ item.rubbishTypeDictValue }}</a-col>
                    <a-col style="padding: 0px 2px;text-align: center;" :span="3">{{ item.rubbishWeight }}</a-col>
                  </a-row>
                </div>
              </vue-seamless-scroll>
            </div>
          </div>
        </a-col>
        <a-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="8"
          :xxl="8">
          <div class="switper-cont">
            <div class="data-title">实时新增用户</div>
            <div class="chart-box data-form">
              <div class="swipter-title">
                <a-row :gutter="0">
                  <a-col style="padding: 0px 2px;text-align: center;" :span="16">注册时间</a-col>
                  <a-col style="padding: 0px 2px;text-align: center;" :span="8">用户手机</a-col>
                </a-row>
              </div>
              <vue-seamless-scroll :data="userLogData" :class-option="classOption" class="seamless-warp">
                <a-spin class="loading" :spinning="userLogSpinning" tip="Loading..." />
                <div class="swipter-data" v-for="item in userLogData" :key="item.id">
                  <a-row :gutter="0">
                    <a-col style="padding: 0px 2px;text-align: center;" :span="16">{{ item.registerTime }}</a-col>
                    <a-col style="padding: 0px 2px;text-align: center;" :span="8">{{ item.mobile }}</a-col>
                  </a-row>
                </div>
              </vue-seamless-scroll>
            </div>
            </vue-seamless-scroll>
          </div>
        </a-col>
      </a-row>
      <!-- 图表数据 -->
      <a-row :gutter="[24,24]" type="flex" justify="space-between">
        <a-col
          :xs="24"
          :sm="20"
          :md="12"
          :lg="12"
          :xl="12"
          :xxl="8">
          <div class="chart-cont">
            <div class="data-title">设备分布统计图</div>
            <chart-pie
              ref="chartPie"
              class="chart-box"
              :value="equipmentPieData"
              title=""
              unit="%"
              :color="equipmentPieColor"
              :xAxisRotate="resize"
              text="" />
          </div>
        </a-col>
        <a-col
          xs="24"
          :sm="20"
          :md="12"
          :lg="12"
          :xl="12"
          :xxl="8">
          <div class="chart-cont">
            <div class="data-title">设备数量统计对比图</div>
            <chart-bar
              ref="ChartBar"
              class="chart-box"
              :color="['#0000fe']"
              :yMax="1000"
              yUnit="台"
              :value="equipmentBarData"
              :seriesData="equipmentBarSeriesData"
              text="" />
          </div>
        </a-col>
        <a-col
          xs="24"
          :sm="20"
          :md="16"
          :lg="12"
          :xl="12"
          :xxl="8">
          <div class="chart-cont">
            <div class="data-title">项目介绍</div>
            <div class="chart-box textCount">
              全市共有党政机关、企事业单位827个，职工人数16655人。其中，市级单位334个，秦都区297个，渭城区196个；居民小区1010个（两区居民小区994个，保障房小区16个），
              物业管理小区770个（两区754个，保障房小区16个）。其中，市本级保障房小区12个，物业管理小区12个。秦都区654个（含保障房小区3个），物业管理小区584个。渭城区
              344个（含保障房小区1个），物业管理174个（含保障房小区1个）；学校（中小学、幼儿园）200所，其中，秦都区139所（中小学53所、幼儿园86所）。渭城区61所（中小
              学27所、幼儿园34所）。截止目前，城区已建成试点单位67个， 设置智能收集箱
              <span class="blue">{{ deviceTotal }}</span>组， 智能兑换亭<span class="blue">{{ sellerTotal }}</span>个， 智能兑换机<span
                class="blue">{{ machineTotal }}</span>个， 覆盖28处办公场所的177个机关事业单位，居民小区29个，企业2个，学校8个。 软件注册人数<span class="blue">{{ userTotal }}</span>人，
              周回收有害垃圾5.646公斤、 可回收物9.26吨， 日处理厨余垃圾106吨。
            </div>
          </div>
        </a-col>
      </a-row>
    </div>

  </div>
  </div>
</template>
<script>
import {
  ChartPie,
  ChartBar
} from '@/components/Echarts'
import vueSeamlessScroll from 'vue-seamless-scroll'
import {
  getUserTotal,
  getDeviceTotal,
  getOfficialPartnerTotal,
  getDeliveryCarousel,
  getCustomerCarousel,
  getExchangeMachineTotal,
  getMapStation
} from '@/api/nodeMap.js'
export default {
  name: 'NodeMap',
  components: {
    ChartPie,
    ChartBar,
    vueSeamlessScroll
  },
  data () {
    return {
      map: null, // 地图对象
      markerLayer: null, // 地图点标记对象
      infoWindow: null, // 地图信息窗口对象
      isMapFull: false, // 地图是否全屏
      userTotal: 0, // 用户总数
      deviceTotal: 0, // 设备总数
      sellerTotal: 0, // 兑换亭总数
      machineTotal: 0, // 兑换机总数
      deliverySpinning: true, // 实时投递数据loading
      userLogSpinning: true, // 实时用户数据loading
      deliveryLogData: [], // 实时投递数据
      userLogData: [], // 实时用户数据
      screenWidth: document.body.clientWidth, // 这里是给到了一个默认值
      timer: false,
      // 设备分布统计图
      equipmentPieData: [{
        name: '学校',
        value: '14'
      },
      {
        name: '居民小区',
        value: '49'
      },
      {
        name: '公共机构',
        value: '32'
      },
      {
        name: '企业',
        value: '5'
      }
      ],
      equipmentPieColor: ['#ffaa00', '#00ff00', '#00aaff', '#ff55ff', '#1dc5d4', '#8465c7', '#00ffff'],
      // 设备数量统计对比图数据
      equipmentBarData: [{
        name: '智能收集箱',
        value: 0
      },
      {
        name: '智能兑换亭',
        value: 0
      },
      {
        name: '智能兑换机',
        value: 0
      }
      ],
      equipmentBarSeriesData: ['0', '0', '0']
    }
  },
  computed: {
    resize () {
      console.log(this.screenWidth, 'this.screenWidth')
      if (this.screenWidth < 1640) {
        return 40
      } else {
        return 0
      }
    },
    mapHeight () {
      return this.isMapFull ? '80vh' : '45vh'
    },
    classOption () {
      return {
        step: 0.4, // 数值越大速度滚动越快
        limitMoveNum: 2, // 开始无缝滚动的数据量 this.dataList.length
        hoverStop: true, // 是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true, // 开启数据实时监控刷新dom
        singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 1000 // 单步运动停止的时间(默认值1000ms)
      }
    }
  },
  watch: {
    screenWidth (val) {
      // 为了避免频繁触发resize函数，使用定时器
      if (!this.timer) {
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function () {
          // that.screenWidth = that.$store.state.canvasWidth
          console.log(that.screenWidth)
          that.timer = false
        }, 400)
      }
    }
  },
  methods: {
    // 初始化地图
    initMap () {
      // 定义地图中心点坐标 默认定位在陕西省咸阳市
      var center = new TMap.LatLng(34.329828, 108.708344)
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      this.map = new TMap.Map(document.getElementById('container'), {
        center: center, // 设置地图中心点坐标
        zoom: 17.2, // 设置地图缩放级别
        pitch: 43.5, // 设置俯仰角
        rotation: 45 // 设置地图旋转角度
      })
      // 创建并初始化MultiMarker 点标记
      this.markerLayer = new TMap.MultiMarker({
        map: this.map, // 指定地图容器
        // 样式定义
        styles: {
          // 创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
          'myStyle': new TMap.MarkerStyle({
            'width': 30, // 点标记样式宽度（像素）
            'height': 30, // 点标记样式高度（像素）
            'src': '../mark.png', // 图片路径
            // 焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
            'anchor': {
              x: 16,
              y: 32
            }
          })
        },
        // 点标记数据数组
        geometries: []
      })
      // 初始化infoWindow
      this.infoWindow = new TMap.InfoWindow({
        map: this.map,
        position: new TMap.LatLng(39.984104, 116.307503),
        offset: {
          x: 0,
          y: -32
        } // 设置信息窗相对position偏移像素
      })
      this.infoWindow.close() // 初始关闭信息窗关闭
      this.markerLayer.on('mousemove', this.showMarkTitle)
      // 监听地图加载完成
      this.map.on('tilesloaded', this.getMapMark)
    },
    // 获取地图点坐标
    getMapMark () {
      getMapStation({}).then(res => {
        const list = res.data || []
        const data = []
        list.map((item, index) => {
          if (item.lat <= 85.051128 && item.lat >= -85.051128) {
            const p = {
              'id': item.id, // 点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
              'styleId': 'myStyle', // 指定样式id
              'position': new TMap.LatLng(Number(item.lat), Number(item.lng)), // 点标记坐标位置
              'properties': { // 自定义属性
                'title': item.name
              }
            }
            data.push(p)
          }
        })
        // 增加点标记
        this.markerLayer.add(data)
      })
    },
    // 显示地图标记点名称
    showMarkTitle (evt) {
      this.infoWindow.open() // 打开信息窗
      this.infoWindow.setPosition(evt.geometry.position) // 设置信息窗位置
      this.infoWindow.setContent(evt.geometry.properties.title) // 设置信息窗内容
    },
    // 获取用户总数
    getUser () {
      getUserTotal({}).then(res => {
        this.userTotal = res.data || 0
      })
    },
    // 获取设备总数
    getDevice () {
      getDeviceTotal({}).then(res => {
        this.deviceTotal = res.data || 0
        this.equipmentBarData[0].value = this.deviceTotal
        console.log(this.equipmentBarData, 'this.equipmentBarData')
      })
    },
    // 获取兑换亭总数
    getSeller () {
      getOfficialPartnerTotal({}).then(res => {
        this.sellerTotal = res.data || 0
        this.equipmentBarData[1].value = this.sellerTotal
      })
    },
    // 获取兑换机总数
    getMachine () {
      getExchangeMachineTotal({}).then(res => {
        this.machineTotal = res.data || 0
        this.equipmentBarData[2].value = this.machineTotal
      })
    },
    // 获取实时投递数据
    getDeliveryLog () {
      getDeliveryCarousel({}).then(res => {
        this.deliveryLogData = res.data.list || []
      })
    },
    // 获取实时用户数据
    getUserLog () {
      getCustomerCarousel({}).then(res => {
        this.userLogData = res.data.list || []
      })
    },
    // 地图是否全屏展示
    isFullscreenMap () {
      this.isMapFull = !this.isMapFull
    }
  },
  mounted () {
    this.initMap()
    const that = this
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
      })()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.deliverySpinning = true
      vm.userLogSpinning = true
      setTimeout(() => {
        vm.deliverySpinning = false
        vm.userLogSpinning = false
      }, 2000)
      vm.getUser()
      vm.getDevice()
      vm.getSeller()
      vm.getMachine()
      vm.getDeliveryLog()
      vm.getUserLog()
      // 5分钟轮播
      setInterval(() => vm.getDeliveryLog(), 1000 * 60 * 5)
      setInterval(() => vm.getUserLog(), 1000 * 60 * 5)
    })
  },
  beforeRouterLeave (to, from, next) {
	  next(vm => {
		  // 销毁地图
		  vm.map.destroy()
	  })
  }
}
</script>

<style lang="less" scoped="scoped">
	.nodeMap-contenter {
		width: 100%;

		.map-cont {
			width: 100%;
			margin-bottom: 20px;

			.map-title {
				background-color: #5c9eff;
				height: 45px;
				line-height: 45px;
				text-align: center;
				color: #fff;
				font-size: 20px;
			}

			.map-footer {
				background-color: #5c9eff;
				padding: 5px;
				color: #fff;
				font-size: 16px;

				.map-data {
					padding: 3px;
				}
			}
		}

		.data-cont {
			width: 100%;
		}

		.data-form {
			text-align: center;
			width: 100%;
			border: 1px solid #d6d6d6;
			border-radius: 10px;
			padding: 10px;
			overflow: hidden;
			display: flex;
			flex-direction: column;

			.seamless-warp {
				flex: 1;
				overflow: hidden;
			}

			.swipter-data {
				height: 40px;
				line-height: 40px;
			}

			.loading {
				margin-top: 50px;
			}

			.network-name {
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
			}
		}

		.switper-cont {
			height: 300px;
			padding: 20px;
			background-color: #fff;
			border-radius: 10px;
			box-shadow: 5px 5px 8px #888888;
			display: flex;
			flex-direction: column;
		}

		.data-title {
			font-size: 16px;
		}

		.data-title:before {
			content: "";
			border: 2px solid #5c9eff;
			margin-right: 20px;
		}

		.chart-box {
			flex: 1;
			width: 100%;
			margin-top: 10px;
		}

		.chart-cont {
			padding: 20px;
			height: 400px;
			background-color: #fff;
			border-radius: 20px;
			box-shadow: 5px 5px 8px #888888;
			display: flex;
			flex-direction: column;

			.textCount {
				text-indent: 2em;

				.blue {
					color: #5c9eff;
					padding: 0px 2px;
				}
			}
		}
	}
</style>
