package device import ( "encoding/json" "errors" "fmt" "strconv" "strings" "time" "git.huangwc.com/pig/pig-farm-controller/internal/app/controller" "git.huangwc.com/pig/pig-farm-controller/internal/infra/logs" "git.huangwc.com/pig/pig-farm-controller/internal/infra/models" "git.huangwc.com/pig/pig-farm-controller/internal/infra/repository" "github.com/gin-gonic/gin" "gorm.io/gorm" ) // Controller 设备控制器,封装了所有与设备相关的业务逻辑 type Controller struct { repo repository.DeviceRepository logger *logs.Logger } // NewController 创建一个新的设备控制器实例 func NewController(repo repository.DeviceRepository, logger *logs.Logger) *Controller { return &Controller{ repo: repo, logger: logger, } } // --- Request DTOs --- // CreateDeviceRequest 定义了创建设备时需要传入的参数 type CreateDeviceRequest struct { Name string `json:"name" binding:"required"` DeviceTemplateID uint `json:"device_template_id" binding:"required"` AreaControllerID uint `json:"area_controller_id" binding:"required"` Location string `json:"location,omitempty"` Properties map[string]interface{} `json:"properties,omitempty"` } // UpdateDeviceRequest 定义了更新设备时需要传入的参数 type UpdateDeviceRequest struct { Name string `json:"name" binding:"required"` DeviceTemplateID uint `json:"device_template_id" binding:"required"` AreaControllerID uint `json:"area_controller_id" binding:"required"` Location string `json:"location,omitempty"` Properties map[string]interface{} `json:"properties,omitempty"` } // --- Response DTOs --- // DeviceResponse 定义了返回给客户端的单个设备信息的结构 type DeviceResponse struct { ID uint `json:"id"` Name string `json:"name"` DeviceTemplateID uint `json:"device_template_id"` DeviceTemplateName string `json:"device_template_name"` AreaControllerID uint `json:"area_controller_id"` AreaControllerName string `json:"area_controller_name"` Location string `json:"location"` Properties map[string]interface{} `json:"properties"` CreatedAt string `json:"created_at"` UpdatedAt string `json:"updated_at"` } // --- DTO 转换函数 --- // newDeviceResponse 从数据库模型创建一个新的设备响应 DTO func newDeviceResponse(device *models.Device) (*DeviceResponse, error) { if device == nil { return nil, nil } var props map[string]interface{} if len(device.Properties) > 0 && string(device.Properties) != "null" { if err := device.ParseProperties(&props); err != nil { return nil, fmt.Errorf("解析设备属性失败 (ID: %d): %w", device.ID, err) } } // 确保 DeviceTemplate 和 AreaController 已预加载 deviceTemplateName := "" if device.DeviceTemplate.ID != 0 { deviceTemplateName = device.DeviceTemplate.Name } areaControllerName := "" if device.AreaController.ID != 0 { areaControllerName = device.AreaController.Name } return &DeviceResponse{ ID: device.ID, Name: device.Name, DeviceTemplateID: device.DeviceTemplateID, DeviceTemplateName: deviceTemplateName, AreaControllerID: device.AreaControllerID, AreaControllerName: areaControllerName, Location: device.Location, Properties: props, CreatedAt: device.CreatedAt.Format(time.RFC3339), UpdatedAt: device.UpdatedAt.Format(time.RFC3339), }, nil } // newListDeviceResponse 从数据库模型切片创建一个新的设备列表响应 DTO 切片 func newListDeviceResponse(devices []*models.Device) ([]*DeviceResponse, error) { list := make([]*DeviceResponse, 0, len(devices)) for _, device := range devices { resp, err := newDeviceResponse(device) if err != nil { return nil, err } list = append(list, resp) } return list, nil } // --- Controller Methods --- // CreateDevice godoc // @Summary 创建新设备 // @Description 根据提供的信息创建一个新设备 // @Tags 设备管理 // @Accept json // @Produce json // @Param device body CreateDeviceRequest true "设备信息" // @Success 200 {object} controller.Response{data=DeviceResponse} // @Router /api/v1/devices [post] func (c *Controller) CreateDevice(ctx *gin.Context) { const actionType = "创建设备" var req CreateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } propertiesJSON, err := json.Marshal(req.Properties) if err != nil { c.logger.Errorf("%s: 序列化属性失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", actionType, "属性序列化失败", req.Properties) return } device := &models.Device{ Name: req.Name, DeviceTemplateID: req.DeviceTemplateID, AreaControllerID: req.AreaControllerID, Location: req.Location, Properties: propertiesJSON, } // 在创建设备前进行自检 // 注意:这里的 SelfCheck 依赖于 DeviceTemplate 和 AreaController 字段, // 但在创建时这些关联对象可能尚未完全加载。如果 SelfCheck 内部需要这些关联对象, // 则需要在调用 SelfCheck 之前手动加载或调整 SelfCheck 逻辑。 // 目前假设 SelfCheck 仅检查 ID 和 Properties。 if err := device.SelfCheck(); err != nil { c.logger.Errorf("%s: 设备属性自检失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求: "+err.Error(), actionType, "设备属性自检失败", device) return } if err := c.repo.Create(device); err != nil { c.logger.Errorf("%s: 数据库操作失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建设备失败: "+err.Error(), actionType, "数据库创建失败", device) return } // 为了在响应中包含 DeviceTemplateName 和 AreaControllerName,需要重新从数据库加载设备,并预加载关联。 createdDevice, err := c.repo.FindByID(device.ID) if err != nil { c.logger.Errorf("%s: 重新加载创建的设备失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备创建成功,但重新加载设备失败", actionType, "重新加载设备失败", device) return } resp, err := newDeviceResponse(createdDevice) if err != nil { c.logger.Errorf("%s: 序列化响应失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备创建成功,但响应生成失败", actionType, "响应序列化失败", createdDevice) return } c.logger.Infof("%s: 设备创建成功, ID: %d", actionType, device.ID) controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "设备创建成功", resp, actionType, "设备创建成功", resp) } // GetDevice godoc // @Summary 获取设备信息 // @Description 根据设备ID获取单个设备的详细信息 // @Tags 设备管理 // @Produce json // @Param id path string true "设备ID" // @Success 200 {object} controller.Response{data=DeviceResponse} // @Router /api/v1/devices/{id} [get] func (c *Controller) GetDevice(ctx *gin.Context) { const actionType = "获取设备" deviceID := ctx.Param("id") if deviceID == "" { c.logger.Errorf("%s: 设备ID为空", actionType) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备ID不能为空", actionType, "设备ID为空", nil) return } // 假设 FindByIDString 方法会预加载 DeviceTemplate 和 AreaController device, err := c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { c.logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { c.logger.Errorf("%s: 设备ID格式错误: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), actionType, "设备ID格式错误", deviceID) return } c.logger.Errorf("%s: 数据库查询失败: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: "+err.Error(), actionType, "数据库查询失败", deviceID) return } resp, err := newDeviceResponse(device) if err != nil { c.logger.Errorf("%s: 序列化响应失败: %v, Device: %+v", actionType, err, device) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备信息失败: 内部数据格式错误", actionType, "响应序列化失败", device) return } c.logger.Infof("%s: 获取设备信息成功, ID: %d", actionType, device.ID) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备信息成功", resp, actionType, "获取设备信息成功", resp) } // ListDevices godoc // @Summary 获取设备列表 // @Description 获取系统中所有设备的列表 // @Tags 设备管理 // @Produce json // @Success 200 {object} controller.Response{data=[]DeviceResponse} // @Router /api/v1/devices [get] func (c *Controller) ListDevices(ctx *gin.Context) { const actionType = "获取设备列表" // 假设 ListAll 方法会预加载 DeviceTemplate 和 AreaController devices, err := c.repo.ListAll() if err != nil { c.logger.Errorf("%s: 数据库查询失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: "+err.Error(), actionType, "数据库查询失败", nil) return } resp, err := newListDeviceResponse(devices) if err != nil { c.logger.Errorf("%s: 序列化响应失败: %v, Devices: %+v", actionType, err, devices) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取设备列表失败: 内部数据格式错误", actionType, "响应序列化失败", devices) return } c.logger.Infof("%s: 获取设备列表成功, 数量: %d", actionType, len(devices)) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取设备列表成功", resp, actionType, "获取设备列表成功", resp) } // UpdateDevice godoc // @Summary 更新设备信息 // @Description 根据设备ID更新一个已存在的设备信息 // @Tags 设备管理 // @Accept json // @Produce json // @Param id path string true "设备ID" // @Param device body UpdateDeviceRequest true "要更新的设备信息" // @Success 200 {object} controller.Response{data=DeviceResponse} // @Router /api/v1/devices/{id} [put] func (c *Controller) UpdateDevice(ctx *gin.Context) { const actionType = "更新设备" deviceID := ctx.Param("id") // 1. 检查设备是否存在 // 假设 FindByIDString 方法会预加载 DeviceTemplate 和 AreaController existingDevice, err := c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { c.logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } if strings.Contains(err.Error(), "无效的设备ID格式") { c.logger.Errorf("%s: 设备ID格式错误: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, err.Error(), actionType, "设备ID格式错误", deviceID) return } c.logger.Errorf("%s: 数据库查询失败: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败: "+err.Error(), actionType, "数据库查询失败", deviceID) return } // 2. 绑定请求参数 var req UpdateDeviceRequest if err := ctx.ShouldBindJSON(&req); err != nil { c.logger.Errorf("%s: 参数绑定失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req) return } propertiesJSON, err := json.Marshal(req.Properties) if err != nil { c.logger.Errorf("%s: 序列化属性失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "属性字段格式错误", actionType, "属性序列化失败", req.Properties) return } // 3. 更新从数据库中查出的现有设备对象的字段 existingDevice.Name = req.Name existingDevice.DeviceTemplateID = req.DeviceTemplateID existingDevice.AreaControllerID = req.AreaControllerID existingDevice.Location = req.Location existingDevice.Properties = propertiesJSON // 在更新设备前进行自检 // 注意:这里的 SelfCheck 依赖于 DeviceTemplate 和 AreaController 字段, // 但在更新时这些关联对象可能尚未完全加载。如果 SelfCheck 内部需要这些关联对象, // 则需要在调用 SelfCheck 之前手动加载或调整 SelfCheck 逻辑。 // 目前假设 SelfCheck 仅检查 ID 和 Properties。 if err := existingDevice.SelfCheck(); err != nil { c.logger.Errorf("%s: 设备属性自检失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "设备属性不符合要求: "+err.Error(), actionType, "设备属性自检失败", existingDevice) return } // 4. 将修改后的 existingDevice 对象保存回数据库 if err := c.repo.Update(existingDevice); err != nil { c.logger.Errorf("%s: 数据库更新失败: %v, Device: %+v", actionType, err, existingDevice) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新设备失败: "+err.Error(), actionType, "数据库更新失败", existingDevice) return } // 为了在响应中包含 DeviceTemplateName 和 AreaControllerName,需要重新从数据库加载设备,并预加载关联。 updatedDevice, err := c.repo.FindByID(existingDevice.ID) if err != nil { c.logger.Errorf("%s: 重新加载更新的设备失败: %v", actionType, err) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备更新成功,但重新加载设备失败", actionType, "重新加载设备失败", existingDevice) return } resp, err := newDeviceResponse(updatedDevice) if err != nil { c.logger.Errorf("%s: 序列化响应失败: %v, Device: %+v", actionType, err, updatedDevice) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "设备更新成功,但响应生成失败", actionType, "响应序列化失败", updatedDevice) return } c.logger.Infof("%s: 设备更新成功, ID: %d", actionType, existingDevice.ID) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备更新成功", resp, actionType, "设备更新成功", resp) } // DeleteDevice godoc // @Summary 删除设备 // @Description 根据设备ID删除一个设备(软删除) // @Tags 设备管理 // @Produce json // @Param id path string true "设备ID" // @Success 200 {object} controller.Response // @Router /api/v1/devices/{id} [delete] func (c *Controller) DeleteDevice(ctx *gin.Context) { const actionType = "删除设备" deviceID := ctx.Param("id") // 我们需要先将字符串ID转换为uint,因为Delete方法需要uint类型 idUint, err := strconv.ParseUint(deviceID, 10, 64) if err != nil { c.logger.Errorf("%s: 设备ID格式错误: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的设备ID格式", actionType, "设备ID格式错误", deviceID) return } // 检查设备是否存在(可选,但通常在删除前会检查) _, err = c.repo.FindByIDString(deviceID) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { c.logger.Warnf("%s: 设备不存在, ID: %s", actionType, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeNotFound, "设备未找到", actionType, "设备不存在", deviceID) return } c.logger.Errorf("%s: 查找设备失败: %v, ID: %s", actionType, err, deviceID) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败: 查找设备时发生内部错误", actionType, "数据库查询失败", deviceID) return } if err := c.repo.Delete(uint(idUint)); err != nil { c.logger.Errorf("%s: 数据库删除失败: %v, ID: %d", actionType, err, idUint) controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除设备失败: "+err.Error(), actionType, "数据库删除失败", deviceID) return } c.logger.Infof("%s: 设备删除成功, ID: %d", actionType, idUint) controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "设备删除成功", nil, actionType, "设备删除成功", deviceID) }