<template>
  <div class="device-detail-page">
    <el-card class="main-card" style="padding: 0" body-style="padding-bottom: 0">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item :label="t('device.device-log798283-0')" prop="logType">
          <el-select
            v-model="queryParams.logType"
            :placeholder="t('device.device-log798283-1')"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in dict.type.iot_event_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('device.device-log798283-2')" prop="identity">
          <el-input
            v-model="queryParams.identity"
            :placeholder="t('device.device-log798283-3')"
            clearable
            size="small"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('device.device-log798283-4')">
          <el-date-picker
            v-model="daterangeTime"
            size="small"
            style="width: 240px"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            :start-placeholder="t('device.device-log798283-5')"
            :end-placeholder="t('device.device-log798283-6')"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" size="small" @click="handleQuery">{{
            t('device.device-log798283-7')
          }}</el-button>
          <el-button icon="Refresh" size="small" @click="resetQuery">{{
            t('device.device-log798283-8')
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="main-card" body-style="padding-top: 0">
      <el-table :border="false" v-loading="loading" :data="deviceLogList" size="small">
        <el-table-column
          :label="t('device.device-log798283-9')"
          align="center"
          prop="logType"
          width="120"
        >
          <template #default="scope">
            <dict-tag :options="dict.type.iot_event_type" :value="scope.row.logType" />
          </template>
        </el-table-column>
        <el-table-column
          :label="t('device.device-log798283-10')"
          align="center"
          prop="logType"
          width="120"
        >
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.mode == 1">{{
              t('device.device-log798283-11')
            }}</el-tag>
            <el-tag type="success" v-else-if="scope.row.mode == 2">{{
              t('device.device-log798283-12')
            }}</el-tag>
            <el-tag type="info" v-else>{{ t('device.device-log798283-13') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="t('device.device-log798283-14')"
          align="center"
          prop="createTime"
          width="150"
        >
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('device.device-log798283-2')" align="center" prop="identity" />
        <el-table-column
          :label="t('device.device-log798283-15')"
          align="left"
          header-align="center"
          prop="logValue"
        >
          <template #default="scope">
            <div v-html="formatValueDisplay(scope.row)"></div>
          </template>
        </el-table-column>

        <el-table-column
          :label="t('device.device-log798283-16')"
          header-align="center"
          align="left"
          prop="remark"
        >
          <template #default="scope">
            {{ scope.row.remark == null ? t('device.device-log798283-17') : scope.row.remark }}
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 40px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
// import { listEventLog } from '@/api/iot/eventLog'

// 定义属性
const props = defineProps({
  device: {
    type: Object,
    default: null
  }
})

// 定义组件名称和字典
defineOptions({
  name: 'DeviceLog',
  dicts: ['iot_event_type', 'iot_yes_no']
})

// Refs
const queryFormRef = ref()

// Reactive data
const thingsModel = reactive({})
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const deviceLogList = ref([])
const daterangeTime = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  logType: null,
  logValue: null,
  deviceId: null,
  serialNumber: null,
  deviceName: null,
  identity: null,
  isMonitor: null
})

const deviceInfo = ref({})

// Watch
watch(
  () => props.device,
  (newVal, oldVal) => {
    deviceInfo.value = newVal
    if (deviceInfo.value && deviceInfo.value.deviceId != 0) {
      queryParams.serialNumber = deviceInfo.value.serialNumber
      getList()
      // 解析缓存物模型
      Object.assign(thingsModel, deviceInfo.value.cacheThingsModel)
    }
  }
)

// Methods
const getList = () => {
  loading.value = true
  // 这里需要实现 addDateRange 方法或者使用其他方式处理日期范围
  const params = { ...queryParams }
  if (daterangeTime.value && daterangeTime.value.length === 2) {
    params.beginTime = daterangeTime.value[0]
    params.endTime = daterangeTime.value[1]
  }

  // listEventLog(params).then((response) => {
  //   deviceLogList.value = response.rows
  //   total.value = response.total
  //   loading.value = false
  // })
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  daterangeTime.value = []
  handleQuery()
}

// 格式化显示数据定义
const formatValueDisplay = (row) => {
  // 类型（1=属性上报，2=调用功能，3=事件上报，4=设备升级，5=设备上线，6=设备离线）
  if (row.logType == 1) {
    let propertyItem = getThingsModelItem(1, row.identity)
    if (propertyItem != '') {
      return (
        (propertyItem.parentName
          ? '[' +
            propertyItem.parentName +
            (propertyItem.arrayIndex ? propertyItem.arrayIndex : '') +
            '] '
          : '') +
        propertyItem.name +
        '： <span style="color:#409EFF;">' +
        getThingsModelItemValue(propertyItem, row.logValue) +
        ' ' +
        (propertyItem.datatype.unit != undefined ? propertyItem.datatype.unit : '') +
        '</span>'
      )
    }
  } else if (row.logType == 2) {
    let functionItem = getThingsModelItem(2, row.identity)
    if (functionItem != '') {
      return (
        (functionItem.parentName
          ? '[' +
            functionItem.parentName +
            (functionItem.arrayIndex ? functionItem.arrayIndex : '') +
            '] '
          : '') +
        functionItem.name +
        '： <span style="color:#409EFF">' +
        getThingsModelItemValue(functionItem, row.logValue) +
        ' ' +
        (functionItem.datatype.unit != undefined ? functionItem.datatype.unit : '') +
        '</span>'
      )
    }
  } else if (row.logType == 3) {
    let eventItem = getThingsModelItem(3, row.identity)
    if (eventItem != '') {
      return (
        (eventItem.parentName
          ? '[' + eventItem.parentName + (eventItem.arrayIndex ? eventItem.arrayIndex : '') + '] '
          : '') +
        eventItem.name +
        '： <span style="color:#409EFF">' +
        getThingsModelItemValue(eventItem, row.logValue) +
        ' ' +
        (eventItem.datatype.unit != undefined ? eventItem.datatype.unit : '') +
        '</span>'
      )
    } else {
      return row.logValue
    }
  } else if (row.logType == 4) {
    return '<span style="font-weight:bold">设备升级</span>'
  } else if (row.logType == 5) {
    return '<span style="font-weight:bold">设备上线</span>'
  } else if (row.logType == 6) {
    return '<span style="font-weight:bold">设备离线</span>'
  }
  return ''
}

// 获取物模型项中的值
const getThingsModelItemValue = (item, oldValue) => {
  // 枚举和布尔转换为文字
  if (item.datatype.type == 'bool') {
    if (oldValue == '0') {
      return item.datatype.falseText
    } else if (oldValue == '1') {
      return item.datatype.trueText
    }
  } else if (item.datatype.type == 'enum') {
    for (let i = 0; i < item.datatype.enumList.length; i++) {
      if (oldValue == item.datatype.enumList[i].value) {
        return item.datatype.enumList[i].text
      }
    }
  }
  return oldValue
}

// 获取物模型中的项
const getThingsModelItem = (type, identity) => {
  if (type == 1 && thingsModel.properties) {
    for (let i = 0; i < thingsModel.properties.length; i++) {
      //普通类型 integer/decimal/string/emum//bool
      if (thingsModel.properties[i].id == identity) {
        return thingsModel.properties[i]
      }
      // 对象 object
      if (thingsModel.properties[i].datatype.type == 'object') {
        for (let j = 0; j < thingsModel.properties[i].datatype.params.length; j++) {
          if (thingsModel.properties[i].datatype.params[j].id == identity) {
            thingsModel.properties[i].datatype.params[j].parentName = thingsModel.properties[i].name
            return thingsModel.properties[i].datatype.params[j]
          }
        }
      }
      // 数组 array
      if (
        thingsModel.properties[i].datatype.type == 'array' &&
        thingsModel.properties[i].datatype.arrayType
      ) {
        if (thingsModel.properties[i].datatype.arrayType == 'object') {
          // 数组元素格式：array_01_parentId_humidity,array_01_前缀终端上报时加上，物模型中没有
          let realIdentity = identity
          let arrayIndex = 0
          if (identity.indexOf('array_') > -1) {
            arrayIndex = identity.substring(6, 8)
            realIdentity = identity.substring(9)
          }
          for (let j = 0; j < thingsModel.properties[i].datatype.params.length; j++) {
            if (thingsModel.properties[i].datatype.params[j].id == realIdentity) {
              // 标注索引和父级名称
              thingsModel.properties[i].datatype.params[j].arrayIndex = Number(arrayIndex) + 1
              thingsModel.properties[i].datatype.params[j].parentName =
                thingsModel.properties[i].name
              return thingsModel.properties[i].datatype.params[j]
            }
          }
        } else {
          // 普通类型
          for (let j = 0; j < thingsModel.properties[i].datatype.arrayCount.length; j++) {
            if (thingsModel.properties[i].id == realIdentity) {
              thingsModel.properties[i].arrayIndex = Number(arrayIndex) + 1
              thingsModel.properties[i].parentName = "t('device.device-log798283-21')"
              return thingsModel.properties[i]
            }
          }
        }
      }
    }
  } else if (type == 2 && thingsModel.functions) {
    for (let i = 0; i < thingsModel.functions.length; i++) {
      //普通类型 integer/decimal/string/emum/bool
      if (thingsModel.functions[i].id == identity) {
        return thingsModel.functions[i]
      }
      // 对象 object
      if (thingsModel.functions[i].datatype.type == 'object') {
        for (let j = 0; j < thingsModel.functions[i].datatype.params.length; j++) {
          if (thingsModel.functions[i].datatype.params[j].id == identity) {
            thingsModel.functions[i].datatype.params[j].parentName = thingsModel.functions[i].name
            return thingsModel.functions[i].datatype.params[j]
          }
        }
      }
      // 数组 array
      if (
        thingsModel.functions[i].datatype.type == 'array' &&
        thingsModel.functions[i].datatype.arrayType
      ) {
        // 数组元素格式：array_01_parentId_humidity,array_01_前缀终端上报时加上，物模型中没有
        let realIdentity = identity
        let arrayIndex = 0
        if (identity.indexOf('array_') > -1) {
          arrayIndex = identity.substring(6, 8)
          realIdentity = identity.substring(9)
        }
        if (thingsModel.functions[i].datatype.arrayType == 'object') {
          for (let j = 0; j < thingsModel.functions[i].datatype.params.length; j++) {
            if (thingsModel.functions[i].datatype.params[j].id == realIdentity) {
              // 标注索引和父级名称
              thingsModel.functions[i].datatype.params[j].arrayIndex = Number(arrayIndex) + 1
              thingsModel.functions[i].datatype.params[j].parentName = thingsModel.functions[i].name
              return thingsModel.functions[i].datatype.params[j]
            }
          }
        } else {
          // 普通类型
          for (let j = 0; j < thingsModel.functions[i].datatype.arrayCount.length; j++) {
            if (thingsModel.functions[i].id == realIdentity) {
              thingsModel.functions[i].arrayIndex = Number(arrayIndex) + 1
              thingsModel.functions[i].parentName = "t('device.device-log798283-21')"
              return thingsModel.functions[i]
            }
          }
        }
      }
    }
  } else if (type == 3 && thingsModel.events) {
    for (let i = 0; i < thingsModel.events.length; i++) {
      if (thingsModel.events[i].id == identity) {
        return thingsModel.events[i]
      }
    }
  }
  return ''
}

// Lifecycle
onMounted(() => {
  if (props.device) {
    queryParams.serialNumber = props.device.serialNumber
    getList()
  }
})
</script>
