package controller

import (
	"github.com/gin-gonic/gin"
	"iot_manager_service/app/middleware"
	"iot_manager_service/app/operation/service"
	"iot_manager_service/util/common"
	"net/http"
	"strconv"
	"time"
)

var Environment = new(environmentCtl)

type environmentCtl struct{}

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

	records, err := service.EnvironmentService.EnvironmentList(claims.TenantId)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, records))
}

func (c *environmentCtl) GetData(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Query("id"))
	records, err := service.EnvironmentService.Get(id)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, records))
}

func (c *environmentCtl) GetHistoryData(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Query("id"))
	scope := ctx.Query("scope")
	queryType, _ := strconv.Atoi(ctx.Query("type"))
	startTimeStr := ctx.Query("startTime")
	endTimeStr := ctx.Query("endTime")

	start := time.Time{}
	end := time.Time{}
	if startTimeStr != "" && endTimeStr != "" {
		startTime, err := time.Parse("2006-01-02 15:03:04", startTimeStr)
		if err != nil {
			ctx.JSON(http.StatusOK, common.ParamsInvalidResponse("startTime invalid", nil))
			return
		}
		start = startTime
		endTime, err := time.Parse("2006-01-02 15:03:04", endTimeStr)
		if err != nil {
			ctx.JSON(http.StatusOK, common.ParamsInvalidResponse("endTime invalid", nil))
			return
		}
		end = endTime
	}
	records, err := service.EnvironmentService.GetHistoryData(id, scope, queryType, start, end)
	if err != nil {
		ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, records))
}

func (c *environmentCtl) GetScopeList(ctx *gin.Context) {
	//hour 使用 EnvironmentData 小时数据
	//day 使用 EnvironmentDataSummary 天数据
	id, _ := strconv.Atoi(ctx.Query("id"))
	scope := ctx.Query("scope")
	queryType, _ := strconv.Atoi(ctx.Query("type"))
	records, err := service.EnvironmentService.GetScopeData(id, scope, queryType)
	if err != nil {
		ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
		return
	}
	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, records))
}
