<template>
  <el-drawer
    :title="t('rem.MonitoringDetails')"
    :append-to-body="true"
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    :show-close="false"
    :size="computedSize"
    :before-close="handleClose"
  >
    <template v-if="true">
      <ContentWrap v-loading="formLoading">
        <ContentWrap>
          <el-form style="height: 89px; margin-left: 20px">
            <el-row style="display: flex; flex-direction: row">
              <el-col :span="8">
                <el-form-item prop="deviceCode">
                  <template #label>
                    <span class="custom-label">{{ t('chooseMaintain.deviceCode') }}:</span>
                  </template>
                  <span class="custom-label">{{ formData.deviceCode }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="deviceName">
                  <template #label>
                    <span class="custom-label">{{ t('deviceForm.category') }}:</span>
                  </template>
                  <span class="custom-label">{{ formData.deviceName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="dept">
                  <template #label>
                    <span class="custom-label">{{ t('devicePerson.dept') }}:</span>
                  </template>
                  <span class="custom-label">{{ formData.dept }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="ifInline">
                  <template #label>
                    <span class="custom-label">{{ t('monitor.online') }}:</span>
                  </template>
                  <template #default>
                    <dict-tag :type="DICT_TYPE.IOT_DEVICE_STATUS" :value="formData.ifInline" />
                  </template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="lastInlineTime">
                  <template #label>
                    <span class="custom-label">{{ t('monitor.latestDataTime') }}:</span>
                  </template>
                  <span class="custom-label">{{ formData.lastInlineTime }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </ContentWrap>
        <ContentWrap>
          <el-row>
            <el-col :span="24">
              <TdDeviceLabel :tags="specs" @select="labelSelect" tag-width="32%" />
            </el-col>
          </el-row>
        </ContentWrap>
        <ContentWrap>
          <div class="chart-container">
            <!-- 图表容器 -->
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              start-placeholder="起始日期时间"
              end-placeholder="结束日期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleDateChange"
            />
            <div v-loading="loading" style="height: 100%" ref="chartContainer"></div>
          </div>
        </ContentWrap>
      </ContentWrap>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import {defineEmits, defineOptions, ref, watch} from 'vue'
import { DICT_TYPE } from '@/utils/dict'
import TdDeviceLabel from '@/views/pms/device/monitor/TdDeviceLabel.vue'
import dayjs from "dayjs";
import {IotStatApi} from "@/api/pms/stat";
import * as echarts from "echarts";
import {IotDeviceApi} from "@/api/pms/device";
import {propTypes} from "@/utils/propTypes";
const { t } = useI18n() // 国际化
const drawerVisible = ref<boolean>(false)
const emit = defineEmits(['update:modelValue', 'add', 'delete'])

defineOptions({
  name: 'DeviceMonitorDrawer'
})

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  bomId: '',
  name: '',
  code: ''
})

const windowWidth = ref(window.innerWidth)
// 动态计算百分比
const computedSize = computed(() => {
  return windowWidth.value > 1200 ? '60%' : '80%'
})

const formLoading = ref(false)
const total = ref(0) // 列表的总页数
const materials = ref([])

const props = defineProps({
  id: propTypes.number.def(undefined),
  dept: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  ifLine: undefined,
  lastLineTime: undefined
})

const formData = ref({
  id: undefined,
  deptName: '',
  deviceCode: '',
  deviceName: '',
  ifInline: undefined,
  lastInlineTime: ''
})
const specs = ref([])

// 响应式数据
const startTime = ref('')
const endTime = ref('')
const topicName = ref([])
const loading = ref(false)
const topic = ref('')

const handleDateChange = async (val) => {
  if (val && val.length === 2) {
    await getChart(val)
    await renderChart()

  }
}
const defaultEnd = dayjs()
const defaultStart = defaultEnd.subtract(1, 'day')
const dateRange = ref([
  defaultStart.format('YYYY-MM-DD HH:mm:ss'),
  defaultEnd.format('YYYY-MM-DD HH:mm:ss')
])
const labelSelect =async (row) =>{
  topic.value = row.identifier
  topicName.value = row.modelName
  await getChart(dateRange.value)
  await renderChart()
}

const chartContainer = ref(null)
let chartInstance = null

// 时间格式化（HH:mm）
const formatTime = timestamp => {
  return new Date(timestamp)
    .toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit',second:'2-digit' })
    .slice(0, 5)
}
const result = ref([])
const getChart = async (range) =>{
  loading.value = true
  debugger
  await IotStatApi.getDeviceInfoChart(props.deviceCode, topic.value, range[0], range[1]).then(res=>{
    result.value = res
    loading.value = false
  })
}
// 初始化图表
const renderChart = async () => {
  debugger
  if (!chartContainer.value) return

  // 销毁旧实例
  if (chartInstance) chartInstance.dispose()

  chartInstance = markRaw(echarts.init(chartContainer.value))
  const option = {
    title:{
      text: topicName.value+'数据趋势',
      left:'center',
    },
    tooltip: { trigger: 'axis', },
    xAxis: {
      type: 'category',
      // data: result.map(d => formatTime(d.timestamp)),
      data: result.value.map(d => dayjs(d.timestamp).format('YYYY-MM-DD HH:mm:ss')),
      axisLabel: { rotate: 45 }, // X轴标签旋转防止重叠
      inverse: true,
    },
    yAxis: { type: 'value' },
    dataZoom: [{
      type: 'slider',
      xAxisIndex: 0,
      start: 0,  // 初始显示范围开始位置
      end: 100   // 初始显示范围结束位置:ml-citation{ref="7" data="citationList"}
    }],
    series: [{
      // data: result.map(d => d.value),
      data: result.value.map(d => d.value),
      type: 'line',
      smooth: true,
      areaStyle: {} // 显示区域填充
    }]
  }

  chartInstance.setOption(option)

  // 窗口自适应
  window.addEventListener('resize', () => chartInstance.resize())
}
watch(() => props.id, async (newVal) => {
  if (newVal) {
    await init()
  }
})
const init =async () =>{
  drawerVisible.value = true
  formLoading.value = true

  formData.value.deviceCode = props.deviceCode
  formData.value.deviceName = props.deviceName
  formData.value.lastInlineTime = props.lastLineTime
  formData.value.ifInline = props.ifLine
  formData.value.dept = props.dept
  await IotDeviceApi.getIotDeviceTds(props.id).then(res => {
    specs.value = res
    specs.value = specs.value.sort((a, b) => {
      return b.modelOrder - a.modelOrder
    })
    formLoading.value = false
    topic.value = specs.value[0].identifier
    topicName.value = specs.value[0].modelName
  })
  await getChart(dateRange.value)
  debugger
  await renderChart()
}
// 打开抽屉
const openDrawer = async () => {
  if (props.id) {
    await init()
  }
}

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false
}

// 关闭抽屉
const handleClose = () => {
  emit('update:modelValue', false)
  materials.value = []
}

defineExpose({ openDrawer, closeDrawer }) // 暴露方法给父组件
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  margin: 20px auto;
  padding: 24px;
  //background: #f8f9fa;
  border-radius: 12px;
}
.chart-container {
  width: 100%;
  height: 600px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.date-controls {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

input[type="datetime-local"] {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s;
}

input[type="datetime-local"]:focus {
  border-color: #409eff;
  outline: none;
}

.separator {
  color: #606266;
}

.query-btn {
  padding: 8px 20px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.query-btn:hover {
  opacity: 0.8;
}

.custom-label{
  font-size: 17px;
  font-weight: bold;
}
</style>
