Newer
Older
smartwell_front / src / views / home / device / device / index.vue
liyaguang on 11 Dec 16 KB 报警规则修改
<!--
  Description: 设备管理-设备管理
  Author: 李亚光
  Date: 2024-07-19
 -->
<script lang="ts" setup name="DeviceManage">
import dayjs from 'dayjs'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import addDialog from './components/addDialog.vue'
import { bfDevice, exportDevice, getDeviceListPage, importDevice, removeDevice, templateDevice } from '@/api/home/device/device'
import { getDeviceTypeListPage } from '@/api/home/device/type'
import { getDictByCode } from '@/api/system/dict'
import { getManufacturerListPage } from '@/api/home/device/product'
import { exportFile } from '@/utils/exportUtils'
import { shortcuts } from '@/utils/common'
import { downloadFile } from '@/utils/download'
import { keepSearchParams } from '@/utils/keepQuery'

const $router = useRouter()
const useStatusList = ref<{ id: string; name: string; value: string }[]>([]) // 设备在用情况
const deviceTypeList = ref<{ id: string; name: string; value: string }[]>([]) // 设备类型
// 表格数据
const list = ref<any[]>([])
const total = ref(0)
// 初始展示列
const columns = ref<any>([
  { text: '状态', value: 'onlineState', align: 'center', isCustom: true, width: '55' },
  { text: '设备编号', value: 'devcode', align: 'center', isRequired: true, width: '150' },
  { text: '设备类型', value: 'deviceTypeName', align: 'center', isRequired: true, width: '220' },
  { text: '监测对象', value: 'watchObject', align: 'center', width: '85' },
  { text: '设备型号', value: 'deviceModel', align: 'center' },
  { text: '厂商', value: 'manufactureName', align: 'center', isRequired: true },
  { text: '安装位号', value: 'tagNumber', align: 'center', isRequired: true, width: '110' },
  { text: '详细位置', value: 'position', align: 'center', isRequired: true },
  { text: '管理单位', value: 'deptName', align: 'center', isRequired: true },
  { text: '在用情况', value: 'validName', align: 'center', isRequired: true, width: '85' },
  { text: '布防状态', value: 'bfztName', align: 'center', isRequired: true },
  { text: '电量', value: 'cellName', align: 'center', isRequired: true, width: '70' },
  { text: '最新上报时间', value: 'logtime', align: 'center', isRequired: true, width: '120' },
  { text: '安装日期', value: 'installDate', align: 'center', isRequired: true, width: '120' },
])
// 最终展示列
const columnsConfig = ref([])
// 修改列
const editColumns = (data: any) => {
  columnsConfig.value = data
}
const loadingTable = ref(true)
//  查询条件
const listQuery = ref({
  limit: 20,
  offset: 1,
  devCode: '', // 设备编号
  devTypeId: '', // 设备类型
  keys: '', // 设备类型
  deptId: '', // 管理单位
  manufacturerId: '', // 厂商
  onlineState: '', // 在线状态
  cell: '', // 电量情况
  valid: '', // 设备在用情况
  logTime1: '',
  logTime2: '',
  bfcf: '',
})
// 开始结束时间
const datetimerange = ref()
watch(() => datetimerange.value, (newVal) => {
  listQuery.value.logTime1 = ''
  listQuery.value.logTime2 = ''
  if (Array.isArray(newVal)) {
    if (newVal.length) {
      listQuery.value.logTime1 = `${newVal[0]}`
      listQuery.value.logTime2 = `${newVal[1]}`
    }
  }
})
// 查询数据
const fetchData = () => {
  loadingTable.value = true
  getDeviceListPage(listQuery.value).then((res) => {
    // console.log(res.data, '数据列表')
    list.value = res.data.rows.map((item: any) => ({
      ...item,
      validName: useStatusList.value.length ? useStatusList.value[useStatusList.value.findIndex(citem => item.valid === citem.value)].name : '',
      deviceTypeName: deviceTypeList.value.length ? deviceTypeList.value[deviceTypeList.value.findIndex(citem => item.deviceType === citem.value)].name : '',
      installDate: dayjs(item.installDate).format('YYYY-MM-DD'),
      bfztName: item.bfzt === '1' ? '布防' : '撤防',
      cellName: item.cell ? Number(item.cell) < 30 ? '电量低' : '充足' : '充足',
    }))
    total.value = res.data.total
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}
// 重置查询条件f
const reset = () => {
  datetimerange.value = []
  listQuery.value = {
    limit: 20,
    offset: 1,
    devCode: '', // 设备编号
    devTypeId: '', // 设备类型
    keys: '', // 设备类型
    deptId: '', // 管理单位
    manufacturerId: '', // 厂商
    onlineState: '', // 在线状态
    cell: '', // 电量情况
    valid: '', // 设备在用情况
    logTime1: '',
    logTime2: '',
    bfcf: '',
  }
  fetchData()
}
// 页数发生变化后的操作,可能是页码变化,可能是每页容量变化,此函数必写
const changePage = (val: { size: number; page: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData()
}
// 新建或者编辑
const addRef = ref()
const editRow = (type: string, row: any) => {
  if (type === 'detail') {
    $router.push({
      path: `/manage/${type}`,
      query: {
        id: row.id,
        row: JSON.stringify(row),
      },
    })
    return
  }
  addRef.value.initDialog(type, row)
}
// 删除
const removeRow = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除该数据吗?',
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    removeDevice([row.id]).then((response) => {
      if (response.code === 200) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
        fetchData()
      }
    })
  })
}
// 撤防
const changeDefense = (row: any) => {
  ElMessageBox.confirm(
    `确定要${row.bfcf === '1' ? '撤防' : '布防'}${row.devcode}设备吗?`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    bfDevice({
      bfcf: row.bfcf === '1' ? '0' : '1',
      id: row.id,
      devcode: row.devcode,
    }).then((res) => {
      ElMessage.success('操作成功')
      fetchData()
    })
  })
}
// 导出列表
const exportList = () => {
  if (!list.value.length) {
    ElMessage.warning('暂无导出数据')
    return
  }
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  exportDevice(listQuery.value).then((res) => {
    exportFile(res.data, '设备列表.xlsx')
    loading.close()
  }).catch(() => {
    loading.close()
  })
}
const fileRef = ref() // 文件上传input,获取input的引用
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('file', event.target.files[0])
    // fd.append('equipmentType', $props.equipmentType)
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    // export function importDevice(data: object, deviceType: string) {
    //   return request({
    //     url: `/equipment/info/import?equipmentType=${deviceType}`,
    //     method: 'post',
    //     data,
    //   })
    // }
    importDevice(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('导入成功')
        fileRef.value.value = ''
        loading.close()
        fetchData()
      }
      else {
        fileRef.value.value = ''
        // ElMessage.error(res.message)
        loading.close()
      }
    }).catch(() => {
      fileRef.value.value = ''
      // ElMessage.error(err.message)
      loading.close()
    })
  }
}
// 导入
const importList = () => {
  fileRef.value.click()
}
// 模板下载
const downloadTemplate = () => {
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  templateDevice().then((res) => {
    // console.log(res.data, '123123')
    if (res.data) {
      downloadFile(res.data, '设备导入模板.xlsx')
    }

    loading.close()
  }).catch(() => {
    loading.close()
  })
}
const isUsed = ref<{ id: string; name: string; value: string }[]>([]) // 是否启用

const manufacturerList = ref<{ id: string; name: string; value: string }[]>([]) // 厂商列表
const cellList = ref<{ id: string; name: string; value: string }[]>([]) // 厂商列表

const onlineStateList = ref<{ id: string; name: string; value: string }[]>([
  {
    name: '在线',
    value: '1',
    id: '1',
  },
  {
    name: '离线',
    value: '0',
    id: '0',
  },
]) // 在线状态
// 获取字典
const fetchDict = async () => {
  // 是否启用
  getDictByCode('isUsed').then((res) => {
    isUsed.value = res.data
  })
  // 电量情况
  getDictByCode('cellStatus').then((res) => {
    cellList.value = res.data
  })
  // 设备在用情况
  getDictByCode('useStatus').then((res) => {
    useStatusList.value = res.data
    if (list.value.length) {
      list.value = list.value.map((item: any) => ({
        ...item,
        validName: useStatusList.value.length ? useStatusList.value[useStatusList.value.findIndex(citem => item.valid === citem.value)].name : '',
      }))
    }
  })
  // 设备类型
  getDeviceTypeListPage({ limit: 9999, offset: 1 }).then((res) => {
    deviceTypeList.value = res.data.rows.map((item: any) => ({ id: item.id, name: item.typeName, value: item.id }))
    if (list.value.length) {
      list.value = list.value.map((item: any) => ({
        ...item,
        deviceTypeName: deviceTypeList.value.length ? deviceTypeList.value[deviceTypeList.value.findIndex(citem => item.deviceType === citem.value)].name : '',
      }))
    }
  })
  // 厂商
  getManufacturerListPage().then((res) => {
    manufacturerList.value = res.data.rows.map((item: any) => ({
      name: item.name || '',
      id: item.id,
      value: item.id,
    }))
  })
}
onMounted(async () => {
  fetchDict()
  fetchData()
})
const { proxy } = getCurrentInstance() as any
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'DeviceManage')
})
onActivated(() => {
  // 从编辑或者新增页面回来需要重新获取列表数据
  // $router.options.history.state.forward 上一次路由地址
  if (!($router.options.history.state.forward as string || '').includes('detail')) {
    console.log('需要重新获取列表')
    fetchData()
  }
})
</script>

<template>
  <!-- 布局 -->
  <app-container>
    <add-dialog ref="addRef" @refresh="fetchData" />
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="fetchData" @clear="reset">
      <search-item>
        <el-input v-model="listQuery.devCode" placeholder="设备编号" clearable />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.devTypeId" placeholder="设备类型" filterable clearable class="select"
          style="width: 192px;"
        >
          <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-input v-model="listQuery.keys" placeholder="安装位号" clearable />
      </search-item>
      <search-item>
        <dept-select
          v-model="listQuery.deptId" placeholder="管理单位" :clearable="true" class="select"
          style="width: 192px;"
        />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.manufacturerId" placeholder="厂商" filterable clearable class="select"
          style="width: 192px;"
        >
          <el-option v-for="item in manufacturerList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.onlineState" placeholder="在线状态" filterable clearable class="select"
          style="width: 192px;"
        >
          <el-option v-for="item in onlineStateList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.cell" placeholder="电量情况" filterable clearable class="select"
          style="width: 192px;"
        >
          <el-option v-for="item in cellList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.valid" placeholder="设备在用情况" filterable clearable class="select"
          style="width: 192px;"
        >
          <el-option v-for="item in useStatusList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.bfcf" placeholder="布防状态" filterable clearable class="select"
          style="width: 192px;"
        >
          <el-option label="布防" value="1" />
          <el-option label="撤防" value="0" />
        </el-select>
      </search-item>
      <search-item>
        <el-date-picker
          v-model="datetimerange" type="datetimerange" format="YYYY-MM-DD HH:mm:ss" :shortcuts="shortcuts"
          value-format="YYYY-MM-DD HH:mm:ss" range-separator="至" start-placeholder="上报开始时间" end-placeholder="上报结束时间"
          clearable
        />
      </search-item>
    </search-area>
    <!-- 表头标题 -->
    <table-container
      :is-config="true" config-title="device-device" :columns="columns" :config-columns="columnsConfig"
      :edit="editColumns"
    >
      <template #btns-right>
        <!-- 操作 -->
        <div>
          <el-button v-if="proxy.hasPerm('/device/manage/add')" type="primary" @click="editRow('add', {})">
            新建
          </el-button>
          <el-button v-if="proxy.hasPerm('/device/manage/down')" type="primary" @click="downloadTemplate">
            模板下载
          </el-button>
          <el-button v-if="proxy.hasPerm('/device/manage/import')" type="primary" @click="importList">
            批量导入
          </el-button>
          <el-button v-if="proxy.hasPerm('/device/manage/export')" type="primary" @click="exportList">
            导出
          </el-button>
          <input ref="fileRef" style="display: none;" type="file" accept=".xls,.xlsx" @change="onFileChange">
        </div>
      </template>
      <!-- 查询结果Table显示 -->
      <normal-table
        :data="list" :total="total" :columns="columnsConfig" :query="listQuery" :list-loading="loadingTable"
        @change="changePage"
      >
        <template #preColumns>
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #isCustom="{ scope, column }">
          <!-- 状态 -->
          <div
            v-if="column.text === '状态'" class="circle"
            :class="scope.row.onlineState === '在线' ? 'online' : 'offline'"
          />
        </template>
        <template #columns>
          <el-table-column label="操作" align="center" width="150">
            <template #default="scope">
              <el-button v-if="proxy.hasPerm('/device/manage/detail')" type="primary" link size="small" @click="editRow('detail', scope.row)">
                查看
              </el-button>
              <el-button v-if="proxy.hasPerm('/device/manage/update')" type="primary" link size="small" @click="editRow('edit', scope.row)">
                编辑
              </el-button>
              <el-button v-if="proxy.hasPerm('/device/manage/add')" type="danger" link size="small" @click="changeDefense(scope.row)">
                {{ scope.row.bfzt === '1' ? '撤防' : '布防' }}
              </el-button>
              <el-button v-if="proxy.hasPerm('/device/manage/delete')" type="danger" link size="small" @click="removeRow(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss">
.select {
  width: 192px;
}
</style>

<style lang="scss" scoped>
.circle {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  margin: 0 auto;
}

.online {
  background-color: #95f204;
}

.offline {
  background-color: #7f7f7f;
}
</style>