package utils

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"
)

// CheckFormula 检测计算公式是否异常
func CheckFormula(formula string) map[string]string {
	mathFormula := []string{"MAX", "MIN", "ABS", "ACOS", "ASIN", "CEIL", "MOD", "POW", "ROUND", "SIGN", "SIN", "TAN", "LOG10", "LOG2", "LOG", "LN", "EXP"}

	str := strings.ToUpper(formula)
	for _, v := range mathFormula {
		str = strings.Replace(str, v, "", -1)
	}
	str = strings.Replace(str, "(", "", -1)
	str = strings.Replace(str, ")", "", -1)

	byteMap := make(map[string]string)
	for i := 0; i < len(str); i++ {
		byteInt := str[i]
		if byteInt >= 65 && byteInt <= 90 {
			byteStr := string(byteInt)
			if _, ok := byteMap[byteStr]; !ok {
				byteMap[byteStr] = byteStr
			}
		}
	}
	return byteMap
}

type FormulaListItem struct {
	Formula string `json:"f"`
	Date    string `json:"d"`
}

// HandleFormulaJson 处理计算公式json串是否异常
func HandleFormulaJson(formula string, startDate string) (dateSlice []string, formulaMap map[string]string, err error) {
	list := make([]FormulaListItem, 0)
	err = json.Unmarshal([]byte(formula), &list)
	if err != nil {
		err = fmt.Errorf("公式串解析失败： json.Unmarshal Err: %v", err)
		return
	}
	formulaMap = make(map[string]string)
	dateSlice = make([]string, 0)
	// 日期排序
	for k, v := range list {
		if k == 0 { // 首个日期均为起始日
			v.Date = startDate
		}
		formulaMap[v.Date] = v.Formula
		dateSlice = append(dateSlice, v.Date)
	}
	sort.Slice(dateSlice, func(i, j int) bool {
		return dateSlice[i] > dateSlice[j]
	})

	return
}

// CheckFormulaJson 检测计算公式json串是否异常
func CheckFormulaJson(formula string) (formulaSlice []string, err error) {
	list := make([]FormulaListItem, 0)
	err = json.Unmarshal([]byte(formula), &list)
	if err != nil {
		err = fmt.Errorf("公式串解析失败： json.Unmarshal Err: %v", err)
		return
	}
	formulaSlice = make([]string, 0)
	// 日期排序
	for _, v := range list {
		formulaSlice = append(formulaSlice, v.Formula)
	}
	return
}
