<template>
  <div style="padding: 10px; background-color: #f8f8f8">
    <div style="margin-top: 10px;">
      <el-row :gutter="24">
        <el-col :span="6">
          <TopCard :footer="productFooter" :value="deviceStatistic.productCount"
                   img="https://demo.jetlinks.cn/images/DataCollect/dashboard/channel.png" title="产品数量"></TopCard>
        </el-col>
        <el-col :span="6">
          <TopCard :footer="deviceFooter" :value="deviceStatistic.deviceCount"
                   img="https://demo.jetlinks.cn/images/DataCollect/dashboard/channel.png" title="设备数量"></TopCard>
        </el-col>
        <el-col :span="6">
          <TopCard :footer="functionFooter" :value="functionCount.totalCount" title="设备交互次数">
            <Charts :options="deviceOnline"></Charts>
          </TopCard>
        </el-col>
        <el-col :span="6">
          <TopCard :footer="deviceLogFooter" :value="this.deviceLogCount.totalCount" title="设备消息量">
            <Charts :options="TodayDevOptions"></Charts>
          </TopCard>
        </el-col>
      </el-row>
    </div>
    <el-card class="box-card" style="height: 530px;margin-top: 20px;">
      <div class="home-title">
        <div style="display: flex;align-items: center;gap: 10px;">
          <div style="width: 7px;height: 7px;background-color: #315EFB;"></div>
          <div>设备消息</div>
        </div>
        <div>
          <el-radio-group v-model="queryMap.type" @input="getDeviceLogDeviceLogStatistic">
            <el-radio-button :label="1">最近一小时</el-radio-button>
            <el-radio-button :label="24">最近24小时</el-radio-button>
            <el-radio-button :label="7">近一周</el-radio-button>
          </el-radio-group>
          <el-date-picker
              v-model="queryTime"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              style="margin-left: 20px;"
              type="datetimerange"
              @change="pickerChange">
          </el-date-picker>
        </div>
      </div>
      <Echarts :options="options"/>
    </el-card>
    <div style="overflow: hidden; border: 1px solid #ccc;margin-top: 20px;">
      <div ref="map" style="height: 400px;"></div>
    </div>
  </div>
</template>

<script>
import Echarts from '../components/Echarts';
import TopCard from '../components/TopCard';
import Charts from '../components/Charts';
import {getDeviceStatistic} from '@/api/iot/device';
import {
  selectDashBoardDeviceStatistic,
  selectDashBoardFunctionStatistic,
  selectDeviceLogYesterdayCount,
  selectDeviceLogDeviceLogStatistic,
  selectDeviceLogDeviceLogAnHourStatistic
} from '@/api/iot/deviceDashBoard';
import {listNotice, getNotice} from '@/api/system/notice';
import CountTo from 'vue-count-to';
import {loadBMap} from '@/utils/map.js';
import {getServer} from '@/api/monitor/server';
import {listAllDeviceShort} from '@/api/iot/device';
import {formatDate2} from '../../../utils';
import {options} from 'runjs';

export default {
  name: 'deviceDashBoard',
  components: {
    CountTo,
    Echarts,
    TopCard,
    Charts
  },
  data() {
    return {
      productFooter: [],
      deviceFooter: [],
      functionFooter: [],
      deviceLogFooter: [],
      //设备交互每小时统计
      functionCountList: [],
      functionTimeList: [],
      functionCount: {},
      //设备消息统计
      deviceLogCount: {},
      deviceLogMinStatisticTime: [],
      deviceLogMinStatisticCount: [],
      deviceLogStatisticTime: [],
      deviceLogStatisticCount: [],
      //查询条件
      queryMap: {
        type: 7,
        startTime: undefined,
        endTime: undefined,
      },
      queryTime: [],
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      open: false,
      // 信息列表
      noticeList: [],
      // 信息详情
      notice: {},
      // 是否为管理员
      isAdmin: false,
      // 设备列表
      deviceList: [],
      // 设备统计信息
      deviceStatistic: {},
      // 设备总数
      deviceCount: 0,
      // 版本号
      version: '3.8.0',
      colorNetwork: ['#FF7D00', '#FFC300', '#37E2E2', '#165DFF', '#722ED1'],
      tableData: [],

    };
  },
  computed: {
    deviceOnline() {
      let deviceOptions = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          show: false,
          data: this.functionTimeList,
        },
        yAxis: {
          type: 'value',
          show: false,
        },
        grid: {
          top: '2%',
          bottom: 0,
        },
        series: [
          {
            name: '在线数',
            data: this.functionCountList,
            type: 'line',
            smooth: true, // 是否平滑曲线
            symbolSize: 0, // 拐点大小
            color: '#D7B0F8',
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#E2C9FA', // 100% 处的颜色
                  },
                  {
                    offset: 1,
                    color: '#FFFFFF', //   0% 处的颜色
                  },
                ],
                global: false, // 缺省为 false
              },
            },
          },
        ],
      };
      return deviceOptions;
    },
    TodayDevOptions() {
      let myTodayDevOptions = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          show: false,
          data: this.deviceLogMinStatisticTime,
        },
        yAxis: {
          type: 'value',
          show: false,
        },
        grid: {
          top: '2%',
          bottom: 0,
        },
        series: [
          {
            name: '消息量',
            data: this.deviceLogMinStatisticCount,
            type: 'line',
            smooth: true, // 是否平滑曲线
            symbolSize: 0, // 拐点大小
            color: '#F29B55',
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#FBBB87', // 100% 处的颜色
                  },
                  {
                    offset: 1,
                    color: '#FFFFFF', //   0% 处的颜色
                  },
                ],
                global: false, // 缺省为 false
              },
            },
          },
        ],
      };
      return myTodayDevOptions;
    },
    options() {
      let myoptions = {
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.deviceLogStatisticTime
        },
        yAxis: {
          type: "value"
        },
        tooltip: {
          trigger: "axis",
          formatter: "{b0}<br />{a0}: {c0}"
        },
        grid: {
          top: "2%",
          bottom: "5%",
          left: "4%",
          // left: e < 9e5 ? "60px" : o * 7.5 + Math.floor(o / 3) * 1.2 + 10 + "px",
          right: "4%"
        },
        series: [{
          name: "消息量",
          data: this.deviceLogStatisticCount,
          type: "line",
          smooth: !0,
          symbolSize: 0,
          color: "#ADC6FF",
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: "#ADC6FF"
              }, {
                offset: 1,
                color: "#FFFFFF"
              }],
              global: false
            }
          }
        }]
      }
      return myoptions;
    }
  },
  created() {
    // this.init();
    // this.getNoticeList();
    // this.getDeviceStatistic();
    this.getAllDevice();
    this.getDeviceCount();
    this.getTodayDevInteraction();
    this.getDeviceLogYesterdayCount();
    this.getDeviceLogDeviceLogMinStatistic();
    this.getDeviceLogDeviceLogStatistic();
  },
  methods: {
    //查询设备消息统计信息
    getDeviceLogDeviceLogStatistic() {
      selectDeviceLogDeviceLogStatistic(this.queryMap).then(response => {
        let data = response.data
        this.deviceLogStatisticTime = []
        this.deviceLogStatisticCount = []
        data.forEach(element => {
          this.deviceLogStatisticTime.push(formatDate2(element.time, 'Y-M-D h:m:s'))
          this.deviceLogStatisticCount.push(element.statisticscount)
        });
        if (this.queryMap.type == 1) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 1);
          this.queryTime = [start, end]
        } else if (this.queryMap.type == 24) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
          this.queryTime = [start, end]
        } else if (this.queryMap.type == 7) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          this.queryTime = [start, end]
        }
      })
    },
    //查询设备消息统计信息小窗口
    getDeviceLogDeviceLogMinStatistic() {
      let queryMap = {
        type: 1
      }
      selectDeviceLogDeviceLogAnHourStatistic(queryMap).then(response => {
        let data = response.data
        data.forEach(element => {
          this.deviceLogMinStatisticTime.push(formatDate2(element.time, 'Y-M-D h:m:s'))
          this.deviceLogMinStatisticCount.push(element.statisticscount)
        });
      })
    },
    //查询昨日设备消磁次数
    getDeviceLogYesterdayCount() {
      selectDeviceLogYesterdayCount().then(response => {
        this.deviceLogCount = {
          totalCount: response.totalCountMap.totalcount,
          yesterdayCount: response.yesterdayCountMap.yesterdaycount
        }
        this.deviceLogFooter = [
          {
            title: '昨日设备消息量',
            value: this.deviceLogCount.yesterdayCount
          }
        ]
      });
    },
    //统计今天每小时设备交互次数
    getTodayDevInteraction() {
      selectDashBoardFunctionStatistic().then(response => {
        let functionMap = response.treeMap;
        this.functionCountList = []
        this.functionTimeList = []
        for (const key in functionMap) {
          const element = functionMap[key];
          this.functionCountList.push(element.count)
          this.functionTimeList.push(element.time)
        }
        this.functionCount = {
          totalCount: response.countMap.totalCount,
          yesterdayCount: response.countMap.yesterdayCount
        }
        this.functionFooter = [
          {
            title: '昨日在线',
            value: this.functionCount.yesterdayCount
          }
        ]
      })
    },
    //设备统计
    getDeviceCount() {
      selectDashBoardDeviceStatistic().then(response => {
        this.deviceStatistic = response.data;
        this.deviceFooter = [
          {
            title: '在线',
            value: this.deviceStatistic.deviceOnlineCount,
            status: 'success',
          },
          {
            title: '离线',
            value: this.deviceStatistic.deviceOfflineCount,
            status: 'error',
          },
          {
            title: '未激活',
            value: this.deviceStatistic.deviceNonactivatedCount,
            status: 'info',
          },
          {
            title: '禁用',
            value: this.deviceStatistic.deviceForbiddenCount,
            status: 'danger',
          }
        ]
        this.productFooter = [
          {
            title: '已发布',
            value: this.deviceStatistic.productHavePublishedCount,
            status: 'success',
          },
          {
            title: '未发布',
            value: this.deviceStatistic.productNotIssueCount,
            status: 'error',
          }
        ]
      })
    },
    //日期点击事件
    pickerChange() {
      this.queryMap = {
        type: undefined,
        startTime: formatDate2(this.queryTime[0], 'Y-M-D h:m:s'),
        endTime: formatDate2(this.queryTime[1], 'Y-M-D h:m:s')
      }
      this.getDeviceLogDeviceLogStatistic()
    },
    init() {
      if (this.$store.state.user.roles.indexOf('tenant') === -1 && this.$store.state.user.roles.indexOf('general') === -1) {
        this.isAdmin = true;
        this.getServer();
      }
    },
    //刷新iframe
    flushIframe() {
      var iframe = window.parent.document.getElementById('iframe');
      iframe.contentWindow.location.reload(true);
    },
    /** 查询设备统计信息 */
    getDeviceStatistic() {
      getDeviceStatistic().then((response) => {
        this.deviceStatistic = response.data;
      });
    },
    /** 查询公告列表 */
    getNoticeList() {
      let queryParams = {
        pageNum: 1,
        pageSize: 6,
      };
      listNotice(queryParams).then((response) => {
        this.noticeList = response.rows.splice(0, 6);
      });
    },
    // 打开信息详情
    openDetail(id) {
      this.open = true;
      this.loading = true;
      getNotice(id).then((response) => {
        this.notice = response.data;
        this.open = true;
        this.loading = false;
      });
    },
    // 取消按钮
    closeDetail() {
      this.title = '';
      this.open = false;
    },
    /**查询所有设备 */
    getAllDevice() {
      listAllDeviceShort(this.queryParams).then((response) => {
        this.deviceList = response.rows;
        this.deviceCount = response.total;
        this.loadMap();
      });
    },
    /**加载地图*/
    loadMap() {
      this.$nextTick(() => {
        loadBMap().then(() => {
          this.getmap();
        });
      });
    },
    /** 查询服务器信息 */
    getServer() {
      getServer().then((response) => {
        this.server = response.data;
        this.tableData = [
          {
            server: '服务器名',
            serverContent: this.server.sys.computerName,
            java: 'Java名称',
            javaContent: this.server.jvm.name,
          },
          {
            server: '服务器IP',
            serverContent: this.server.sys.computerIp,
            java: '启动时间',
            javaContent: this.server.jvm.startTime,
          },
          {
            server: '操作系统',
            serverContent: this.server.sys.osName,
            java: 'Java版本',
            javaContent: this.server.jvm.version,
          },
          {
            server: '系统架构',
            serverContent: this.server.sys.osArch,
            java: '运行时长',
            javaContent: this.server.jvm.runTime,
          },
          {
            server: 'CPU核心',
            serverContent: this.server.cpu.cpuNum,
            java: '占用内存',
            javaContent: this.server.jvm.used,
          },
          {
            server: '内存大小',
            serverContent: this.server.mem.total,
            java: 'JVM总内存',
            javaContent: this.server.jvm.total,
          },
        ];
        this.$nextTick(() => {
          this.drawPieCpu();
          this.drawPieMemery();
          this.drawPieDisk();
        });
      });
    },

    /** 地图 */
    getmap() {
      var myChart = this.$echarts.init(this.$refs.map);
      var option;

      // 单击事件
      myChart.on('click', (params) => {
        if (params.data.deviceId) {
          this.$router.push({
            path: '/iot/device-edit',
            query: {
              t: Date.now(),
              deviceId: params.data.deviceId,
            },
          });
        }
      });

      // 格式化数据
      let convertData = function (data, status) {
        var res = [];
        for (var i = 0; i < data.length; i++) {
          var geoCoord = [data[i].longitude, data[i].latitude];
          if (geoCoord && data[i].status == status) {
            res.push({
              name: data[i].deviceName,
              value: geoCoord,
              serialNumber: data[i].serialNumber,
              status: data[i].status,
              isShadow: data[i].isShadow,
              firmwareVersion: data[i].firmwareVersion,
              networkAddress: data[i].networkAddress,
              productName: data[i].productName,
              activeTime: data[i].activeTime == null ? '' : data[i].activeTime,
              deviceId: data[i].deviceId,
              serialNumber: data[i].serialNumber,
              locationWay: data[i].locationWay,
            });
          }
        }
        return res;
      };
      option = {
        title: {
          text: '设备分布（在线数 ' + this.deviceList.filter((x) => x.status == 3).length + '）',
          subtext: '',
          sublink: 'https://iot.yanfankeji.com',
          target: '_blank',
          textStyle: {
            color: '#333',
            textBorderColor: '#fff',
            textBorderWidth: 10,
          },
          top: 10,
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            var htmlStr = '<div style="padding:5px;line-height:28px;">';
            htmlStr += "设备名称： <span style='color:#409EFF'>" + params.data.name + '</span><br />';
            htmlStr += '设备编号： ' + params.data.serialNumber + '<br />';
            htmlStr += '设备状态： ';
            if (params.data.status == 1) {
              htmlStr += "<span style='color:#E6A23C'>未激活</span>" + '<br />';
            } else if (params.data.status == 2) {
              htmlStr += "<span style='color:#F56C6C'>禁用</span>" + '<br />';
            } else if (params.data.status == 3) {
              htmlStr += "<span style='color:#67C23A'>在线</span>" + '<br />';
            } else if (params.data.status == 4) {
              htmlStr += "<span style='color:#909399'>离线</span>" + '<br />';
            }
            if (params.data.isShadow == 1) {
              htmlStr += '设备影子： ' + "<span style='color:#67C23A'>启用</span>" + '<br />';
            } else {
              htmlStr += '设备影子： ' + "<span style='color:#909399'>未启用</span>" + '<br />';
            }
            htmlStr += '产品名称： ' + params.data.productName + '<br />';
            htmlStr += '固件版本： Version ' + params.data.firmwareVersion + '<br />';
            htmlStr += '激活时间： ' + params.data.activeTime + '<br />';
            htmlStr += '定位方式： ';
            if (params.data.locationWay == 1) {
              htmlStr += '自动定位' + '<br />';
            } else if (params.data.locationWay == 2) {
              htmlStr += '设备定位' + '<br />';
            } else if (params.data.locationWay == 3) {
              htmlStr += '自定义位置' + '<br />';
            } else {
              htmlStr += '未知' + '<br />';
            }
            htmlStr += '所在地址： ' + params.data.networkAddress + '<br />';
            htmlStr += '</div>';
            return htmlStr;
          },
        },
        bmap: {
          center: [133, 38],
          zoom: 5,
          roam: true,
          mapStyle: {
            styleJson: [
              {
                featureType: 'water',
                elementType: 'all',
                stylers: {
                  color: '#a0cfff',
                },
              },
              {
                featureType: 'land',
                elementType: 'all',
                stylers: {
                  color: '#fafafa', // #fffff8 淡黄色
                },
              },
              {
                featureType: 'railway',
                elementType: 'all',
                stylers: {
                  visibility: 'off',
                },
              },
              {
                featureType: 'highway',
                elementType: 'all',
                stylers: {
                  color: '#fdfdfd',
                },
              },
              {
                featureType: 'highway',
                elementType: 'labels',
                stylers: {
                  visibility: 'off',
                },
              },
              {
                featureType: 'arterial',
                elementType: 'geometry',
                stylers: {
                  color: '#fefefe',
                },
              },
              {
                featureType: 'arterial',
                elementType: 'geometry.fill',
                stylers: {
                  color: '#fefefe',
                },
              },
              {
                featureType: 'poi',
                elementType: 'all',
                stylers: {
                  visibility: 'off',
                },
              },
              {
                featureType: 'green',
                elementType: 'all',
                stylers: {
                  visibility: 'off',
                },
              },
              {
                featureType: 'subway',
                elementType: 'all',
                stylers: {
                  visibility: 'off',
                },
              },
              {
                featureType: 'manmade',
                elementType: 'all',
                stylers: {
                  color: '#d1d1d1',
                },
              },
              {
                featureType: 'local',
                elementType: 'all',
                stylers: {
                  color: '#d1d1d1',
                },
              },
              {
                featureType: 'arterial',
                elementType: 'labels',
                stylers: {
                  visibility: 'off',
                },
              },
              {
                featureType: 'boundary',
                elementType: 'all',
                stylers: {
                  color: '#999999',
                },
              },
              {
                featureType: 'building',
                elementType: 'all',
                stylers: {
                  color: '#d1d1d1',
                },
              },
              {
                featureType: 'label',
                elementType: 'labels.text.fill',
                stylers: {
                  color: '#999999',
                },
              },
            ],
          },
        },
        series: [
          {
            type: 'scatter',
            coordinateSystem: 'bmap',
            data: convertData(this.deviceList, 1),
            symbolSize: 15,
            itemStyle: {
              color: '#E6A23C',
            },
          },
          {
            type: 'scatter',
            coordinateSystem: 'bmap',
            data: convertData(this.deviceList, 2),
            symbolSize: 15,
            itemStyle: {
              color: '#F56C6C',
            },
          },
          {
            type: 'scatter',
            coordinateSystem: 'bmap',
            data: convertData(this.deviceList, 4),
            symbolSize: 15,
            itemStyle: {
              color: '#909399',
            },
          },
          {
            type: 'effectScatter',
            coordinateSystem: 'bmap',
            data: convertData(this.deviceList, 3),
            symbolSize: 15,
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke',
              scale: 5,
            },
            label: {
              formatter: '{b}',
              position: 'right',
              show: false,
            },
            itemStyle: {
              color: '#67C23A',
              shadowBlur: 100,
              shadowColor: '#333',
            },
            zlevel: 1,
          },
        ],
      };

      option && myChart.setOption(option, true);
    },

    drawPieCpu() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.pieCpu);
      var option;
      option = {
        title: {
          text: 'CPU使用率',
          left: 'left',
          textStyle: {
            fontSize: 16,
          },
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'right',
        },
        color: ['#E6A23C', '#F56C6C', '#DDD'],
        series: [
          {
            name: 'CPU使用率 %',
            type: 'pie',
            radius: '55%',
            label: {
              show: false,
            },
            labelLine: {
              normal: {
                position: 'inner',
                show: false,
              },
            },
            data: [
              {
                value: this.server.cpu.used,
                name: '用户',
              },
              {
                value: this.server.cpu.sys,
                name: '系统',
              },
              {
                value: this.server.cpu.free,
                name: '空闲',
              },
            ],
          },
        ],
      };
      option && myChart.setOption(option);
    },
    drawPieMemery() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.pieMemery);
      var option;
      option = {
        title: {
          text: '内存使用率',
          left: 'left',
          textStyle: {
            fontSize: 16,
          },
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'right',
        },
        color: ['#F56C6C', '#DDD'],
        series: [
          {
            name: '内存使用率 G',
            type: 'pie',
            radius: '55%',
            label: {
              show: false,
            },
            labelLine: {
              normal: {
                position: 'inner',
                show: false,
              },
            },
            data: [
              {
                value: this.server.mem.used,
                name: '已用',
              },
              {
                value: this.server.mem.free,
                name: '剩余',
              },
            ],
          },
        ],
      };
      option && myChart.setOption(option);
    },
    drawPieDisk() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.pieDisk);
      var option;
      let one = this.server.sysFiles[0].used.replace('GB', '');
      let two = this.server.sysFiles[0].free.replace('GB', '');
      option = {
        title: {
          text: '系统盘使用率',
          left: 'left',
          textStyle: {
            fontSize: 16,
          },
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'right',
        },
        color: ['#F56C6C', '#DDD'],
        series: [
          {
            name: '磁盘状态 G',
            type: 'pie',
            radius: '55%',
            label: {
              show: false,
            },
            labelLine: {
              normal: {
                position: 'inner',
                show: false,
              },
            },
            data: [
              {
                value: one,
                name: '已用',
              },
              {
                value: two,
                name: '可用',
              },
            ],
          },
        ],
      };
      option && myChart.setOption(option);
    },
  },
};
</script>

<style>
.home-title {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 12px;
  font-weight: 700;
  font-size: 18px;
}
</style>
