package service

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

	"be.ems/src/framework/constants"
	"be.ems/src/framework/database/redis"
	"be.ems/src/modules/ne/model"
	"be.ems/src/modules/ne/repository"
)

// 实例化服务层 NeConfig 结构体
var NewNeConfig = &NeConfig{
	neConfigRepository: repository.NewNeConfig,
}

// NeConfig 网元参数配置可用属性值 服务层处理
type NeConfig struct {
	neConfigRepository *repository.NeConfig // 网元参数配置可用属性值表
}

// RefreshByNeType 通过ne_type刷新redis中的缓存
func (r *NeConfig) RefreshByNeTypeAndNeID(neType string) []model.NeConfig {
	// 多个
	if neType == "" || neType == "*" {
		neConfigList := r.neConfigRepository.Select(model.NeConfig{})
		if len(neConfigList) > 0 {
			neConfigGroup := map[string][]model.NeConfig{}
			for _, v := range neConfigList {
				if item, ok := neConfigGroup[v.NeType]; ok {
					neConfigGroup[v.NeType] = append(item, v)
				} else {
					neConfigGroup[v.NeType] = []model.NeConfig{v}
				}
			}
			for k, v := range neConfigGroup {
				key := fmt.Sprintf("%s:NeConfig:%s", constants.CACHE_NE_DATA, strings.ToUpper(k))
				redis.Del("", key)
				if len(v) > 0 {
					for i, item := range v {
						if err := json.Unmarshal([]byte(item.ParamJson), &item.ParamData); err != nil {
							continue
						}
						v[i] = item
					}
					values, _ := json.Marshal(v)
					redis.Set("", key, string(values), 0)
				}
			}
		}
		return neConfigList
	}
	// 单个
	key := fmt.Sprintf("%s:NeConfig:%s", constants.CACHE_NE_DATA, strings.ToUpper(neType))
	redis.Del("", key)
	neConfigList := r.neConfigRepository.Select(model.NeConfig{
		NeType: neType,
	})
	if len(neConfigList) > 0 {
		for i, v := range neConfigList {
			if err := json.Unmarshal([]byte(v.ParamJson), &v.ParamData); err != nil {
				continue
			}
			neConfigList[i] = v
		}
		values, _ := json.Marshal(neConfigList)
		redis.Set("", key, string(values), 0)
	}
	return neConfigList
}

// ClearNeCacheByNeType 清除网元类型参数配置缓存
func (r *NeConfig) ClearNeCacheByNeType(neType string) bool {
	key := fmt.Sprintf("%s:NeConfig:%s", constants.CACHE_NE_DATA, neType)
	if neType == "*" {
		key = fmt.Sprintf("%s:NeConfig:*", constants.CACHE_NE_DATA)
	}
	keys, err := redis.GetKeys("", key)
	if err != nil {
		return false
	}
	return redis.DelKeys("", keys) == nil
}

// FindByNeType 查询网元类型参数配置
func (r *NeConfig) FindByNeType(neType string) []model.NeConfig {
	var neConfigList []model.NeConfig
	key := fmt.Sprintf("%s:NeConfig:%s", constants.CACHE_NE_DATA, strings.ToUpper(neType))
	jsonStr, _ := redis.Get("", key)
	if len(jsonStr) > 7 {
		err := json.Unmarshal([]byte(jsonStr), &neConfigList)
		if err != nil {
			neConfigList = []model.NeConfig{}
		}
	} else {
		neConfigList = r.RefreshByNeTypeAndNeID(neType)
	}
	return neConfigList
}

// FindByNeTypeAndParamName 查询网元类型参数配置By参数名
func (r *NeConfig) FindByNeTypeAndParamName(neType, paramName string) model.NeConfig {
	neConfigList := r.FindByNeType(neType)
	var neConfig model.NeConfig
	for _, v := range neConfigList {
		if v.ParamName == paramName {
			neConfig = v
			break
		}
	}
	return neConfig
}

// FindByPage 分页查询列表数据
func (r *NeConfig) FindByPage(query map[string]string) ([]model.NeConfig, int64) {
	return r.neConfigRepository.SelectByPage(query)
}

// Find 查询列表
func (r *NeConfig) Find(param model.NeConfig) []model.NeConfig {
	return r.neConfigRepository.Select(param)
}

// FindById 通过ID查询
func (r *NeConfig) FindById(id int64) model.NeConfig {
	if id <= 0 {
		return model.NeConfig{}
	}
	neHosts := r.neConfigRepository.SelectByIds([]int64{id})
	if len(neHosts) > 0 {
		return neHosts[0]
	}
	return model.NeConfig{}
}

// Insert 新增信息
func (r *NeConfig) Insert(param model.NeConfig) int64 {
	return r.neConfigRepository.Insert(param)
}

// Update 修改信息
func (r *NeConfig) Update(param model.NeConfig) int64 {
	return r.neConfigRepository.Update(param)
}

// DeleteByIds 批量删除信息
func (r *NeConfig) DeleteByIds(ids []int64) (int64, error) {
	// 检查是否存在
	data := r.neConfigRepository.SelectByIds(ids)
	if len(data) <= 0 {
		return 0, fmt.Errorf("param.noData")
	}

	if len(data) == len(ids) {
		rows := r.neConfigRepository.DeleteByIds(ids)
		return rows, nil
	}
	// 删除信息失败！
	return 0, fmt.Errorf("delete fail")
}
