<!-- 设备详情 -->
<script name="DeviceInfoDetail" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IConfigItem, IDeviceConfig, IDeviceInfo } from './device-info'
import DeviceConfigList from './configList.vue'
import DataQueryList from '@/views/data/query/list.vue'
import DeviceElectricityList from './electricity.vue'
import { addDevice, detailDevice, detailDeviceConfig, updateDevice } from '@/api/basic/device'

const configItemName = ref([
  { name: 'interval', text: '采集周期', unit: '分钟' },
  { name: 'repeat', text: '重传次数', unit: '' },
  { name: 'period', text: '上传周期', unit: '分钟' },
  { name: 'times', text: '采集次数', unit: '' },
  { name: 'acqStart', text: '采集开始时间', unit: '分钟' },
  { name: 'upperLimit', text: '报警上限', unit: '' },
  { name: 'lowerLimit', text: '报警上限', unit: '' },
  { name: 'destIp', text: '地址', unit: '' },
  { name: 'destPort', text: '端口', unit: '' },
])

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

const route = useRoute()
const router = useRouter()
const title = ref('')

const radioItems = ref([
  { name: '数据查询', value: 'device-data' },
  { name: '下发配置', value: 'device-config' },
  // { name: '耗电分析', value: 'device-cell' },
])
const current = ref('')
const currentLabel = ref('')

const basicFormRef = ref()

const deviceInfo = ref<IDeviceInfo>({
  id: '',
  groupId: '',
  devcode: '',
  deviceName: '',
  deviceType: '',
  deviceTypeName: '',
  status: '',
  statusName: '',
  cell: '',
  imei: '',
  iccid: '',
  model: '',
  modelName: '',
  productId: '',
  productName: '',
  encipherType: '',
  encipherTypeName: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  dataValue: '',
})

const deviceConfig = ref<IDeviceConfig>({
  deviceId: '',
  devCode: '',
  frameLogId: '',
  configJson: '',
  logtime: '',
})

const configItemList = ref<Array<IConfigItem>>([])

// 逻辑
const resetForm = () => {
  router.go(-1)
}

// 详情页的各个tab切换操作
const radioChangeHandler = (newVal: string | number | boolean) => {
  const radioTarget = radioItems.value.filter(item => item.name === newVal)
  if (radioTarget.length > 0) {
    currentLabel.value = radioTarget[0].name
    current.value = radioTarget[0].value
  }
  else {
    currentLabel.value = radioItems.value[0].name
    current.value = radioItems.value[0].value
  }
}

// 添加
const saveSealInfoForm = () => {
  // 将创建时间改为提交的时间
  deviceInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
  addDevice(deviceInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      type.value = 'detail'
      title.value = '设备详情（详情）'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}
// 编辑
const updateSealInfoById = () => {
  updateDevice(deviceInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      type.value = 'detail'
      title.value = '设备详情（详情）'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 保存
const saveForm = async () => {
  if (!basicFormRef) { return }

  await basicFormRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (type.value === 'create') {
          saveSealInfoForm()
        }
        else if (type.value === 'update') {
          updateSealInfoById()
        }
      })
    }
  })
}

// 查询详情
const loading = ref(true)
const detailById = (id: string) => {
  loading.value = true
  detailDevice({ id }).then((res) => {
    if (res.code === 200) {
      deviceInfo.value = res.data
    }
    loading.value = false
  }).catch(() => {
    loading.value = false
  })

  detailDeviceConfig(id).then((res) => {
    if (res.code === 200) {
      deviceConfig.value = res.data

      if (res.data !== '' && res.data.configItemList.length > 0) {
        configItemList.value = res.data.configItemList.map((item: any) => {
          return {
            ...item,
            text: configItemName.value.filter(nameDict => nameDict.name === item.cmd)[0].text,
          }
        })
      }
    }
  })
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  // 默认显示第一个tab内容
  current.value = radioItems.value[0].value
  currentLabel.value = radioItems.value[0].name

  switch (params.type) {
    case 'detail':
      title.value = '设备详情'
      id.value = params.id

      detailById(id.value)

      break
    default:
      title.value = ''
      break
  }
}

onMounted(async () => {
  initDialog(route.query)
})
</script>

<template>
  <app-container>
    <detail-page :title="`${title}`">
      <template #btns>
        <el-button type="info" @click="resetForm()">
          关闭
        </el-button>
      </template>

      <el-form v-loading="loading" ref="basicFormRef" :model="deviceInfo" label-position="left" label-width="110px"
        stripe>
        <el-row :gutter="24">
          <!-- 第一行 第一列 -->
          <el-col :span="6">
            <el-form-item label="设备编号：">
              {{ deviceInfo.devcode }}
            </el-form-item>
            <el-form-item label="设备IMEI：">
              {{ deviceInfo.imei }}
            </el-form-item>
          </el-col>

          <!-- 第一行 第二列 -->
          <el-col :span="6">
            <el-form-item label="所属产品：">
              {{ deviceInfo.productName }}
            </el-form-item>

            <el-form-item label="ICCID：">
              {{ deviceInfo.iccid }}
            </el-form-item>
          </el-col>

          <!-- 第一行 第三列 -->
          <el-col :span="6">
            <el-form-item label="设备类型：">
              {{ deviceInfo.deviceTypeName }}
            </el-form-item>

            <el-form-item label="加密方式：">
              {{ deviceInfo.encipherTypeName }}
            </el-form-item>
          </el-col>

          <!-- 第一行 第四列 -->
          <el-col :span="6">
            <el-form-item label="设备型号：">
              {{ deviceInfo.modelName }}
            </el-form-item>

            <el-form-item label="创建时间：">
              {{ deviceInfo.createTime }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24" style="margin-top: 20px;">
          <el-col :span="18">
            <el-form-item label="当前配置：">
              <el-tag v-for="item in configItemList" :key="item.idx" size="large" style="margin-right: 10px;">
                {{ item.text }} : {{ item.value }}
              </el-tag>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="收到时间：">
              {{ deviceConfig.logtime }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-radio-group v-model="currentLabel" style="margin: 20px;" @change="radioChangeHandler">
        <el-radio-button v-for="item in radioItems" :key="item.value" :label="item.name" :disabled="id === ''" />
      </el-radio-group>

      <template v-if="current === 'device-data'">
        <data-query-list :embedded="true" :dev-code="deviceInfo.devcode" />
      </template>

      <template v-if="current === 'device-config'">
        <device-config-list :devcode="deviceInfo.devcode" />
      </template>

      <!-- <template v-if="current === 'device-cell'">
        <DeviceElectricityList :devcode="deviceInfo.devcode" />
      </template> -->
    </detail-page>
  </app-container>
</template>
