package controllers

import (
	"encoding/json"
	"eta/eta_mini_crm_ht/models"
	"fmt"
)

type SysConfigController struct {
	BaseAuthController
}

type Config struct {
	ConfigId   int
	ConfigType string
	Json       bool
}

const (
	ConfigTypeInt  = "int"
	ConfigTypeStr  = "string"
	ConfigTypeByte = "byte"
)
const (
	// configCode
	PaymentWayCode = "paymentWay"
)

// SysConfigMap 用于存储错误码和错误信息的映射
var SysConfigMap = map[string]*Config{
	PaymentWayCode: {ConfigId: 1003, ConfigType: ConfigTypeStr, Json: true},
}

func GetConfig(code string) *Config {
	return SysConfigMap[code]
}

// GetConfig
// @Title 系统用户详情信息
// @Description 用户详情信息
// @Param   SysUserId   query   int  true       "系统用户id"
// @Success 200 {object} models.LoginResp
// @router /config [get]
func (this *SysConfigController) GetConfig() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	ConfigKey := this.GetString("ConfigKey")

	if ConfigKey == "" {
		br.Msg = "系统参数错误"
		br.ErrMsg = fmt.Sprintf("系统参数错误 <%d>", ConfigKey)
		return
	}
	configMap := SysConfigMap[ConfigKey]
	configId := configMap.ConfigId
	if configId == 0 {
		br.Msg = "系统参数错误"
		br.ErrMsg = fmt.Sprintf("系统参数错误,系统配置不存在")
		return
	}
	config, err := models.GetConfig(configId)
	if err != nil {
		br.Msg = "系统参数获取失败"
		br.ErrMsg = "系统参数获取失败,Err" + err.Error()
		return
	}
	var value interface{}
	switch config.ConfigType {
	case ConfigTypeInt:
		value = config.ByteValue
	case ConfigTypeByte:
		value = config.IntValue
	case ConfigTypeStr:
		if configMap.Json {
			var jsonMap map[string]interface{}
			err = json.Unmarshal([]byte(config.StrValue), &jsonMap)
			value = jsonMap
		} else {
			value = config.StrValue
		}

	}

	br.Data = value
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}