package admin

import (
	"github.com/gin-gonic/gin"
	"server/dao"
	"server/model/common/request"
	"server/model/common/response"
	"server/utils/logger"
	"strconv"
)

type DeviceApi struct{}

func (da *DeviceApi) QueryAllDevices(c *gin.Context) {
	devices, err := deviceService.QueryAllDevices()
	if err != nil {
		logger.Get().Error("QueryAllDevices ---- " + err.Error())
		response.FailWithMessage("设备获取设备", c)
		return
	}
	response.OkWithData(devices, c)
}

func (da *DeviceApi) QueryDeviceList(c *gin.Context) {
	var info request.DeviceSearch
	err := c.ShouldBindJSON(&info)
	if err != nil {
		logger.Get().Error("QueryDeviceList ---- " + err.Error())
		response.FailWithMessage("参数解析失败", c)
		return
	}
	list, total, err := deviceService.QueryDeviceList(info)
	if err != nil {
		logger.Get().Error("QueryDeviceList ---- " + err.Error())
		response.FailWithMessage("设备获取列表错误", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     info.PageInfo.Page,
		PageSize: info.PageInfo.PageSize,
	}, "获取成功", c)
}

func (da *DeviceApi) CreateDevice(c *gin.Context) {
	var device dao.Device
	err := c.ShouldBindJSON(&device)
	if err != nil {
		logger.Get().Error("CreateDevice ---- " + err.Error())
		response.FailWithMessage("参数解析失败", c)
		return
	}
	err = deviceService.CreateDevice(device)
	if err != nil {
		logger.Get().Error("CreateDevice ---- " + err.Error())
		response.FailWithMessage("设备创建失败", c)
		return
	}
	response.OkWithMessage("创建成功", c)
}

func (da *DeviceApi) UpdateDevice(c *gin.Context) {
	var device dao.Device
	err := c.ShouldBindJSON(&device)
	if err != nil {
		logger.Get().Error("UpdateDevice ---- " + err.Error())
		response.FailWithMessage("参数解析失败", c)
		return
	}
	err = deviceService.UpdateDevice(device)
	if err != nil {
		logger.Get().Error("UpdateDevice ---- " + err.Error())
		response.FailWithMessage("设备更新失败", c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

func (da *DeviceApi) DeleteDevice(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		logger.Get().Error("DeleteDevice ---- " + err.Error())
		response.FailWithMessage("参数错误", c)
		return
	}
	err = deviceService.DeleteDevice(id)
	if err != nil {
		logger.Get().Error("DeleteDevice ---- " + err.Error())
		response.FailWithMessage("设备删除失败", c)
		return
	}
	response.OkWithMessage("删除成功", c)
}
