<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)"
        :check="playAudio(marker.devicepolice)"
      ></el-amap-circle-marker>
      <!-- 应急物资 -->
      <el-amap-marker
        v-for="(marker, index) in markersGoods"
        :key="marker.id+'wz'"
        :position="marker.mapcenter | rebuildUserCenter(marker.mapcenter)"
        :visible="markersGoodsVisible"
        :content="marker.name | rebuildGoodsContent(marker.total, marker.color)"
        :vid="index"
        :clickable="true"
        :events="checkPermission(['manage isadmin']) ? rebuildGoodsEvent(marker) : ''"
        :z-index="markerUserZIndex"
      ></el-amap-marker>
      <!-- 右上角设备和用户切换按钮 -->
      <div class="toolbar">
        <el-button 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-button type="primary" size="mini" round @click="getDangerDeviceList">隐患设备</el-button>
        <el-switch
          v-model="markersGoodsVisible"
          active-text="应急物资"
        >
        </el-switch>
        <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="35%"
      :modal="false"
      top="20vh"
      custom-class="zero-dialog"
    >
      <el-table :data="gridData" :show-header="false">
        <el-table-column property="title" width="180px"></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" @row-click="openDeviceBox">
            <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: {
    rebuildGoodsContent(name, count, color) {
      let mcontent = '<div class="mapIcon"><span class="mapIcon_title">%name</span><span class="mapIcon_num_all" style="background-color:%color">%num</span></div>';
      mcontent = mcontent.replace(/%name/, name).replace(/%num/, count).replace(/%color/, color);
      return mcontent;
    },
    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 {
      markersGoodsVisible: false,
      markersGoods: [{
        id: 1,
        mapcenter: '114.209927,38.224691',
        name: '应急物资1',
        total: 200,
        color: '#23e610',
      }, {
        id: 2,
        mapcenter: '114.209927,38.221291',
        name: '应急物资2',
        total: 20,
        color: '#dd000e',
      }],
      audio: new Audio('/audio/alarm.wav'),
      audio_play: false,
      intervalId: null,
      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;
      });
    this.dataRefresh();
  },
  destroyed(){
    // 在页面销毁后，清除计时器
    this.clearIntv();
  },
  methods: {
    checkPermission,
    allDevices() {
      this.clearIntv();
      this.dataRefresh();
      devices()
        .then(res => {
          this.leftDeviceName = '全部设备';
          this.markersDevice = res.data;
          this.zoom = 6;
          this.markersDeviceVisible = true;
          this.markerVisible = false;
        });
    },
    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);
        },
      };
    },
    // 应急物资
    rebuildGoodsEvent(marker) {
      var mapcenter = marker.mapcenter.replace(/\s*/g, '');
      const that = this;
      const position = mapcenter.split(',');
      return {
        click(e) {
          that.zoom = 15;
          that.center = position;
        },
      };
    },
    markerClickEvent(marker) {
      const that = this;
      return {
        click(e) {
          that.getUserDeviceInfo(marker.id);
        },
      };
    },
    // 获取单个用户下的设备
    getUserDeviceList(uid) {
      // 停止定时器
      this.clearIntv();
      devices({ uid: uid })
        .then(res => {
          this.markersDevice = res.data;
        });
      this.dataRefresh(uid);
    },
    // 获取隐患设备
    getDangerDeviceList() {
      // 停止定时器
      this.clearIntv();
      devices({ devicestatus: 7 })
        .then(res => {
          this.markersDevice = res.data;
          this.markersDeviceVisible = true;
          this.markerVisible = false;
        });
      // this.dataRefresh();
    },
    // 获取设备详细信息
    getUserDeviceInfo(id) {
      deviceinfo(id)
        .then(res => {
          const deviceInfo = res.data;
          this.center = deviceInfo.devicecoord.replace(/\s*/g, '').split(',');
          this.dialogTableVisible = true;
          this.markersDeviceVisible = true;
          this.gridData = [
            {
              title: '设备编号',
              content: deviceInfo.devicenum,
            },
            {
              title: '坐标',
              content: deviceInfo.devicecoord,
            },
            {
              title: '设备类型',
              content: deviceInfo.tname,
            },
            {
              title: '用户',
              content: deviceInfo.usernickname,
            },
            {
              title: '检测介质',
              content: deviceInfo.gas,
            },
            {
              title: '切断装置',
              content: this.shutoffDevice(deviceInfo.shutoff_type),
            },
            {
              title: '切断装置状态',
              content: this.shutoffStatus(deviceInfo.shutoff_status),
            },
            {
              title: '状态',
              content: deviceInfo.status_name,
            },
            {
              title: '安装位置',
              content: deviceInfo.deviceinfo,
            },
            {
              title: '联系人',
              content: deviceInfo.devicelinkman,
            },
            {
              title: '电话',
              content: deviceInfo.devicephone,
            },
          ];
        });
    },
    // 切断装置
    shutoffDevice(id) {
      const shutoff_types = [];
      shutoff_types[0] = '未绑定';
      shutoff_types[1] = '电磁阀';
      shutoff_types[2] = '机械手';
      return shutoff_types[id];
    },
    shutoffStatus(id) {
      const shutoff = [];
      shutoff[0] = '初始化';
      shutoff[1] = '开启';
      shutoff[2] = '关闭';
      return shutoff[id];
    },
    openDeviceBox(row, column, event) {
      this.getUserDeviceInfo(row.id);
    },
    // 定时刷新数据
    dataRefresh(uid = null) {
      // 计时器正在进行中，退出函数
      if (this.intervalId != null) {
        return;
      }
      // 计时器为空，操作
      this.intervalId = setInterval(() => {
        console.log('刷新' + uid + '--' + new Date());
        if (uid > 0) {
          users({ uid: uid })
            .then(res => {
              this.markers = res.data;
            });
          devices({ uid: uid })
            .then(res => {
              this.markersDevice = res.data;
            });
        } else {
          users()
            .then(res => {
              this.markers = res.data;
            });
          devices({})
            .then(res => {
              this.markersDevice = res.data;
            });
        }
      }, 3000);
    },
    // 停止定时器
    clearIntv() {
      clearInterval(this.intervalId); // 清除计时器
      this.intervalId = null; // 设置为null
    },
    // 播放报警声音
    playAudio(state) {
      if (this.audio_play === false && (state === 4 || state === 5 || state === 6 || state === 16)) {
        const playPromise = this.audio.play();
        const that = this;
        if (playPromise) {
          playPromise.then(() => {
            // 音频加载成功
            // 音频的播放需要耗时
            that.tiemr = setInterval(() => {
              that.second--;
              if (that.second <= 0) {
                this.audio.pause();
                this.audio_play = true;
                clearInterval(that.tiemr);
              }
            }, 1000);
          }).catch((e) => {
            // 音频加载失败
            console.error(e);
          });
        }
      }
    },
  },
};
</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: 100px;
}
.zero-user-devices{
  position: fixed;
  top: 100px;
  padding: 0px 10px 0px 10px;
  background-color: #ffffff;
}
.zero-dialog {
  float: right;
  right: 1px;
  bottom: 1px;
}
</style>
