package service

import (
	"fmt"
	"iot_manager_service/app/system/dao"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/logger"

	"strconv"
)

// 字典管理服务
var DictService = new(dictService)

type dictService struct{}

const (
	//ControlType    = "control_type" => ControlType    = "operation_his_type" 2022/12/31 17:18
	ControlType    = "operation_his_type"
	ModuleType     = "module_his_type"
	Sex            = "sex"
	ResolutionType = "resolution_type"

	SexNameKey        = "%d:sys:sex_name:%d"
	ModuleTypeKey     = "%d:dict:module_type:%d"
	ControlTypeKey    = "%d:dict:control_type:%d"
	ResolutionTypeKey = "%d:dict:resolution_type:%d"
)

func (s *dictService) GetCacheDict(redisKey, code string, dictId int) string {
	var name string
	name, err := cache.Redis.Get(redisKey).Result()
	if err != nil {
		dict := &dao.Dict{Code: code, DictKey: strconv.Itoa(dictId)}
		if err := dict.GetByCodeAndKey(); err != nil {
			logger.Logger.Errorf("GetByCodeAndKey err = %d \n", err)
		} else {
			name = dict.DictValue
			cache.Redis.Set(redisKey, name, -1)
		}
	}
	return name
}

func (s *dictService) GetByCode(code string) ([]dao.Dict, error) {
	dict := &dao.Dict{Code: code}
	return dict.GetByCode()
}

func (s *dictService) GetControlType(tenantId string, id int) string {
	return s.GetCacheDict(fmt.Sprintf(ControlTypeKey, tenantId, id), ControlType, id)
}

func (s *dictService) GetModuleName(tenantId string, id int) string {
	return s.GetCacheDict(fmt.Sprintf(ModuleTypeKey, tenantId, id), ModuleType, id)
}

func (s *dictService) GetSexName(tenantId string, id int) string {
	return s.GetCacheDict(fmt.Sprintf(SexNameKey, tenantId, id), Sex, id)
}

func (s *dictService) GetResolutionName(tenantId string, id int) string {
	return s.GetCacheDict(fmt.Sprintf(ResolutionTypeKey, tenantId, id), ResolutionType, id)
}
