package hdl

import (
	"applet/app/utils"
	"fmt"
	"github.com/gin-gonic/gin"

	"applet/app/e"
	"applet/app/md"
	"applet/app/svc"
)

// 文件七牛云回调确认
func FileImgCallback(c *gin.Context) {
	masterID := c.Query("master_id")
	c.Set("mid", masterID)
	var args md.FileCallback
	err := c.ShouldBindJSON(&args)
	utils.FilePutContents("qiniuyun", masterID)

	if err != nil {
		utils.FilePutContents("qiniuyun", utils.SerializeStr(err))
		fmt.Println("七牛云上传回调参数错误：>>>>>>>>>>", err)
		e.OutErr(c, 200, e.ERR_INVALID_ARGS)
		return
	}
	fmt.Println("七牛云上传回调参数：>>>>>>>>>>", utils.SerializeStr(args))
	if err = svc.FileSave(c, &args); err != nil {
		utils.FilePutContents("qiniuyun", utils.SerializeStr(err))

		fmt.Println("七牛云上传回调保存文件错误：>>>>>>>>>>", err)
		e.OutErr(c, 200, err)
		return
	}

	res := map[string]interface{}{
		"name":     args.FileName,
		"fname":    getFileNameURL(c, args.FileName),
		"fsize":    args.FileSize,
		"provider": args.Provider,
		"uid":      args.Uid,
		"dir_id":   args.DirId,
		"w":        args.Width,
		"h":        args.Height,
	}
	e.OutSuc(c, &res, nil)
}

func getFileNameURL(c *gin.Context, filename string) string {
	protocol := svc.SysCfgGet(c, "file_bucket_scheme")
	domain := svc.SysCfgGet(c, "file_bucket_host")
	imgformat := svc.SysCfgGet(c, "file_avatar_thumbnail")
	if protocol != "" && domain != "" && imgformat != "" {
		return protocol + "://" + domain + "/" + filename
	}
	return filename
}
