diff --git a/structs/utils/calculate-process.go b/structs/utils/calculate-process.go new file mode 100644 index 0000000..5890c0e --- /dev/null +++ b/structs/utils/calculate-process.go @@ -0,0 +1,39 @@ +package utils + +import ( + "strings" + + v2 "gitea.timerzz.com/kedaya_haitao/common/structs/v2" +) + +func CalculateProviderPrice(calculates []v2.CalculateProcess, env map[string]int) (p v2.ProviderPrice) { + var calculateStrings = make([]string, 0, len(calculates)) + for _, c := range calculates { + process, price := c.Run(env) + if process != "" { + calculateStrings = append(calculateStrings, process) + if p.FinalPrice == 0 { + p.FinalPrice = price + } + p.FinalPrice = min(p.FinalPrice, price) + } + } + p.CalMark = strings.Join(calculateStrings, "\n") + return +} + +func CalculateSellerPrice(calculates []v2.CalculateProcess, env map[string]int) (p v2.SellerPrice) { + var calculateStrings = make([]string, 0, len(calculates)) + for _, c := range calculates { + process, price := c.Run(env) + if process != "" { + calculateStrings = append(calculateStrings, process) + if p.FinalPrice == 0 { + p.FinalPrice = price + } + p.FinalPrice = min(p.FinalPrice, price) + } + } + p.CalMark = strings.Join(calculateStrings, "\n") + return +} diff --git a/structs/v2/calculate-process.go b/structs/v2/calculate-process.go index 43708cf..ce89eb8 100644 --- a/structs/v2/calculate-process.go +++ b/structs/v2/calculate-process.go @@ -1,7 +1,11 @@ package v2 import ( + "fmt" + "strings" "time" + + "github.com/expr-lang/expr" ) type CalculateProcess struct { @@ -19,3 +23,34 @@ type CalculateProcess struct { // 名称 Name string `json:"name"` } + +// 计算过程 +func (c *CalculateProcess) Run(env map[string]int) (string, int) { + if c.Condition != "" { + condition, err := expr.Compile(c.Condition, expr.AsBool()) + if err != nil { + return fmt.Sprintf("【%s】 condition compile error: %v", c.Name, err), 0 + } + if ok, err := expr.Run(condition, env); err != nil { + return fmt.Sprintf("【%s】 condition run error: %v", c.Name, err), 0 + } else if !ok.(bool) { + return "", 0 + } + } + program, err := expr.Compile(c.Process, expr.AsInt()) + if err != nil { + return fmt.Sprintf("【%s】 process compile error: %v", c.Name, err), 0 + } + + output, err := expr.Run(program, env) + if err != nil { + return fmt.Sprintf("【%s】 process run error: %v", c.Name, err), 0 + } + var replaceList = make([]string, 0, 2*len(env)) + for k, v := range env { + replaceList = append(replaceList, k, fmt.Sprintf("%.2f", float64(v/100))) + } + replacer := strings.NewReplacer(replaceList...) + var resp = output.(int) + return replacer.Replace(fmt.Sprintf("【%s】 %s = %.2f", c.Name, c.Process, float64(resp/100))), resp +}