package admin

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

type RegionApi struct{}

func (ra *RegionApi) QueryAllRegions(c *gin.Context) {
	regions, err := regionService.QueryAllRegions()
	if err != nil {
		logger.Get().Error("QueryAllRegions ---- " + err.Error())
		response.FailWithMessage("获取地区失败", c)
		return
	}
	response.OkWithData(regions, c)
}

func (ra *RegionApi) CreateRegion(c *gin.Context) {
	var region dao.Region
	if err := c.ShouldBindJSON(&region); err != nil {
		logger.Get().Error("CreateRegions ---- " + err.Error())
		response.FailWithMessage("参数解析失败", c)
		return
	}
	err := regionService.CreateRegion(region)
	if err != nil {
		logger.Get().Error("CreateRegions ---- " + err.Error())
		response.FailWithMessage("创建地区失败", c)
		return
	}
	response.OkWithMessage("创建地区成功", c)
}

func (ra *RegionApi) UpdateRegion(c *gin.Context) {
	var region dao.Region
	if err := c.ShouldBindJSON(&region); err != nil {
		logger.Get().Error("UpdateRegions ---- " + err.Error())
		response.FailWithMessage("参数解析失败", c)
		return
	}
	err := regionService.UpdateRegion(region)
	if err != nil {
		logger.Get().Error("UpdateRegions ---- " + err.Error())
		response.FailWithMessage("更新地区失败", c)
		return
	}
	response.OkWithMessage("更新地区成功", c)
}

func (ra *RegionApi) DeleteRegion(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		logger.Get().Error("DeleteRegions ---- " + err.Error())
		response.FailWithMessage("参数错误", c)
		return
	}
	err = regionService.DeleteRegion(id)
	if err != nil {
		logger.Get().Error("DeleteRegions ---- " + err.Error())
		response.FailWithMessage("删除地区失败", c)
		return
	}
	response.OkWithMessage("删除地区成功", c)
}
