package templatefunc

import (
	"encoding/json"
	"fmt"
	"html/template"
	"strconv"
)

func BaseTemplateFunc() template.FuncMap {
	addInt := func(arg1, arg2 int) int {
		return arg1 + arg2
	}
	addFloat := func(arg1, arg2 float64) float64 {
		return arg1 + arg2
	}
	minusInt := func(arg1, arg2 int) int {
		return arg1 - arg2
	}
	minusFloat := func(arg1, arg2 float64) float64 {
		return arg1 - arg2
	}

	return template.FuncMap{
		"addInt":     addInt,
		"addFloat":   addFloat,
		"minusInt":   minusInt,
		"minusFloat": minusFloat,
		"discalc":    DiscountCalculation,
		"safeHTML":   SafeHTML,
		"toJson":     ToJson,
	}
}

// DiscountCalculation 折扣计算，float64
// arg1 原件
// arg2 现价
func DiscountCalculation(arg1, arg2 float64) string {
	f := 1.0 - (arg2)/arg1
	if f < 0 {
		f = f * -1
	}

	return strconv.FormatFloat(f*100, 'f', 0, 64)
	//res := strconv.FormatFloat(f*100, 'f', 0, 64)
	//fmt.Println("=========>", arg1, ",", arg2, ",", res)
	//return res
}

// SafeHTML 将数据转为html输出，而不是文本
func SafeHTML(s string) template.HTML {
	return template.HTML(s)
}

// ToJson 将内容转为json
func ToJson(arg any) string {
	//将arg转换为json字符串
	marshal, err := json.Marshal(arg)
	if err != nil {
		return ""
	}
	fmt.Println("ToJson:", string(marshal))
	return string(marshal)
}
