package utils

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

// CheckFormula 检测计算公式是否异常
func CheckFormula(formula string) (byteMap map[string]string, err error) {
	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 {
			// 判断前一位是否是数字，如果是数字就报错
			if i > 0 {
				if str[i-1] >= '0' && str[i-1] <= '9' {
					err = fmt.Errorf("计算公式异常，请检查公式：%s", formula)
					return
				}
			}
			byteStr := string(byteInt) //获取计算公式中的占位符A，B, AA，AB
			if i+1 < len(str) {
				next := str[i+1]
				if next >= 65 && next <= 90 {
					byteStr += string(next)
					i++
				}
			}
			if _, ok := byteMap[byteStr]; !ok {
				byteMap[byteStr] = byteStr
			}
		}
	}
	return
}

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

// HandleFormulaJson 处理计算公式json串是否异常
func HandleFormulaJson(formula string, endDate time.Time) (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)
	// 查找最后的一天作为首个公式的起始日期
	maxDate := endDate.AddDate(0, 0, 1).Format(FormatDate)
	// 日期排序
	for k, v := range list {
		if k == 0 { // 首个日期均为起始日
			v.Date = maxDate
		}
		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
}
