package sysconfig

import (
	"fmt"
	"net/http"
	"strings"

	"nms_nbi/features/sys_config/model"
	"nms_nbi/features/sys_config/service"
	"nms_nbi/lib/core/utils/ctx"
	"nms_nbi/lib/core/utils/parse"
	"nms_nbi/lib/core/vo/result"
	"nms_nbi/lib/midware"
	"nms_nbi/lib/services"
	"nms_nbi/restagent/config"
)

// 参数配置信息接口添加到路由
func Routers() []services.RouterItem {
	// 实例化控制层 SysConfigApi 结构体
	var apis = &SysConfigApi{
		sysConfigService: service.NewServiceSysConfig,
	}

	rs := [...]services.RouterItem{
		{
			Method:     "GET",
			Pattern:    "/configs",
			Handler:    apis.List,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "GET",
			Pattern:    "/config/{configId}",
			Handler:    apis.Info,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "POST",
			Pattern:    "/config",
			Handler:    apis.Add,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "PUT",
			Pattern:    "/config",
			Handler:    apis.Edit,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "DELETE",
			Pattern:    "/config/{configIds}",
			Handler:    apis.Remove,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "PUT",
			Pattern:    "/config/refreshCache",
			Handler:    apis.RefreshCache,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "GET",
			Pattern:    "/config/configKey/{configKey}",
			Handler:    apis.ConfigKey,
			Middleware: midware.Authorize(nil),
		},
		// 添加更多的 Router 对象...
	}

	// 生成两组前缀路由
	rsPrefix := []services.RouterItem{}
	for _, v := range rs {
		path := "/configManage/{apiVersion}" + v.Pattern
		// 固定前缀
		v.Pattern = config.DefaultUriPrefix + path
		rsPrefix = append(rsPrefix, v)
		// 可配置
		v.Pattern = config.UriPrefix + path
		rsPrefix = append(rsPrefix, v)
	}
	return rsPrefix
}

// 参数配置信息
//
// PATH /configManage
type SysConfigApi struct {
	// 参数配置服务
	sysConfigService *service.ServiceSysConfig
}

// 参数配置列表
//
// GET /list
func (s *SysConfigApi) List(w http.ResponseWriter, r *http.Request) {
	querys := ctx.QueryMap(r)
	data := s.sysConfigService.SelectConfigPage(querys)
	ctx.JSON(w, 200, result.Ok(data))
}

// 参数配置信息
//
// GET /:configId
func (s *SysConfigApi) Info(w http.ResponseWriter, r *http.Request) {
	configId := ctx.Param(r, "configId")
	if configId == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	data := s.sysConfigService.SelectConfigById(configId)
	if data.ConfigID == configId {
		ctx.JSON(w, 200, result.OkData(data))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 参数配置新增
//
// POST /
func (s *SysConfigApi) Add(w http.ResponseWriter, r *http.Request) {
	var body model.SysConfig
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.ConfigID != "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查属性值唯一
	uniqueConfigKey := s.sysConfigService.CheckUniqueConfigKey(body.ConfigKey, "")
	if !uniqueConfigKey {
		msg := fmt.Sprintf("[%s] Parameter key name already exists", body.ConfigKey)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	body.CreateBy = ctx.LoginUserToUserName(r)
	insertId := s.sysConfigService.InsertConfig(body)
	if insertId != "" {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 参数配置修改
//
// PUT /
func (s *SysConfigApi) Edit(w http.ResponseWriter, r *http.Request) {
	var body model.SysConfig
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.ConfigID == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查属性值唯一
	uniqueConfigKey := s.sysConfigService.CheckUniqueConfigKey(body.ConfigKey, body.ConfigID)
	if !uniqueConfigKey {
		msg := fmt.Sprintf("[%s] Parameter key name already exists", body.ConfigKey)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	// 检查是否存在
	config := s.sysConfigService.SelectConfigById(body.ConfigID)
	if config.ConfigID != body.ConfigID {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access parameter configuration data!"))
		return
	}

	body.UpdateBy = ctx.LoginUserToUserName(r)
	rows := s.sysConfigService.UpdateConfig(body)
	if rows > 0 {
		ctx.JSON(w, 200, result.Ok(nil))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 参数配置删除
//
// DELETE /:configIds
func (s *SysConfigApi) Remove(w http.ResponseWriter, r *http.Request) {
	configIds := ctx.Param(r, "configIds")
	if configIds == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(configIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		ctx.JSON(w, 200, result.Err(nil))
		return
	}
	rows, err := s.sysConfigService.DeleteConfigByIds(uniqueIDs)
	if err != nil {
		ctx.JSON(w, 200, result.ErrMsg(err.Error()))
		return
	}
	msg := fmt.Sprintf("删除成功：%d", rows)
	ctx.JSON(w, 200, result.OkMsg(msg))
}

// 参数配置刷新缓存
//
// PUT /refreshCache
func (s *SysConfigApi) RefreshCache(w http.ResponseWriter, r *http.Request) {
	s.sysConfigService.ResetConfigCache()
	ctx.JSON(w, 200, result.Ok(nil))
}

// 参数配置根据参数键名
//
// GET /configKey/:configKey
func (s *SysConfigApi) ConfigKey(w http.ResponseWriter, r *http.Request) {
	configKey := ctx.Param(r, "configKey")
	if configKey == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	key := s.sysConfigService.SelectConfigValueByKey(configKey)
	if key != "" {
		ctx.JSON(w, 200, result.OkData(key))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}
