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 GateWayApi struct{}

func (g *GateWayApi) GateWayList(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 := GateWayService.GetGateWayInfoList(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 (g *GateWayApi) AddGateway(c *gin.Context) {
	var w model.ReqGateway
	err := c.ShouldBindJSON(&w)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	gateWay := devices.GateWay{GatewayName: w.GatewayName, IntersectId: w.IntersectId, GatewayCode: w.GatewayCode, GatewayBrand: w.GatewayBrand, GatewayModel: w.GatewayModel, IpAddress: w.IpAddress, InstallTime: w.InstallTime}
	err = GateWayService.AddGateway(gateWay)
	if err != nil {
		global.GVA_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("添加成功", c)
}

func (g *GateWayApi) UpdateGateway(c *gin.Context) {
	var w model.ReqGateway
	err := c.ShouldBindJSON(&w)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(w, utils.IdVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	gateWay := devices.GateWay{ID: w.ID, GatewayName: w.GatewayName, IntersectId: w.IntersectId, GatewayCode: w.GatewayCode, GatewayBrand: w.GatewayBrand, GatewayModel: w.GatewayModel, IpAddress: w.IpAddress, InstallTime: w.InstallTime}
	err = GateWayService.UpdateGateway(gateWay)
	if err != nil {
		global.GVA_LOG.Error("设置失败!", zap.Error(err))
		response.FailWithMessage("设置失败", c)
		return
	}
	response.OkWithMessage("设置成功", c)
}

func (g *GateWayApi) DelGateway(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 = GateWayService.DelGateway(reqId.ID)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

func (g *GateWayApi) PublicGateway(c *gin.Context) {
	list, err := GateWayService.PublicGateway()
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(gin.H{"pubGateway": list}, "获取成功", c)
}
