package controller

import (
	"github.com/gin-gonic/gin"
	"iot_manager_service/app/middleware"
	"iot_manager_service/app/system/dao"
	"iot_manager_service/app/system/model"
	"iot_manager_service/app/system/service"
	"iot_manager_service/util/common"
	"math"
	"net/http"
	"strconv"
)

var Tenant = new(tenant)

type tenant struct{}

func (c *tenant) GetInfo(ctx *gin.Context) {
	domain := ctx.Query("domain")
	tenant, _ := service.TenantService.GetByDomain(domain)
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, tenant))
}

func (c *tenant) GetDetail(ctx *gin.Context) {
	id := ctx.Query("id")
	iId, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	tenant, err := service.TenantService.Get(iId)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, tenant))
}

func (c *tenant) List(ctx *gin.Context) {
	current, _ := strconv.Atoi(ctx.Query("current"))
	size, _ := strconv.Atoi(ctx.Query("size"))
	tId := ctx.Query("tenantId")
	tenantName := ctx.Query("tenantName")
	linkman := ctx.Query("linkman")
	if current == 0 {
		current = 1
	}
	if size <= 0 || size > 100 {
		size = 10
	}

	tenantId := ""
	if tId != "" {
		tenantId = (tId)
	}

	tenants, counts, err := service.TenantService.List(tenantId, tenantName, linkman, current, size)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	pages := math.Ceil(float64(counts) / float64(size))
	rsp := model.RsqTenantList{
		Current: current,
		Size:    size,
		Total:   counts,
		Pages:   int(pages),
		Records: tenants,
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, rsp))
}

func (c *tenant) Submit(ctx *gin.Context) {
	var req dao.Tenant
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	err := service.TenantService.Submit(req)
	ctx.JSON(http.StatusOK, err)
}

func (c *tenant) Remove(ctx *gin.Context) {
	value, _ := ctx.Get(middleware.Authorization)
	claims := value.(*middleware.Claims)

	var req *model.ReqTenantRemove
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
		return
	}
	err := service.TenantService.Remove(claims.UserId, req.IDs)
	ctx.JSON(http.StatusOK, err)
}

func (c *tenant) GetList(ctx *gin.Context) {
	tenants, err := service.TenantService.GetList()
	if err != nil {
		ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, tenants))
}
