<template>

  <a-card
    title="设备分析"
    :tab-list="tabListNoTitle"
    :active-tab-key="activeTabKey"
    @tabChange="key => onTabChange(key)"
  >
    <a-row :gutter="[8, 8]" style="margin-top: 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"
                @change="selectDevice"
                @search="getDeviceLabel"
              >
                <template v-if="state.fetching" #notFoundContent>
                  <a-spin size="small" />
                </template>
              </a-select>
            </a-spin>
            <a-range-picker  :value="getDateBeforeByHalf" @change="changeRangePicker" format="YYYY/MM/DD"  />
          </a-space>
        </a-col>
        <a-col :span="24">
          <a-spin :spinning="state.loading" >
          <a-empty style="margin: 0 auto;" v-if="!state.deviceId" description="请选择设备" ></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-` + key"
                style="width: 1000px; height: 400px;"
                v-for="key in attrKeys"
                :key="key"
              >
              </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'

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

const route = useRoute()

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

const attrKeys = computed(() => Object.keys(state.attrSource))

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

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

state.deviceId = route.query.id as string

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

watch(
  () => activeTabKey.value,
  () => activeTabKey.value === 'session' ? getDeviceSession() : getDeviceAttr()
)

// 获取当前时间到半小时之前
const getDateBeforeByHalf = () => {
  const curTimeStamp = new Date().getTime()

  const halfHourTimeStampBefore = curTimeStamp - 60 * 30 * 1000
  return [dayjs(curTimeStamp), dayjs(halfHourTimeStampBefore)]
}

console.log(getDateBeforeByHalf())

// watch(
//   () => state.attrSource,
//   () => {
//     nextTick(() => {
//       Object.keys(state.attrSource).forEach(key => {
//         const chartDom = document.getElementById('device-attr-' + key)

//         const myChart = echarts.init(chartDom!)
//         const attrItem = state.attrSource[key]

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

//         attrEchartsJson.series[0].data = attrItem.map(item => item.longValue)

//         attrEchartsJson.title.text = key

//         myChart.setOption(attrEchartsJson)
//       })
//       state.loading = false
//     })
//   }
// )

// watch(
//   () => state.dataSource,
//   () => {
//     if (activeTabKey.value === 'session') {
//       const chartDom = document.getElementById('device-session')
//       const chartDomScatter = document.getElementById('device-session-scatter')
//       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' ? '上线' : '下线')

//       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'
//         }
//       ]

//       scatterOption.series[0].data = state.dataSource.filter(item => item.sessionType === 'CONNECT').map(item => [0, connectCount])

//       scatterOption.series[1].data = state.dataSource.filter(item => item.sessionType !== 'CONNECT').map(item => [1, disconnectCount])

//       let currentOption = scatterOption

//       setInterval(function () {
//         currentOption = currentOption === scatterOption ? barOption : scatterOption
//         chartDomScatterChart.setOption(currentOption, true)
//       }, 2000)

//       chartDomScatterChart.setOption(currentOption)
//       myChart.setOption(sessionEchartsJson)

//       state.loading = false
//     }
//   }
// )

watch(
  () => state.deviceId,
  () => activeTabKey.value === 'session' ? getDeviceSession() : getDeviceAttr()
)

const changeRangePicker = (time) => {
  const [startTime, endTime] = time

  state.start = new Date(startTime).getTime()
  state.end = new Date(endTime).getTime()

  activeTabKey.value === 'session' ? getDeviceSession() : getDeviceAttr()
}

const selectDevice = () => {

}

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

const getDeviceSession = async () => {
  if (!state.deviceId) return
  state.loading = true
  const { data } = await DeviceContriller.getSession({ deviceId: state.deviceId, start: state.start, end: state.end })
  state.dataSource = data
}

const getDeviceAttr = async () => {
  if (!state.deviceId) return
  state.loading = true
  const { data } = await DeviceContriller.getAttr({ deviceId: state.deviceId, start: state.start, end: state.end })
  state.attrSource = data
}

const getDeviceList = async () => {
  state.spinning = true
  const { data } = await DeviceContriller.list()
  state.spinning = false
  deviceState.dataSource = data
}

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