Newer
Older
smartwell_front / src / views / home / device / device / index.vue
liyaguang on 9 May 20 KB 新需求修改*2
<!--
  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, syncDeviceStatus } 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 $route = useRoute()
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: '85', sortable: true },
  { text: '设备编号', value: 'devcode', align: 'center', isRequired: true, width: '160', isCustom: true, sortable: true },
  { text: '设备类型', value: 'deviceTypeName', align: 'center', isRequired: true, width: '220' },
  { text: '监测对象', value: 'watchObject', align: 'center', width: '85', isRequired: false },
  { text: '设备型号', value: 'deviceModel', align: 'center', isRequired: false },
  { text: '名称', value: 'ledgerName', align: 'center', isRequired: false, width: '120' },
  { text: '标签', value: 'marker', align: 'center', isRequired: false },
  { 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: '85', sortable: true },
  { text: '最新上传时间', value: 'logtime', align: 'center', isRequired: true, width: '150', sortable: true },
  { 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: '',
  deviceCategory: '',
  monitorType: '',
  devTypeIds: [],
  ledgerName: '', // 闸井名称
  marker: '' // 闸井标签
})
// 开始结束时间
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,
    devTypeIds: listQuery.value.devTypeIds.join(','),
  }).then((res) => {
    list.value = []
    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: item.installDate ? dayjs(item.installDate).format('YYYY-MM-DD') : '',
      // bfztName: item.bfzt === '1' ? '布防' : '撤防',
      cellName: item.cell ? item.cell.includes('V') || item.cell.includes('mV') ? item.cell : parseInt(item.cell) < 30 ? '电量低' : '充足' : '充足',
      deviceTypeName: item.typeName,
    }))
    // console.log(list.value, 'list.')
    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: '',
    deviceCategory: '',
    monitorType: '',
    devTypeIds: [],
    ledgerName: '', // 闸井名称
    marker: '' // 闸井标签
  }
  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], [row.devcode]).then((response) => {
      if (response.code === 200) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
        fetchData()
      }
    })
  })
}
// 撤防
const changeDefense = (row: any) => {
  ElMessageBox.confirm(
    // scope.row.bfzt === '1' ? '撤防' : '布防'
    `确定要${row.bfzt === '1' ? '撤防' : '布防'}${row.devcode}设备吗?`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    bfDevice({
      bfcf: row.bfzt === '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) => {
    if (res.data) {
      downloadFile(res.data, '设备导入模板.xlsx')
    }

    loading.close()
  }).catch(() => {
    loading.close()
  })
}
// 同步设备状态
const syncDevice = () => {
  ElMessageBox.confirm(
    `确定要同步设备状态吗?`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(res => {
    syncDeviceStatus({})
    setTimeout(() => {
      ElMessage.success('同步成功,请等待。。。')
    }, 500)
  })
}
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 () => {
  // 厂商
  const res1 = await getManufacturerListPage()
  manufacturerList.value = res1.data.rows.map((item: any) => ({
    name: item.name || '',
    id: item.id,
    value: item.id,
  }))
  if($route.path.includes('meet')) {
    const needShow = ['迅腾', '环能']
    manufacturerList.value = manufacturerList.value.filter((item: { id: string; name: string; value: string }) => needShow.some((citem: string) => item.name.includes(citem)))
    listQuery.value.manufacturerId = manufacturerList.value[0].id
  }
  // 是否启用
  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 : '',
    //   }))
    // }
  })

}
onMounted(async () => {
  await fetchDict()
  fetchData()
})
const { proxy } = getCurrentInstance() as any
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'DeviceManage')
})
onActivated(() => {
  // 从编辑或者新增页面回来需要重新获取列表数据
  // $router.options.history.state.back 上一次路由地址
  if (!($router.options.history.state.back as string || '').includes('detail')) {
    // console.log('需要重新获取列表')
    fetchData()
  }
})

const isShowMore = ref(false)
const toggleSearchMore = () => {
  isShowMore.value = !isShowMore.value
}
</script>

<template>
  <!-- 布局 -->
  <app-container>
    <add-dialog ref="addRef" @refresh="fetchData" />
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="fetchData" @clear="reset">
      <template #middle-btns>
        <el-button type="primary" class="search-btn" @click="toggleSearchMore">
          高级检索
        </el-button>
      </template>
      <search-item>
        <el-input v-model="listQuery.devCode" placeholder="设备编号" clearable style="width: 162px;" />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.devTypeIds" placeholder="设备类型" :max-collapse-tags="1" multiple collapse-tags filterable clearable collapse-tags-tooltip
        style="width: 182px;" class="select-device-type">
          <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 style="width: 162px;" />
      </search-item>
      <search-item>
        <dept-select v-model="listQuery.deptId" placeholder="管理单位" :clearable="true" class="select"
        style="width: 162px;" />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.manufacturerId" placeholder="厂商" filterable :clearable="!$route.path.includes('meet')" class="select"
        style="width: 162px;">
          <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: 162px;">
          <el-option v-for="item in onlineStateList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item v-show="isShowMore">
        <el-select v-model="listQuery.cell" placeholder="电量情况" filterable clearable class="select"
        style="width: 162px;">
          <el-option v-for="item in cellList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item v-show="isShowMore">
        <el-select v-model="listQuery.valid" placeholder="设备在用情况" filterable clearable class="select"
        style="width: 162px;">
          <el-option v-for="item in useStatusList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item v-show="isShowMore">
        <el-select v-model="listQuery.bfcf" placeholder="布防状态" filterable clearable class="select"
        style="width: 162px;">
          <el-option label="布防" value="1" />
          <el-option label="撤防" value="0" />
        </el-select>
      </search-item>
      <search-item v-show="isShowMore">
        <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-item>
        <!-- <div style="display: flex; align-items: center;">
          <span>设备类别</span>
          <el-checkbox-group v-model="deviceCategory">
            <el-checkbox label="自有设备" value="0" />
            <el-checkbox label="数据服务" value="1" />
          </el-checkbox-group>
        </div> -->
        <el-select v-model="listQuery.deviceCategory" placeholder="设备类别" filterable clearable class="select"
        style="width: 162px;">
          <el-option label="自有设备" value="0" />
          <el-option label="数据服务" value="1" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model="listQuery.monitorType" placeholder="监测类型" filterable clearable class="select"
        style="width: 162px;">
          <el-option label="长期" value="1" />
          <el-option label="临时" value="0" />
        </el-select>
      </search-item>
      <search-item v-show="isShowMore">
        <el-input v-model="listQuery.ledgerName" placeholder="名称" clearable style="width: 162px;" />
      </search-item>
      <search-item v-show="isShowMore">
        <el-input v-model="listQuery.marker" placeholder="标签" clearable style="width: 162px;" />
      </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/sync')" type="primary" @click="syncDevice">
            设备状态同步
          </el-button>
          <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'" />
          <!-- 设备编号 -->
          <span v-if="column.text === '设备编号'" style="display: flex;justify-content: center;align-items: center;">
            <el-tooltip class="box-item" effect="dark"
              :content="`${scope.row.deviceTypeName}(${scope.row.manufactureName})`" placement="top">
              {{ scope.row[column.value] }}
            </el-tooltip>
            <span v-if="scope.row.deviceCategory === '1'" class="device-data">数</span>
          </span>
        </template>
        <template #columns>
          <el-table-column label="操作" align="center" width="170">
            <template #default="scope">
              <el-button
                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: 162px;
}
</style>

<style lang="scss" scoped>
.select-device-type {
  ::v-deep(.el-tag) {
    max-width: 120px;
  }
}
.circle {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  margin: 0 auto;
}

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

.offline {
  background-color: #7f7f7f;
}

.pointer {
  &:hover {
    cursor: pointer;
  }
}

.device-data {
  display: inline-block;
  background-color: #0d76d4;
  width: 18px !important;
  height: 18px !important;
  color: #fff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 5px;
  font-size: 12px;
  flex-shrink: 0;
}

.link {
  // color: #0d76d4 !important;

  &:hover {
    text-decoration: underline !important;
  }
}
</style>