package hdl

import (
	"applet/app/e"
	"applet/app/md"
	"applet/app/svc"
	"applet/app/utils"
	"applet/app/utils/logx"
	"github.com/gin-gonic/gin"
)

// 请求上传图片
func ImgReqUpload(c *gin.Context) {
	user := svc.GetUser(c)
	uid := utils.IntToStr(user.Info.Uid)
	// 文件名名称
	var args struct {
		Dir      string `json:"dir"`
		FileName string `json:"file_name"`
		FileSize int64  `json:"file_size"` // 文件大小, 单位byte
	}
	if err := c.ShouldBindJSON(&args); err != nil || args.FileSize < 1 || args.FileName == "" {
		logx.Warn(err)
		e.OutErr(c, e.ERR_INVALID_ARGS)
		return
	}
	scheme := "http"
	if c.Request.TLS != nil {
		scheme = "https"
	}
	// 拼装回调地址
	callbackUrl := scheme + "://" + c.Request.Host + "/api/v1/file/img/callback?master_id=" + c.GetString("mid")
	utils.FilePutContents("qiniuyun", callbackUrl)
	//fmt.Println(callbackUrl)
	// callbackUrl = "http://120.55.83.222/raw.php"
	res, err := svc.ImgReqUpload(c, uid, args.Dir, args.FileName, callbackUrl, args.FileSize)
	if err != nil {
		e.OutErr(c, 400, err)
		return
	}
	my := utils.SerializeStr(res)
	var my1 map[string]interface{}
	utils.Unserialize([]byte(my), &my1)
	if c.GetHeader("Platform") == md.PLATFORM_WX_APPLET || c.GetHeader("Platform") == md.PLATFORM_TIKTOK_APPLET || c.GetHeader("Platform") == md.PLATFORM_TOUTIAO_APPLET || c.GetHeader("Platform") == md.PLATFORM_BAIDU_APPLET || c.GetHeader("Platform") == md.PLATFORM_ALIPAY_APPLET {
		my1["host"] = "https://api.zhiyingos.com/api/v1/proxy/upload" //官方页面才有白名单
	}
	e.OutSuc(c, my1, nil)
}

// 请求上传图片
func ImgReqUploadNoUser(c *gin.Context) {
	// 文件名名称
	var args struct {
		Dir      string `json:"dir"`
		FileName string `json:"file_name"`
		FileSize int64  `json:"file_size"` // 文件大小, 单位byte
	}
	if err := c.ShouldBindJSON(&args); err != nil || args.FileSize < 1 || args.FileName == "" {
		logx.Warn(err)
		e.OutErr(c, e.ERR_INVALID_ARGS)
		return
	}

	scheme := "http"
	if c.Request.TLS != nil {
		scheme = "https"
	}
	// 拼装回调地址
	callbackUrl := scheme + "://" + c.Request.Host + "/api/v1/file/img/callback?master_id=" + c.GetString("mid")
	utils.FilePutContents("qny", callbackUrl)
	//fmt.Println(callbackUrl)
	// callbackUrl = "http://120.55.83.222/raw.php"
	res, err := svc.ImgReqUpload(c, "", args.Dir, args.FileName, callbackUrl, args.FileSize)
	if err != nil {
		e.OutErr(c, 400, err)
		return
	}
	my := utils.SerializeStr(res)
	var my1 map[string]interface{}
	utils.Unserialize([]byte(my), &my1)
	domainApiBase := svc.GetWebSiteDomainInfoOfficial(c, "api")
	if c.GetHeader("Platform") == md.PLATFORM_WX_APPLET || c.GetHeader("Platform") == md.PLATFORM_TIKTOK_APPLET || c.GetHeader("Platform") == md.PLATFORM_TOUTIAO_APPLET || c.GetHeader("Platform") == md.PLATFORM_BAIDU_APPLET || c.GetHeader("Platform") == md.PLATFORM_ALIPAY_APPLET {
		my1["host"] = domainApiBase + "/api/v1/proxy/upload"
	}
	e.OutSuc(c, my1, nil)
}
