package devices

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"server/dao/devices"
	"server/global"
	"server/model/common/request"
	"server/model/common/response"
	model "server/model/devices"
	"server/utils"
)

type RadarApi struct{}

func (radarApi *RadarApi) RadarList(c *gin.Context) {
	var pageInfo request.PageInfo
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(pageInfo, utils.PageInfoVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := RadarService.GetRadarInfoList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

func (radarApi *RadarApi) UpdateRadar(c *gin.Context) {
	var r model.ReqRadar
	err := c.ShouldBindJSON(&r)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(r, utils.IdVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	radar := devices.Radar{
		ID:             r.ID,
		RadarName:      r.RadarName,
		RadarCode:      r.RadarCode,
		RadarBrand:     r.RadarBrand,
		RadarModel:     r.RadarModel,
		DetectionRange: r.DetectionRange,
		IPAddress:      r.IpAddress,
		InstallTime:    r.InstallTime,
		Shunt:          r.Shunt,
		ShuntDescribe:  r.ShuntDescribe,
		GatewayId:      r.GatewayID,
	}
	err = RadarService.UpdateRadar(radar)
	if err != nil {
		global.GVA_LOG.Error("设置失败!", zap.Error(err))
		response.FailWithMessage("设置失败", c)
		return
	}
	response.OkWithMessage("设置成功", c)
}

func (radarApi *RadarApi) AddRadar(c *gin.Context) {
	var r model.ReqRadar
	err := c.ShouldBindJSON(&r)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	radar := devices.Radar{
		RadarName:      r.RadarName,
		RadarCode:      r.RadarCode,
		RadarBrand:     r.RadarBrand,
		RadarModel:     r.RadarModel,
		DetectionRange: r.DetectionRange,
		IPAddress:      r.IpAddress,
		InstallTime:    r.InstallTime,
		Shunt:          r.Shunt,
		ShuntDescribe:  r.ShuntDescribe,
		GatewayId:      r.GatewayID,
	}
	err = RadarService.AddRadar(radar)
	if err != nil {
		global.GVA_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("添加成功", c)
}

func (radarApi *RadarApi) DelRadar(c *gin.Context) {
	var reqId request.GetById
	err := c.ShouldBindJSON(&reqId)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(reqId, utils.IdVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	err = RadarService.DelRadar(reqId.ID)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
		return
	}
	response.OkWithMessage("删除成功", c)
}
