<template>
  <div class="main animate__animated animate__backInRight" v-loading="loading">
    <custom-search-bar :fields="fields.filter((f) => f.isSearch)" v-model="searchForm" @search="search" @reset="toReset"></custom-search-bar>
    <custom-button-bar :fields="buttonFields" @add="toAdd"></custom-button-bar>
    <custom-table :data="data" :fields="fields" @query="search" :total="total" :opera="opera" @edit="toEdit" @delete="toDelete" :select="true"> </custom-table>
    <el-dialog v-model="dialog" title="数据维护信息" :destroy-on-close="false" @close="toClose" width="50%">
      <custom-form v-model="form" :fields="fields" :rules="{}" @save="toSave"> </custom-form>
    </el-dialog>
  </div>
</template>

<script setup>
const $checkRes = inject('$checkRes')
import { cloneDeep, get } from 'lodash-es'
const { t } = useI18n()
// 接口
import { PerformanceStore } from '@/store/api/core/performance'
const store = PerformanceStore()
const data = ref([])
const searchForm = ref({})
const fields = [
  { label: '节点名称', model: 'node_name', isSearch: true },
  { label: '管理IP', model: 'admin_ip' },
  { label: '系统IP', model: 'system_ip' },
  { label: '开关机状态', model: 'switch' },
  { label: 'CPU利用率(%)', model: 'cpu_utilize' },
  { label: 'GPU利用率(%)', model: 'gpu_utilize' },
  { label: '内存利用率(%)', model: 'memory' },
  { label: '网络端口收发速度', model: 'speed' },
  { label: '负载', model: 'load' }
]
const opera = [
  { label: t('common.update'), method: 'edit' },
  { label: t('common.delete'), method: 'delete', confirm: true, type: 'danger' }
]
const buttonFields = [{ label: t('common.add'), method: 'add' }]
let skip = 0
let limit = inject('limit')
const total = ref(20)
// 加载中
const loading = ref(false)
const dialog = ref(false)
const form = ref({})
// 请求
onMounted(async () => {
  loading.value = true
  await search({ skip, limit })
  loading.value = false
})
const search = async (query = { skip: 0, limit }) => {
  const info = { skip: query.skip, limit: query.limit, ...searchForm.value }
  const res = await store.query(info)
  if (res.errcode == '0') {
    data.value = res.data.data
    total.value = res.data.total
  }
}
// 添加
const toAdd = () => {
  dialog.value = true
}
// 修改
const toEdit = (data) => {
  form.value = data
  dialog.value = true
}
// 删除
const toDelete = async (data) => {
  const res = await store.del(data._id)
  if ($checkRes(res, true)) {
    search({ skip: 0, limit })
  }
}
const toSave = async () => {
  const data = cloneDeep(form.value)
  let res
  if (get(data, '_id')) res = await store.update(data)
  else res = await store.create({ ...data })
  if ($checkRes(res, true)) {
    search({ skip: 0, limit })
    toClose()
  }
}
// 重置
const toReset = async () => {
  searchForm.value = {}
  await search({ skip, limit })
}
const toClose = () => {
  form.value = {}
  dialog.value = false
}
</script>
<style scoped lang="scss"></style>
