<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="设备" prop="deviceName">
        <el-select
          v-model="queryParams.deviceName"
          @change="handleQuery"
          clearable
          filterable
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in deviceList"
            :key="item.id"
            :label="item.deviceName"
            :value="item.deviceName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="属性" prop="attribute">
        <el-select
          v-model="queryParams.attributes"
          @change="handleQuery"
          clearable
          filterable
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in deviceAttrList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="属性值" prop="attrValue">
        <el-input
          v-model="queryParams.attrValue"
          placeholder="请输入属性值"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-360px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['iot:mqtt-data-record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表和看板 -->
  <ContentWrap>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="数据" name="data" />
      <el-tab-pane label="看板" name="dashboard" />
    </el-tabs>

    <!-- 数据列表 -->
    <el-table v-if="activeName === 'data'" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="设备" align="center" prop="deviceName" />
      <el-table-column label="属性" align="center" prop="attribute" />
      <el-table-column label="属性值" align="center" prop="attrValue" />
      <el-table-column
        label="设备时间"
        align="center"
        prop="deviceTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['iot:mqtt-data-record:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-if="activeName === 'data'"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 看板图表 -->
    <div v-if="activeName === 'dashboard'" class="dashboard-container">
      <p>dewewe</p>
      <div ref="chartRef" class="chart-container"></div>
    </div>


  </ContentWrap>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MqttDataRecordApi, MqttDataRecordVO } from '@/api/iot/mqttdatarecord'
import { DeviceApi, DeviceVO } from "@/api/iot/device"
import { MqttRecordApi } from "@/api/iot/mqttrecord"
import { TabsPaneContext } from "element-plus"
import * as echarts from 'echarts'
import { onMounted, ref, reactive, watch } from 'vue'

/** 设备数据记录 列表 */
defineOptions({ name: 'MqttDataRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MqttDataRecordVO[]>([]) // 列表的数据
const deviceList = ref<DeviceVO[]>([])
const deviceAttrList = ref<string[]>([])
const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceName: undefined,
  attributes: [],
  attribute: undefined,
  attrValue: undefined,
  deviceTime: [],
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const activeName = ref('data') // 当前激活的tab

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MqttDataRecordApi.getMqttDataRecordPage2(queryParams)
    list.value = data.list
    total.value = data.total
    // 如果当前在看板tab，更新图表
    if (activeName.value === 'dashboard') {
      updateChart()
    }
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  if(deviceList.value!=null && deviceList.value.length > 0){
    deviceAttrList.value = await MqttRecordApi.getDeviceAttr(queryParams.deviceName)
  }
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MqttDataRecordApi.deleteMqttDataRecord(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MqttDataRecordApi.getMqttDataRecordPage2(queryParams)
    download.excel(data, '设备数据记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/** tab 切换 */
const handleTabClick = (tab: TabsPaneContext) => {
  if (tab.paneName === 'dashboard') {
    // 切换到看板时初始化图表
    if (!chart) {

    }
  }
}

/** 监听数据变化，更新图表 */
watch(() => list.value, () => {
  if (activeName.value === 'dashboard') {
  }
}, { deep: true })

let timer: any = null;
/** 初始化 **/
onMounted(async () => {
  deviceList.value = await DeviceApi.getDeviceList()
  getList()

  timer = setInterval(async () => {
    const data = await MqttDataRecordApi.getMqttDataRecordPage2(queryParams)
    list.value = data.list
    total.value = data.total
  }, 5000);
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
  if (chart) {
    chart.dispose()
    chart = null
  }
})

</script>

<style lang="scss" scoped>
.dashboard-container {
  width: 100%;
  height: 500px;
  margin-top: 20px;
  
  .chart-container {
    width: 100%;
    height: 100%;
  }
}
</style>
