<template>
  <div class="amap-page-container" style="height: calc(100vh - 84px);">
    <el-amap
      ref="map"
      vid="amapDemo"
      :amap-manager="amapManager"
      :zoom="zoom"
      :center="center"
      :events="events"
      class="amap-demo"
      :plugin="plugin"
    >
      <!-- 用户标记 -->
      <el-amap-marker
        v-for="(marker, index) in markers"
        :key="marker.id"
        :position="marker.mapcenter | rebuildUserCenter(marker.mapcenter)"
        :visible="markerVisible"
        :content="marker.name | rebuildContent(marker.UserDaviceNum, marker.police)"
        :vid="index"
        :clickable="true"
        :events="checkPermission(['manage isadmin']) ? rebuildEvent(marker) : ''"
        :z-index="markerUserZIndex"
      ></el-amap-marker>
      <el-amap-circle-marker
        v-for="marker in markersDevice"
        :key="marker.id"
        :visible="markersDeviceVisible"
        :center="marker.devicecoord | deviceLocationFilter(marker.devicecoord)"
        :radius="13"
        :fill-color="marker.devicepolice | deviceStatusFilter('color')"
        :fill-opacity="1"
        :stroke-color="'#ccc'"
        :stroke-opacity="0.9"
        :events="markerClickEvent(marker)"
      ></el-amap-circle-marker>
      <!-- 右上角设备和用户切换按钮 -->
      <div class="toolbar">
        <el-button v-if="leftDeviceName != '全部设备' " type="primary" size="mini" round @click="allDevices">全部设备</el-button>
        <!-- <el-button v-if="checkPermission(['manage device'])" type="primary" size="mini" round @click="allDevices">全部设备</el-button> -->
        <el-switch
          v-model="markersDeviceVisible"
          active-text="设备"
        >
        </el-switch>
        <el-switch
          v-model="markerVisible"
          active-text="用户"
        >
        </el-switch>
      </div>
    </el-amap>
    <!-- 点击地图标记打开的信息窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogTableVisible"
      width="20%"
      :modal="false"
      custom-class="zero-dialog"
    >
      <el-table :data="gridData" :show-header="false">
        <el-table-column property="title"></el-table-column>
        <el-table-column property="content"></el-table-column>
      </el-table>
    </el-dialog>
    <!-- 用户的设备列表 -->
    <div v-if="deviceListVisible" class="zero-user-devices">
      <el-collapse v-if="checkPermission(['manage isadmin'])" v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">
            设备列表 - {{ leftDeviceName }}
          </template>
          <el-table :data="markersDevice" style="100%" max-height="700">
            <el-table-column property="devicenum" label="设备编号" width="200px"></el-table-column>
            <el-table-column property="deviceinfo" label="位置" width="200px"></el-table-column>
            <el-table-column property="nd" label="值" width="40px"></el-table-column>
            <el-table-column property="devicepolice" label="状态">
              <template slot-scope="scope">
                <el-tag effect="dark" :hit="false" style="border-color: #ffffff;" :color="scope.row.devicepolice | deviceStatusFilter('color')" size="mini">
                  {{ scope.row.devicepolice | deviceStatusFilter('status') }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <el-collapse v-if="checkPermission(['manage device'])" v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">
            {{ leftDeviceName }}
          </template>
          <el-table :data="markersDevice" style="100%" max-height="700">
            <el-table-column property="devicenum" label="设备编号" width="200px"></el-table-column>
            <el-table-column property="deviceinfo" label="位置" width="200px"></el-table-column>
            <el-table-column property="nd" label="值" width="40px"></el-table-column>
            <el-table-column property="devicepolice" label="状态">
              <template slot-scope="scope">
                <el-tag effect="dark" :hit="false" style="border-color: #ffffff;" :color="scope.row.devicepolice | deviceStatusFilter('color')" size="mini">
                  {{ scope.row.devicepolice | deviceStatusFilter('status') }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import VueAMap from 'vue-amap';
import { AMapManager } from 'vue-amap';
import { devices, users, deviceinfo } from '@/api/map';
import checkPermission from '@/utils/permission';
Vue.use(VueAMap);

// 初始化vue-amap
VueAMap.initAMapApiLoader({
  // 高德的key
  key: '95cc1b89d62f020ce5a21ec503daef6c',
  // 插件集合
  plugin: [
    'AMap.Autocomplete',
    'AMap.PlaceSearch',
    'AMap.Scale',
    'AMap.OverView',
    'AMap.ToolBar',
    'AMap.MapType',
    'AMap.PolyEditor',
    'AMap.CircleEditor',
  ],
  // 高德 sdk 版本，默认为 1.4.4
  v: '1.4.15',
  uiVersion: '1.0.11',
});

export default {
  filters: {
    rebuildContent(company, deviceCount, alarmCount) {
      let mcontent = '<div class="mapIcon"><span class="mapIcon_title">%name</span><span class="mapIcon_num_all">%num</span><span class="mapIcon_num">%alarm</span></div>';
      mcontent = mcontent.replace(/%name/, company).replace(/%num/, deviceCount).replace(/%alarm/, alarmCount);
      return mcontent;
    },
    rebuildUserCenter(mapcenter) {
      if (mapcenter === null) {
        return '';
      }
      mapcenter = mapcenter.replace(/\s*/g, '');
      return mapcenter.split(',');
    },
    deviceLocationFilter(center) {
      if (center === null) {
        return '';
      }
      center = center.replace(/\s*/g, '');
      return center.split(',');
    },
    deviceStatusFilter(status, cate) {
      var statuses = [];
      statuses[1] = { color: '#1c7a17', name: '正常' };
      statuses[2] = { color: '#f6e032', name: '错误' };
      statuses[3] = { color: '#f6e032', name: '传感器故障' };
      statuses[4] = { color: '#f30016', name: '报警' };
      statuses[5] = { color: '#f42f18', name: '低报' };
      statuses[6] = { color: '#97000b', name: '高报' };
      statuses[7] = { color: '#f6e032', name: '通信故障' };
      statuses[8] = { color: '#f6e032', name: '超量程' };
      statuses[9] = { color: '#747677', name: '离线' };
      statuses[10] = { color: '#f6e032', name: '电量低' };
      statuses[11] = { color: '#f6e032', name: '主电故障' };
      statuses[12] = { color: '#f6e032', name: '备电故障' };
      statuses[13] = { color: '#f6e032', name: '无此节点' };
      statuses[14] = { color: '#f6e032', name: '低电压' };
      statuses[15] = { color: '#f6e032', name: '故障' };
      statuses[16] = { color: '#97000b', name: '报警联动' };
      if (cate === 'color') {
        return statuses[status].color;
      } else if (cate === 'status') {
        return statuses[status].name;
      }
    },
  },
  data(){
    const _this = this;
    return {
      map: {},
      amapManager: new AMapManager(),
      zoom: 6,
      center: [114.505208, 38.045474],
      events: {
        init: (o) => {
          o.setMapStyle('amap://styles/normal');
          // console.log(o.getCenter());
          // console.log(this.$refs.map.$$getInstance());
          o.getCity(result => {
            // console.log(result);
          });
        },
        'moveend': () => {
        },
        'zoomchange': () => {
          _this.zoom = this.$refs.map.$$getInstance().getZoom();
        },
        'click': (e) => {
          // alert('map clicked');
        },
      },
      plugin: [{
        pName: 'ToolBar',
        position: 'LB',
      }, {
        pName: 'MapType',
        defaultType: 0,
        events: {
          init(o) {
            console.log(o);
          },
        },
      }],
      markers: [],
      markerVisible: true,
      markersDevice: [],
      markersDeviceVisible: false,
      gridData: {}, // 设备信息
      dialogTitle: '设备信息', // 设备信息标题
      dialogTableVisible: false, // 设备信息是否显示
      deviceListVisible: true, // 用户设备列表是否显示
      activeNames: ['1'], // 左侧设备列表默认打开
      markerUserZIndex: 100,
      deviceAll: undefined,
      leftDeviceName: '全部设备',
    };
  },
  watch: {
  },
  mounted() {
  },
  created() {
    this.$store.dispatch('app/toggleSideBar');
    // const users = devices.users();
    users()
      .then(res => {
        this.markers = res.data;
      });
    devices({})
      .then(res => {
        this.markersDevice = res.data;
      });
  },
  methods: {
    checkPermission,
    allDevices() {
      devices()
        .then(res => {
          this.leftDeviceName = '全部设备';
          this.markersDevice = res.data;
          this.zoom = 6;
        });
    },
    getUserDevices(center) {
      // alert(userid);
      this.zoom = 12;
      this.center = center;
      this.markerVisible = true;
      this.markersDeviceVisible = true;
    },
    rebuildEvent(marker) {
      var mapcenter = marker.mapcenter.replace(/\s*/g, '');
      const that = this;
      const position = mapcenter.split(',');
      return {
        click(e) {
          // alert(that.zoom);
          that.leftDeviceName = marker.name;
          that.getUserDevices(position);
          that.deviceListVisible = true;
          that.markerUserZIndex = 1000;
          that.getUserDeviceList(marker.id);
        },
      };
    },
    markerClickEvent(marker) {
      const that = this;
      return {
        click(e) {
          that.getUserDeviceInfo(marker.id);
        },
      };
    },
    // 获取单个用户下的设备
    getUserDeviceList(uid) {
      devices({ uid: uid })
        .then(res => {
          this.markersDevice = res.data;
        });
    },
    // 获取设备详细信息
    getUserDeviceInfo(id) {
      deviceinfo(id)
        .then(res => {
          this.dialogTableVisible = true;
          const deviceInfo = res.data;
          this.gridData = [
            {
              title: '设备编号',
              content: deviceInfo.devicenum,
            },
            {
              title: '坐标',
              content: deviceInfo.devicecoord,
            },
            {
              title: '设备类型',
              content: deviceInfo.tname,
            },
            {
              title: '用户',
              content: deviceInfo.usernickname,
            },
            {
              title: '检测介质',
              content: deviceInfo.gas,
            },
            {
              title: '状态',
              content: deviceInfo.status_name,
            },
            {
              title: '安装位置',
              content: deviceInfo.deviceinfo,
            },
            {
              title: '联系人',
              content: deviceInfo.devicelinkman,
            },
            {
              title: '电话',
              content: deviceInfo.devicephone,
            },
          ];
        });
    },
  },
};
</script>

<style>
.amap-demo {
  height: 300px;
}
.mapIcon{
  vertical-align: middle;
  color: #555;
  background-color: #fffeef;
  font-size: 12px;
  white-space: nowrap;
  position: relative;
  border: 1px solid #8e8e8e;
  width: auto;
  border-radius: 5px 5px 5px 0;
  height: 23px;
  line-height: 23px;
  /* top: 25px; */
  /* left: -37px; */
}
.mapIcon_title{
  padding: 5px;
  border-radius: 5px 0 0 0;
}
.mapIcon_num{
  padding: 0 5px;
  display: inline-block;
  height: 100%;
  color: #fff;
  background-color: #dc3912;
  border-radius: 0 5px 5px 0;
}
.mapIcon_num_all{
  padding: 0 5px;
  display: inline-block;
  height: 100%;
  color: #fff;
  background-color: #23e610;
  /* border-radius: 0 5px 5px 0; */
}
.mapIcon:before, .mapIcon:after{
  content: '';
  display: block;
  position: absolute;
  width: 0;
  height: 0;
  border: solid rgba(0,0,0,0);
  border-width: 6px;
  /* left: 40px; */
}
.mapIcon:before{
  bottom: -13px;
  border-top-color: #8e8e8e;
}
.mapIcon:after{
  bottom: -12px;
  border-top-color: #fffeef;
}
.toolbar{
  position: fixed;
  top: 120px;
  right: 40px;
}
.zero-user-devices{
  position: fixed;
  top: 100px;
  padding: 0px 10px 0px 10px;
  background-color: #ffffff;
}
</style>
