<template>
  <div class="dashboard-container">
    <div class="card-box">
      <div class="card-item red">
        <div class="card-title">{{ riskName['306001'] || '' }}区域人数</div>
        <div class="card-num">{{ riskCount['306001'] || 0 }}</div>
        <div class="line">
          <div class="left"></div>
          <div class="right"></div>
        </div>
        <img :src="require('@/assets/images/card_bg.png')" alt="" />
      </div>
      <div class="card-item orange">
        <div class="card-title">{{ riskName['306002'] || '' }}区域人数</div>
        <div class="card-num">{{ riskCount['306002'] || 0 }}</div>
        <div class="line">
          <div class="left"></div>
          <div class="right"></div>
        </div>
        <img :src="require('@/assets/images/card_bg.png')" alt="" />
      </div>
      <div class="card-item yellow">
        <div class="card-title">{{ riskName['306003'] || '' }}区域人数</div>
        <div class="card-num">{{ riskCount['306003'] || 0 }}</div>
        <div class="line">
          <div class="left"></div>
          <div class="right"></div>
        </div>
        <img :src="require('@/assets/images/card_bg.png')" alt="" />
      </div>
      <div class="card-item blue">
        <div class="card-title">{{ riskName['306004'] || '' }}区域人数</div>
        <div class="card-num">{{ riskCount['306004'] || 0 }}</div>
        <div class="line">
          <div class="left"></div>
          <div class="right"></div>
        </div>
        <img :src="require('@/assets/images/card_bg.png')" alt="" />
      </div>
      <div class="card-item green">
        <div class="card-title">当前在岗总人数</div>
        <div class="card-num">{{ allCount }}</div>
        <div class="line">
          <div class="left"></div>
          <div class="right"></div>
        </div>
        <img :src="require('@/assets/images/card_bg.png')" alt="" />
      </div>
    </div>
    <div class="content-row">
      <div class="content-box content1">
        <div class="content-header">
          <div class="border-line"></div>
          <span>部门在岗人数统计</span>
        </div>
        <div class="content-body">
          <el-table
            ref="table"
            :data="department"
            row-key="id"
            max-height="300"
            :header-cell-style="{
              background: '#2892F0',
              color: '#fff',
              padding: '5px 0',
              'text-align': 'center',
            }"
          >
            <el-table-column label="部门" prop="label" align="left" />
            <el-table-column label="总数" prop="personCount_All" align="center" width="100" />
            <el-table-column label="在岗" prop="personCount" align="center" width="100" />
            <el-table-column
              label="未在岗"
              prop="personCount_Remaining"
              align="center"
              width="100"
            />
          </el-table>
        </div>
      </div>
      <div class="content-box content2">
        <div class="content-header">
          <div class="border-line"></div>
          <span>区域人数统计</span>
        </div>
        <div class="content-body">
          <v-chart autoresize :option="alarmweekInfo" />
        </div>
      </div>
    </div>
    <div class="content-row">
      <div class="content-box content3">
        <div class="content-header">
          <div class="border-line"></div>
          <span>7天报警趋势</span>
        </div>
        <div class="content-body">
          <v-chart autoresize :option="alarmweekInfo" />
        </div>
      </div>
      <div class="content-box content4">
        <div class="content-header">
          <div class="border-line"></div>
          <span>本日报警分布图</span>
        </div>
        <div class="content-body">
          <v-chart autoresize :option="alarmdayInfo" />
        </div>
      </div>
    </div>
    <!-- <div class="div-content">
      <div class="div-content2">
        <div class="div-content3-title">部门在岗人数统计</div>
        <div class="div-content3">
          <div class="div-content4-title">
            <span>总数</span>
            <span>在岗</span>
            <span>未在岗</span>
          </div>
          <el-tree :data="department" default-expand-all :render-content="dRenderContent"></el-tree>
        </div>
      </div>
      <div class="div-content2">
        <div class="div-content3-title">区域人数统计</div>
        <div class="div-content3">
          <el-tree :data="area" default-expand-all :render-content="aRenderContent"></el-tree>
        </div>
      </div>
      <div class="div-content2">
        <div style="height: 50%; padding-top: 10px">
          <v-chart autoresize :option="alarmdayInfo" />
        </div>
        <div style="height: 50%; padding-top: 10px">
          <v-chart autoresize :option="alarmweekInfo" />
        </div>
      </div>
    </div> -->
    <!-- <v-chart autoresize :option="bulidOption(item)" /> -->
    <!-- <el-image class="dashboard-img" :src="'/static/images/dashboard_bg.jpg'" /> -->
  </div>
</template>

<script>
import { initData } from '@/api/data'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart, GaugeChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  PolarComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components'
import { use } from 'echarts/core'
import VChart, { THEME_KEY } from 'vue-echarts'
import lodash from 'lodash'
import dayjs from 'dayjs'
import * as mqtt from 'mqtt'
import { getMQTTCilentId } from '@/utils/mqtt'

use([
  CanvasRenderer,
  LineChart,
  GaugeChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  PolarComponent,
  GridComponent,
  LegendComponent,
])

export default {
  name: 'Dashboard',
  components: { VChart },
  data() {
    return {
      monitor: null,
      a: 100,
      departInfo: null,
      buildId: null,
      areaPersonCount: {
        title: {
          text: '区域人数统计',
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: [],
            type: 'line',
          },
        ],
      },
      alarmdayInfo: {
        title: {
          text: '本日报警分布图',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          top: '10%',
          left: 'center',
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      },
      alarmweekInfo: {
        title: {
          text: '7天报警趋势',
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: [],
            type: 'line',
          },
        ],
      },
      riskCount: {},
      riskName: {},
      department: [],
      area: [],
      departmentCount: {},
      areaCount: {},
      allCount: '0',
      mqttClient: null,
    }
  },
  computed: {
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    VUE_APP_BASE_WS() {
      return 'ws://' + window.location.host + process.env.VUE_APP_BASE_API
    },
  },
  created() {
    this.init()
    this.monitor = window.setInterval(() => {
      setTimeout(() => {
        this.getChartDate()
      }, 2)
    }, 5000)
  },
  destroyed() {
    this.mqttClient.end()
    clearInterval(this.monitor)
  },
  mounted() {},
  methods: {
    init() {
      initData('system/dataDictDetail/getTypeListJson', { dictType: '306' }).then((res) => {
        let dic = res.data.content
        if (dic && dic.length > 0) {
          dic.forEach((a) => (this.riskName[a.dictKey] = a.dictValue))
        }
      })

      initData('system/department/getDeptsTree', { id: 0 }).then((res) => {
        const content = res.data.content
        this.buildTreeData(content)
        this.department = content
        // console.log(this.department)
      })

      initData('positioning/countArea/getTreeRC', { buildId: this.buildId }).then((res) => {
        this.area = res.data.content
      })

      let today = dayjs().startOf('d')
      let t = today.add(1, 'day').add(-1, 'millisecond')
      let w = today.add(-6, 'day')
      initData('Alarm/Data/GetStatisticData', {
        startTime: today.format(),
        endTime: t.format(),
      }).then((res) => {
        this.alarmdayInfo.series[0].data = res.data.pieData
      })

      initData('Alarm/Data/GetStatisticData', { startTime: w.format(), endTime: t.format() }).then(
        (res) => {
          this.alarmweekInfo.xAxis.data = res.data.lineData.name
          this.alarmweekInfo.series[0].data = res.data.lineData.data
        }
      )

      this.startMQTT()
    },
    getChartDate() {
      let today = dayjs().startOf('d')
      let t = today.add(1, 'day').add(-1, 'millisecond')
      let w = today.add(-6, 'day')

      initData('Alarm/Data/GetStatisticData', {
        startTime: today.format(),
        endTime: t.format(),
      }).then((res) => {
        this.alarmdayInfo.series[0].data = res.data.pieData
      })

      initData('Alarm/Data/GetStatisticData', { startTime: w.format(), endTime: t.format() }).then(
        (res) => {
          this.alarmweekInfo.xAxis.data = res.data.lineData.name
          this.alarmweekInfo.series[0].data = res.data.lineData.data
        }
      )
    },
    //开始MQTT接收
    startMQTT() {
      // 连接选项
      const options = {
        clean: true, // true: 清除会话, false: 保留会话
        keepalive: 60,
        connectTimeout: 4000, // 超时时间
        // 认证信息
        clientId: getMQTTCilentId('dashboard'),
        username: 'client',
        password: '19c9547ad2029be96774fce5f1b9f099',
      }
      const connectUrl = this.VUE_APP_BASE_WS + '/MQTTOverWebSocket'
      //console.log(connectUrl)
      this.mqttClient = mqtt.connect(connectUrl, options)

      let _this = this
      this.mqttClient.on('connect', function () {
        //订阅主题
        console.log('统计MQTT正在连接')
        _this.mqttClient.subscribe('CountArea/+/' + (this.buildId ? this.buildId : 'All'))
        console.log('CountArea/+/' + (this.buildId ? this.buildId : 'All'))
      })
      this.mqttClient.on('message', (topic, message) => {
        if (topic == 'Online') {
          console.log('统计MQTT收到消息：', topic, message.toString())
        } else if (topic.startsWith('CountArea/CountDic/')) {
          this.areaCount = JSON.parse(message.toString())
        } else if (topic.startsWith('CountArea/DepartmentCountDic/')) {
          this.departmentCount = JSON.parse(message.toString())
        } else if (topic.startsWith('CountArea/AllCount/')) {
          this.allCount = message.toString()
        } else if (topic.startsWith('CountArea/RiskCount/')) {
          this.riskCount = JSON.parse(message.toString())
        }
      })
    },
    nodeColor(riskLevel) {
      switch (riskLevel) {
        case '306001':
          return '#ff4949'
        case '306002':
          return '#e09213'
        case '306003':
          return '#d8c732'
        case '306004':
          return '#606aff'
        default:
          return '#000'
      }
    },
    dRenderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node" style="color: #000">
          <span>{node.label}</span>
          <span class="custom-tree-node-count">
            <span>
              {this.departmentCount[data.id] ? this.departmentCount[data.id].Count_All : 0}
            </span>
            <span>{this.departmentCount[data.id] ? this.departmentCount[data.id].Count : 0}</span>
            <span>
              {this.departmentCount[data.id] ? this.departmentCount[data.id].Count_Remaining : 0}
            </span>
          </span>
        </span>
      )
    },
    aRenderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span style={'color: ' + this.nodeColor(data.riskLevel)}>{node.label}</span>
          <span style={'width: 100px; color: ' + this.nodeColor(data.riskLevel)}>
            人数：{this.areaCount[data.treeId] || 0}
          </span>
        </span>
      )
    },
    buildTreeData(arr) {
      arr.forEach((data) => {
        if (data.children && data.children.length) {
          delete data['hasChildren']
          // this.$set(data, 'hasChildren', true)
          this.buildTreeData(data.children)
        }
        // else {
        //   this.$set(data, 'hasChildren', false)
        // }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
// 绿色变量
$greenBg: #00827c;
// 蓝色变量
$blueBg: #296fd4;
.dashboard-container {
  min-height: calc(100vh - 84px);
  max-height: 100%;
  width: 100%;
  margin: 0;
  padding: 20px;
  background-color: #eee;
  pointer-events: auto;
}
.card-box {
  width: 100%;
  height: 118px;
  display: flex;
  justify-content: space-between;
  .card-item {
    width: 20%;
    height: 100%;
    margin-right: 20px;
    border-radius: 10px;
    position: relative;
    padding: 24px 30px;
    .card-title {
      font-size: 16px;
      color: #ffffff;
      letter-spacing: 0.73px;
      font-weight: 700;
    }
    .card-num {
      margin: 8px 0;
      font-size: 30px;
      color: #ffffff;
      letter-spacing: 1.36px;
      font-weight: 500;
    }
    .line {
      width: 100%;
      height: 4px;
      display: flex;
      .left {
        width: 50%;
        height: 100%;
        background-image: linear-gradient(270deg, #ffffff 0%, rgba(255, 255, 255, 0) 100%);
        border-radius: 3px;
      }
      .right {
        width: 50%;
        height: 100%;
        opacity: 0.3;
        background: #ffffff;
        border-radius: 3px;
      }
    }
    img {
      width: 143px;
      height: 102px;
      position: absolute;
      right: 0;
      top: 0;
    }
    &:last-child {
      margin-right: 0;
    }
    &.red {
      background-image: linear-gradient(90deg, #ffa193 0%, #f73c71 100%);
    }
    &.orange {
      background-image: linear-gradient(90deg, #ffc48d 0%, #ff852c 100%);
    }
    &.yellow {
      background-image: linear-gradient(90deg, #ffd161 0%, #ffc600 100%);
    }
    &.blue {
      background-image: linear-gradient(90deg, #93c4ff 0%, #3c79f7 100%);
    }
    &.green {
      background-image: linear-gradient(90deg, #66d6e5 0%, #00bfbd 100%);
    }
  }
}
.content-row {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .content-box {
    margin-right: 20px;
    margin-top: 20px;
    padding: 0 20px;
    background: #fff;
    border-radius: 10px;
    .content-header {
      width: 100%;
      height: 60px;
      line-height: 60px;
      border-bottom: 1px solid #eee;
      position: relative;
      .border-line {
        width: 3px;
        height: 17px;
        background: #18a9ad;
        border-radius: 2px;
        position: absolute;
        left: -20px;
        top: 21px;
      }
      span {
        font-size: 16px;
        color: #404d54;
        letter-spacing: 0.8px;
        font-weight: 700;
      }
    }
    .content-body {
      width: 100%;
      height: 310px;
      padding-top: 10px;
    }
    &:last-child {
      margin-right: 0;
    }
    &.content1 {
      width: 40%;
      height: 370px;
    }
    &.content2 {
      width: 60%;
      height: 370px;
    }
    &.content3 {
      width: 60%;
      height: 370px;
    }
    &.content4 {
      width: 40%;
      height: 370px;
    }
  }
}

.cardheader {
  font-size: 20px;
  text-align: right;
}
.cardcount {
  margin-top: 20px;
  font-size: 40px;
  text-align: right;
}
.div-card {
  display: inline-block;
  height: 100%;
  width: 20%;
  padding-right: 10px;
}
.box-card {
  border: 0;
  border-radius: 10px;
}
::v-deep .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 20px;
  padding-right: 8px;
}
::v-deep .custom-tree-node-count {
  width: 195px;
  justify-content: flex-end;
}
::v-deep .custom-tree-node-count span {
  display: inline-block;
  width: 65px;
  text-align: center;
}
.div-content {
  height: 80%;
  flex: fit-content;
  flex-flow: row;
  display: flex;
}
.div-content2 {
  flex: 1 1 0;
  padding: 10px;
}
.div-content3-title {
  height: 50px;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  padding-top: 10px;
}
::v-deep .div-content3 {
  height: calc(100% - 60px);
  overflow-y: auto;
}
.div-content4-title {
  height: 30px;
  text-align: right;
  padding-top: 0px;
  font-size: 20px;
  padding-right: 8px;
}
.div-content4-title span {
  display: inline-block;
  text-align: center;
  width: 65px;
}
</style>
