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"
	"time"
)

type IntersectApi struct{}

func (i *IntersectApi) PublicIntersect(c *gin.Context) {
	list, err := IntersectService.PublicIntersect()
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(gin.H{"pubIntersect": list}, "获取成功", c)
}

func (i *IntersectApi) AddIntersect(c *gin.Context) {
	var reqi model.ReqIntersect
	err := c.ShouldBindJSON(&reqi)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	intersect := devices.Intersect{
		IntersectName: reqi.IntersectName,
		Address:       reqi.Address,
		IntersectType: reqi.IntersectType,
		CreateTime:    time.Now(),
	}
	err = IntersectService.AddIntersect(intersect)
	if err != nil {
		global.GVA_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("添加成功", c)
}

func (i *IntersectApi) UpdateIntersect(c *gin.Context) {
	var reqi model.ReqIntersect
	err := c.ShouldBindJSON(&reqi)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(reqi, utils.IdVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	intersect := devices.Intersect{
		ID:            reqi.ID,
		IntersectName: reqi.IntersectName,
		Address:       reqi.Address,
		IntersectType: reqi.IntersectType,
	}
	err = IntersectService.UpdateIntersect(intersect)
	if err != nil {
		global.GVA_LOG.Error("设置失败!", zap.Error(err))
		response.FailWithMessage("设置失败", c)
		return
	}
	response.OkWithMessage("设置成功", c)
}

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

func (i *IntersectApi) IntersectList(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 := IntersectService.GetIntersectInfoList(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)
}
