package common_utils import ( "gitea.anxinyun.cn/container/common_models" "gitea.anxinyun.cn/container/common_utils/configLoad" "log" "strings" ) type UnitHelper struct { configHelper *ConfigHelper unitsGroup map[string][]common_models.DataUnit } func NewUnitHelper() *UnitHelper { redisAddr := configLoad.LoadConfig().GetString("redis.address") unitHelper := &UnitHelper{ configHelper: NewConfigHelper(redisAddr), unitsGroup: map[string][]common_models.DataUnit{}, } unitHelper.getUnitsGroup() return unitHelper } func NewUnitHelperWithConfig(configHelper *ConfigHelper) *UnitHelper { return &UnitHelper{ configHelper: configHelper, unitsGroup: map[string][]common_models.DataUnit{}, } } func (the *UnitHelper) getUnitsGroup() { dp, err := the.configHelper.GetDataUnit() if err != nil { return } units := map[string][]common_models.DataUnit{} for _, unit := range dp { groupK := unit.Dimension if _, ok := units[groupK]; ok { units[groupK] = append(units[groupK], unit) } else { units[groupK] = []common_models.DataUnit{unit} } } the.unitsGroup = units } func (the *UnitHelper) GetUnitTransK(from, to string) float64 { k := 1.0 from = strings.ToLower(from) to = strings.ToLower(to) if from == to { return k } isTransOk := false //必须同组的才有效 for _, units := range the.unitsGroup { fromObj := struct { isHad bool k float64 }{} toObj := struct { isHad bool k float64 }{} for _, unit := range units { if unit.Name == from { fromObj.isHad = true fromObj.k = unit.Coef } if unit.Name == to { toObj.isHad = true toObj.k = unit.Coef } } if fromObj.isHad && toObj.isHad { k = fromObj.k / toObj.k isTransOk = true break } } if !isTransOk { log.Printf("不支持的单位转换 %s->%s", from, to) } return k }