package dashboard

import (
	"cs-agent/internal/builders"
	"cs-agent/internal/pkg/constants"
	"cs-agent/internal/pkg/dto/request"
	"cs-agent/internal/pkg/dto/response"
	"cs-agent/internal/pkg/enums"
	"cs-agent/internal/pkg/httpx"
	"cs-agent/internal/services"
	"strings"

	"cs-agent/internal/pkg/httpx/params"

	"github.com/gin-gonic/gin"
	"github.com/mlogclub/simple/web"
)

func AssetAnyList(ctx *gin.Context) {
	if _, err := services.AuthService.RequirePermission(ctx, constants.PermissionAssetView); err != nil {
		httpx.WriteJSON(ctx, err)
		return
	}

	cnd := params.NewPagedSqlCnd(ctx,
		params.QueryFilter{ParamName: "provider"},
		params.QueryFilter{ParamName: "status"},
		params.QueryFilter{ParamName: "createUserId"},
		params.QueryFilter{ParamName: "filename", Op: params.Like},
	).Desc("id")
	if strings.TrimSpace(ctx.Query("status")) == "" {
		cnd = cnd.Eq("status", enums.AssetStatusSuccess)
	}

	list, paging := services.AssetService.FindPageByCnd(cnd)
	results := make([]response.AssetResponse, 0, len(list))
	for _, item := range list {
		results = append(results, builders.BuildAsset(&item))
	}
	httpx.WriteJSON(ctx, &web.PageResult{Results: results, Page: paging})
	return
}

func AssetGetBy(ctx *gin.Context, id int64) {
	if _, err := services.AuthService.RequirePermission(ctx, constants.PermissionAssetView); err != nil {
		httpx.WriteJSON(ctx, err)
		return
	}
	item := services.AssetService.Get(id)
	if item == nil {
		httpx.WriteJSON(ctx, web.JsonErrorMsg("文件不存在"))
		return
	}
	httpx.WriteJSON(ctx, builders.BuildAsset(item))
	return
}

func AssetPostCreate(ctx *gin.Context) {
	operator, err := services.AuthService.RequirePermission(ctx, constants.PermissionAssetCreate)
	if err != nil {
		httpx.WriteJSON(ctx, err)
		return
	}

	req := request.CreateAssetRequest{}
	if err := params.ReadForm(ctx, &req); err != nil {
		httpx.WriteJSON(ctx, err)
		return
	}
	header, err := ctx.FormFile("file")
	if err != nil {
		httpx.WriteJSON(ctx, web.JsonErrorMsg("请选择上传文件"))
		return
	}
	item, err := services.AssetService.UploadFile(header, req.Prefix, operator)
	if err != nil {
		httpx.WriteJSON(ctx, err)
		return
	}
	httpx.WriteJSON(ctx, builders.BuildAsset(item))
	return
}

func AssetPostDelete(ctx *gin.Context) {
	operator, err := services.AuthService.RequirePermission(ctx, constants.PermissionAssetDelete)
	if err != nil {
		httpx.WriteJSON(ctx, err)
		return
	}

	req := request.DeleteAssetRequest{}
	if err := params.ReadJSON(ctx, &req); err != nil {
		httpx.WriteJSON(ctx, err)
		return
	}
	if err := services.AssetService.DeleteAsset(req.ID, operator); err != nil {
		httpx.WriteJSON(ctx, err)
		return
	}
	httpx.WriteJSON(ctx, nil)
	return
}
