<template>
  <statistics-template
    title="上下线统计"
    :list="[{value: 20, color: 'green', label: '上线次数'}, {value: 20, color: 'red', label: '下线次数'}]"
  />
  <a-card
    style="margin-top: 20px;"
    title="设备分析"
    :tab-list="tabListNoTitle"
    :active-tab-key="activeTabKey"
    @tabChange="key => onTabChange(key)"
  >
    <a-row :gutter="[8, 8]" style="margin: 0 20px;" >

        <a-col :span="24" >
          <a-space>
            <a-spin
              :spinning="state.spinning"
            >
              <a-select
                v-model:value="state.searchDeviceLabel"
                show-search
                placeholder="输入设备名检索设备"
                :default-active-first-option="false"
                style="width: 170px"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                :options="state.dataSource"
                @search="getDeviceLabel"
                @change="selectDevice"
              >
                <template v-if="state.fetching" #notFoundContent>
                  <a-spin size="small" />
                </template>
              </a-select>
            </a-spin>
            <a-select
                v-if="activeTabKey === 'attr'"
                v-model:value="state.attributeKey"
                placeholder="请选择属性"
                style="width: 170px"
                :show-arrow="false"
                @change="selectAttr"
              >
                <a-select-option
                  v-for="item in deviceState.attrList"
                  :key="item.key"
                  :value="item.key"
                >{{item.keyLabel}}</a-select-option>
              </a-select>
            <a-range-picker :show-time="{ format: 'HH:mm' }" v-model:value="times" @change="changeRangePicker"  />
          </a-space>
        </a-col>
        <a-col :span="24">
          <a-spin :spinning="state.loading" >
          <a-empty style="margin: 0 auto;" v-if="emptyCondition" :description="emptyDesc" ></a-empty>
          <span v-else>
            <a-col :span="24" v-if="activeTabKey === 'session'">
              <a-row>
                <a-col :xs="24" :md="24" :xl="12" >
                  <div id="device-session" style="width: 600px;height: 400px;" ></div>
                </a-col>
                <a-col :xs="24" :md="24" :xl="12">
                  <div id="device-session-scatter" style="width: 600px;height: 400px;" ></div>
                </a-col>
              </a-row>
            </a-col>
            <a-col :span="24" v-else>
              <div
                id="device-attr"
                style="width: 1000px; height: 400px;"
              >
              </div>
            </a-col>
          </span>
        </a-spin>
        </a-col>

      </a-row>
  </a-card>
</template>
<script lang='ts' setup >
import { DeviceContriller } from '@/controller'
import { reactive, watch, computed, ref, onMounted, watchEffect, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useRoute } from 'vue-router'
import { sessionEchartsJson, attrEchartsJson, scatterOption, barOption, calculateAverage } from './json/echartsJson'
import dayjs from 'dayjs'
import StatisticsTemplate from '@/components/StatisticsTemplate'

const tabListNoTitle = [{
  key: 'session',
  tab: '上下线分析'
},
{
  key: 'attr',
  tab: '属性分析'
}]

const route = useRoute()

const activeTabKey = ref<'session' | 'attr'>('session')

const emptyCondition = computed(() => activeTabKey.value === 'session' ? state.dataSource.length === 0 : state.attrSource.length === 0)

const emptyDesc = computed(() => !state.deviceId ? '请选择设备' : '该设备下暂无数据')

const deviceState = reactive<{
  dataSource: IOT.API.DEVICE.Device[]
  attrList: IOT.API.DEVICE.Attr[]
}>({
  dataSource: [],
  attrList: []
})

const state = reactive<{
  attrSource: IOT.API.DEVICE.Attr[]
  [key: string]: any
}>({
  deviceId: '',
  searchDeviceLabel: null,
  start: 0,
  end: '',
  dataSource: [],
  attrSource: [],
  loading: false,
  analysisType: '',
  spinning: false,
  onlineNum: 0,
  offlineNum: 0,
  attributeKey: null
})

const times = ref([dayjs().subtract(30, 'minute'), dayjs()])

state.deviceId = route.query.id as string

const onTabChange = (key: 'session' | 'attr') => activeTabKey.value = key

// 切换上下线分析
watch(
  () => activeTabKey.value,
  () => {
    state.deviceId = null
    state.searchDeviceLabel = null
    state.attributeKey = null
  }
)

// 获取设备属性分析数据
watch(
  () => state.attrSource,
  () => {
    nextTick(() => {
      if (state.attrSource.length === 0) {
        state.loading = false
        return
      }
      const chartDom = document.getElementById('device-attr')

      const myChart = echarts.init(chartDom!)

      attrEchartsJson.xAxis.data = (state.attrSource.map(item => dayjs(item.ts).format('HH:MM:ss')) || []) as never[]

      attrEchartsJson.series[0].data = state.attrSource.map(item => item.value)

      attrEchartsJson.title.text = state.attrSource[0].keyLabel

      myChart.setOption(attrEchartsJson)

      state.loading = false
    })
  }
)

// 获取上下线分析图表数据
// state.dataSource
watch(
  () => state.dataSource,
  () => {
    setTimeout(() => {
      if (state.dataSource.length === 0) {
        state.loading = false
        return
      }
      if (activeTabKey.value === 'session') {
        const chartDom = document.getElementById('device-session')
        const chartDomScatter = document.getElementById('device-session-scatter')
        console.log('chartDom:', chartDom)

        const myChart = echarts.init(chartDom!)
        const chartDomScatterChart = echarts.init(chartDomScatter!)
        sessionEchartsJson.xAxis.data = state.dataSource.map(item => item.createAt) as never[]
        sessionEchartsJson.series[0].data = state.dataSource.map(item => item.sessionType === 'CONNECT' ? '上线' : '下线')
        sessionEchartsJson.series[1].data = state.dataSource.map(item => item.sessionType !== 'CONNECT' ? '上线' : '下线')

        const connectCount = state.dataSource.filter(item => item.sessionType === 'CONNECT').length
        const disconnectCount = state.dataSource.length - connectCount

        barOption.series[0].data = [
          {
            value: calculateAverage(connectCount),
            groupId: 'male'
          },
          {
            value: calculateAverage(disconnectCount),
            groupId: 'female'
          }
        ]

        sessionEchartsJson.series[0].name = `上线数量 ${state.onlineNum}`
        sessionEchartsJson.series[1].name = `下线数量 ${state.offlineNum}`

        chartDomScatterChart.setOption(barOption)
        myChart.setOption(sessionEchartsJson)

        state.loading = false
      }
    }, 3000)
  }
)

const selectAttr = (value: string) => {
  state.attributeKey = value
  getDeviceAttr()
}

const changeRangePicker = (time) => {
  activeTabKey.value === 'session' ? getDeviceSession() : getDeviceAttr()
}

const selectDevice = async (value: string) => {
  const device = await DeviceContriller.byId(value)
  state.deviceId = device.id
  console.log('device:', state.deviceId)
  if (activeTabKey.value === 'attr') {
    getDeviceAttribute()
  } else {
    getDeviceSession()
  }
}

const getDeviceLabel = async (val: string) => {
  if (!val) return
  state.spinning = true
  const { data } = await DeviceContriller.labelsByLabel(val)
  state.spinning = false
  state.dataSource = data.map(item => ({ value: item.id, label: item.deviceLabel }))
  console.log(data)
}

const getDeviceSession = async () => {
  if (!state.deviceId) return
  state.loading = true
  const { data } = await DeviceContriller.getSession({ deviceId: state.deviceId, start: dayjs(times.value[0]).unix() * 1000, end: dayjs(times.value[1]).unix() * 1000 })
  state.dataSource = data.sessionEntities
  state.offlineNum = data.offlineNum
  state.onlineNum = data.onlineNum
}

const getDeviceAttr = async () => {
  if (!state.deviceId) return
  state.loading = true
  // .format('YYYY/MM/DD HH:mm:ss')
  const { data } = await DeviceContriller.getAttr({
    deviceId: state.deviceId,
    start: 1,
    end: new Date().getTime(),
    attributeKey: state.attributeKey
  })
  state.attrSource = data
}

const getDeviceAttribute = async () => {
  const { data } = await DeviceContriller.getDeviceAttribute(state.deviceId)
  deviceState.attrList = data
}

onMounted(() => {
  if (state.deviceId) {
    getDeviceSession()
  }
})
</script>
<style lang='less' scoped >
</style>
