三拍团队设备增删改查

DeviceController

package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.Device;
import com.example.demo.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/*
 * Qi
 * 25/4/21
 * 设备的增删改查
 * */
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @GetMapping("/list")
    public Result getAllDevices() {
        return Result.success(deviceService.getAllDevices());
    }

    @GetMapping("/{deviceId}")
    public Result getDevice(@PathVariable String deviceId) {
        Device device = deviceService.getDeviceById(deviceId);
        return device != null ? Result.success(device) : Result.fail("设备不存在");
    }

    @PostMapping("/add")
    public Result addDevice(@RequestBody Device device) {
        if (deviceService.addDevice(device)) {
            return Result.success(device);
        }
        return Result.fail("添加设备失败,设备ID可能已存在");
    }

    @PutMapping("/update")
    public Result updateDevice(@RequestBody Device device) {
        if (deviceService.updateDevice(device)) {
            return Result.success(device);
        }
        return Result.fail("更新设备失败,设备可能不存在");
    }

    @DeleteMapping("/{deviceId}")
    public Result deleteDevice(@PathVariable String deviceId) {
        if (deviceService.deleteDevice(deviceId)) {
            return Result.success();
        }
        return Result.fail("删除设备失败,设备可能不存在");
    }
}

Device

package com.example.demo.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("devices")
public class Device {
    @TableId
    private String deviceId;
    private String deviceType;
    private String location;
    private String status;

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    public String getDeviceType() {
        return deviceType;
    }

    public void setDeviceType(String deviceType) {
        this.deviceType = deviceType;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

DeviceMapper

package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.Device;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface DeviceMapper extends BaseMapper<Device> {
}

DeviceServiceImpl

package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.Device;
import com.example.demo.mapper.DeviceMapper;
import com.example.demo.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/*
 * Qi
 * 25/4/21
 * 设备的增删改查
 * */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public List<Device> getAllDevices() {
        return deviceMapper.selectList(null);
    }

    @Override
    public Device getDeviceById(String deviceId) {
        return deviceMapper.selectById(deviceId);
    }

    @Override
    public boolean addDevice(Device device) {
        // 检查设备ID是否已存在
        Device existingDevice = deviceMapper.selectById(device.getDeviceId());
        if (existingDevice != null) {
            return false;
        }
        return deviceMapper.insert(device) > 0;
    }

    @Override
    public boolean updateDevice(Device device) {
        return deviceMapper.updateById(device) > 0;
    }

    @Override
    public boolean deleteDevice(String deviceId) {
        return deviceMapper.deleteById(deviceId) > 0;
    }
}

DeviceService

package com.example.demo.service;

import com.example.demo.entity.Device;
import java.util.List;
/*
 * Qi
 * 25/4/21
 * 设备的增删改查
 * */
public interface DeviceService {
    List<Device> getAllDevices();
    Device getDeviceById(String deviceId);
    boolean addDevice(Device device);
    boolean updateDevice(Device device);
    boolean deleteDevice(String deviceId);
}

<!-- Qi -->
<!-- 05/4/21 -->
<template>
  <div class="device-container">
    <div class="header">
      <el-button type="primary" @click="handleAdd">添加设备</el-button>
    </div>
    
    <el-table :data="deviceList" border style="width: 100%">
      <el-table-column prop="deviceId" label="设备编号" width="120" />
      <el-table-column prop="deviceType" label="设备类型" width="150" />
      <el-table-column prop="location" label="设备位置" width="200" />
      <el-table-column prop="status" label="设备状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <el-button 
            size="small" 
            type="warning" 
            @click="handleFaultReport(scope.row)"
            :disabled="scope.row.status === '故障'"
          >报修</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑设备对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="deviceForm" label-width="100px">
        <el-form-item label="设备编号" v-if="!isEdit">
          <el-input v-model="deviceForm.deviceId" />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-input v-model="deviceForm.deviceType" />
        </el-form-item>
        <el-form-item label="设备位置">
          <el-input v-model="deviceForm.location" />
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="deviceForm.status" style="width: 100%">
            <el-option label="正常" value="正常" />
            <el-option label="故障" value="故障" />
            <el-option label="维护中" value="维护中" />
            <el-option label="报废" value="报废" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDeviceList, addDevice, updateDevice, deleteDevice } from '@/api/device'
import FaultReportForm from './components/FaultReportForm.vue'

const deviceList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')
const deviceForm = ref({
  deviceId: '',
  deviceType: '',
  location: '',
  status: '正常'
})

// 获取设备列表
const fetchDeviceList = async () => {
  try {
    const res = await getDeviceList()
    if (res.code === 200) {  // 注意这里改为数字类型的 200
      deviceList.value = res.data || []  // 添加空数组作为默认值
    } else {
      ElMessage.error(res.msg || '获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表错误:', error)
    ElMessage.error('获取设备列表失败')
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '正常': 'success',
    '故障': 'danger',
    '维护中': 'warning',
    '报废': 'info'
  }
  return statusMap[status] || ''
}

// 添加设备
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加设备'
  deviceForm.value = {
    deviceId: '',
    deviceType: '',
    location: '',
    status: '正常'
  }
  dialogVisible.value = true
}

// 编辑设备
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑设备'
  deviceForm.value = { ...row }
  dialogVisible.value = true
}

// 删除设备
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该设备吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDevice(row.deviceId)
      if (res.code === 200) {  // 修改为数字类型的 200
        ElMessage.success('删除成功')
        fetchDeviceList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户点击取消按钮时的处理
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    const api = isEdit.value ? updateDevice : addDevice
    const res = await api(deviceForm.value)
    if (res.code === 200) {  // 修改为数字类型的 200
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      dialogVisible.value = false
      fetchDeviceList()
    } else {
      ElMessage.error(res.msg || (isEdit.value ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
  }
}

onMounted(() => {
  fetchDeviceList()
})

const faultReportFormRef = ref(null)

const handleFaultReport = (row) => {
  faultReportFormRef.value.showDialog(row.deviceId)
}
</script>

<style scoped>
.device-container {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

<!-- 添加故障报修表单组件 -->
<fault-report-form ref="faultReportFormRef" @success="fetchDeviceList" />
<template>

  <div>
    <!-- 头部开始 -->
    <div style="height: 60px; background-color: #8686e0; display: flex; align-items: center">
      <div style="width: 200px; display: flex; align-items: center; padding-left: 15px">
        <img width="40px" src="@/assets/logo.png">
        <span style=" font-size: 24px; margin-left: 5px ;color: white">这是系统</span>
      </div>

      <div style="flex: 1"></div>
      <div style="width: fit-content; display: flex; align-items: center; padding-right: 20px">
        <img src="@/assets/user.png" alt="" style="width: 40px" height="40px">
        <span style="color: white; margin-left: 5px">用户名</span>
      </div>
    </div>
    <!-- 头部结束 -->


    <!-- 下面部分开始 -->
    <div style="display: flex; flex-direction: column">
      <!--   顶部导航   -->
      <div>
        <el-menu router :default-active="router.currentRoute.value.path" :default-openeds="['1']" class="el-menu-demo" mode="horizontal">
          <el-menu-item index="/lender/home">
            <el-icon><House /></el-icon>
            系统首页
          </el-menu-item>
          <el-menu-item index="/lender/inspect" disabled>巡检</el-menu-item>
          <el-menu-item index="/lender/maintenance">保养</el-menu-item>
          <el-menu-item index="/lender/test">检测</el-menu-item>
          <el-menu-item index="/lender/device">设备管理</el-menu-item>
        </el-menu>
      </div>

      <!-- 主体区域开始 -->
      <div style="display: flex; justify-content: center; background-color: #f8f8ff; min-height: calc(100vh - 110px)">
        <div style="width: 80%; max-width: 1200px; padding: 20px; background-color: white; margin: 20px; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1)">
          <RouterView />
        </div>
      </div>
      <!-- 主体区域结束 -->

    </div>
    <!-- 下面部分结束 -->

  </div>

</template>


<script setup>
import router from "@/router/index.js";
</script>

<style scoped>
.el-menu .is-active{
  background-color: #e6ecf7;
}
</style>
posted @ 2025-04-22 23:16  QixunQiu  阅读(4)  评论(0)    收藏  举报