package svc

import (
	"applet/app/utils"
	"fmt"
	"github.com/syyongx/php2go"
	"strings"

	"github.com/gin-gonic/gin"
)

// ImageFormat is 格式化 图片
func ImageFormat(c *gin.Context, name string) string {
	if strings.Contains(name, "https:") || strings.Contains(name, "http:") {
		return name
	}
	scheme := SysCfgGet(c, "file_bucket_scheme")
	domain := SysCfgGet(c, "file_bucket_host")
	name, _ = php2go.URLDecode(name)
	name = php2go.URLEncode(name)
	return fmt.Sprintf("%s://%s/%s", scheme, domain, name)
}

// OffImageFormat is 格式化官方 图片
func OffImageFormat(c *gin.Context, name string) string {
	if strings.Contains(name, "https:") || strings.Contains(name, "http:") {
		return name
	}
	name, _ = php2go.URLDecode(name)
	name = php2go.URLEncode(name)

	return fmt.Sprintf("%s://%s/%s", "http", "ossn.izhim.net", name)
}

// ImageBucket is 获取域名
func ImageBucket(c *gin.Context) (string, string) {
	return SysCfgGet(c, "file_bucket_scheme"), SysCfgGet(c, "file_bucket_host")
}

// ImageFormatWithBucket is 格式化成oss 域名
func ImageFormatWithBucket(scheme, domain, name string) string {
	if strings.Contains(name, "http") || name == "" {
		return name
	}
	name, _ = php2go.URLDecode(name)
	name = php2go.URLEncode(name)
	return fmt.Sprintf("%s://%s/%s", scheme, domain, name)
}

// ImageBucketNew is 获取域名
func ImageBucketNew(c *gin.Context) (string, string, string, map[string]string) {
	var list = make(map[string]string, 0)
	for i := 1; i < 10; i++ {
		keys := "file_bucket_sub_host" + utils.IntToStr(i)
		list[keys] = SysCfgGet(c, keys)
	}
	return SysCfgGet(c, "file_bucket_scheme"), SysCfgGet(c, "file_bucket_host"), SysCfgGet(c, "file_bucket_sub_host"), list
}

// ImageFormatWithBucket is 格式化成oss 域名
func ImageFormatWithBucketNew(scheme, domain, subDomain string, moreSubDomain map[string]string, name string) string {
	if strings.Contains(name, "http") {
		return name
	}
	if strings.Contains(name, "{{subhost}}") && subDomain != "" { //读副域名  有可能是其他平台的
		domain = subDomain
	}
	//为了兼容一些客户自营商城导到不同系统 并且七牛云不一样
	for i := 1; i < 10; i++ {
		keys := "file_bucket_sub_host" + utils.IntToStr(i)
		if strings.Contains(name, "{{subhost"+utils.IntToStr(i)+"}}") && moreSubDomain[keys] != "" {
			domain = moreSubDomain[keys]
		}
		name = strings.ReplaceAll(name, "{{subhost"+utils.IntToStr(i)+"}}", "")
	}
	name = strings.ReplaceAll(name, "{{host}}", "")
	name = strings.ReplaceAll(name, "{{subhost}}", "")
	name, _ = php2go.URLDecode(name)
	name = php2go.URLEncode(name)
	return fmt.Sprintf("%s://%s/%s", scheme, domain, name)
}
