package agent

import (
	"errors"
	"net/http"
	"strconv"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/rest/httpx"

	"wechat-api/internal/logic/agent"
	"wechat-api/internal/svc"
)

const (
	defaultMultipartMemory = 32 << 20 // 32 MB
)

// swagger:route post /agent/data/upload agent UploadAgentData
//
// upload agent data | 上传data
//
// upload agent data | 上传data
//
// Responses:
//  200: BaseDataInfo

func UploadAgentDataHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseMultipartForm(defaultMultipartMemory); err != nil {
			httpx.Error(w, err)
			return
		}

		l := agent.NewUploadAgentDataLogic(r.Context(), svcCtx)

		file, header, err := r.FormFile("file")
		agentIds, ok := r.Form["agentId"]

		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		if !ok || len(agentIds) != 1 {
			httpx.ErrorCtx(r.Context(), w, errors.New("agentId cannot be null"))
			return
		}
		if file == nil {
			httpx.ErrorCtx(r.Context(), w, errors.New("upload file cannot be null"))
			return
		}

		//l.Logger.Infof("header=%+v size=%d filename=%v\n", header.Header, header.Size, header.Filename)

		if header.Header.Get("Content-Type") != "text/csv" {
			httpx.ErrorCtx(r.Context(), w, errors.New("file format must be csv"))
			return
		}
		agentId, _ := strconv.Atoi(agentIds[0])

		var req types.UploadDataReq
		if err := httpx.Parse(r, &req, true); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		resp, err := l.UploadAgentData(&req, file, uint64(agentId))

		// 删除临时文件
		_ = r.MultipartForm.RemoveAll()

		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
