package sysdicttype

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

	"be.ems/features/sys_dict_type/model"
	sysDictTypeService "be.ems/features/sys_dict_type/service"
	"be.ems/lib/core/utils/ctx"
	"be.ems/lib/core/utils/parse"
	"be.ems/lib/core/vo/result"
	"be.ems/lib/midware"
	"be.ems/lib/services"
	"be.ems/restagent/config"
)

// 字典类型信息接口添加到路由
func Routers() []services.RouterItem {
	// 实例化控制层 SysDictTypeApi 结构体
	var apis = &SysDictTypeApi{
		sysDictTypeService: *sysDictTypeService.NewServiceSysDictType,
	}

	rs := [...]services.RouterItem{
		{
			Method:     "GET",
			Pattern:    "/dictTypes",
			Handler:    apis.List,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "GET",
			Pattern:    "/dictType/{dictId}",
			Handler:    apis.Info,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "POST",
			Pattern:    "/dictType",
			Handler:    apis.Add,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "PUT",
			Pattern:    "/dictType",
			Handler:    apis.Edit,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "DELETE",
			Pattern:    "/dictType/{dictIds}",
			Handler:    apis.Remove,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "PUT",
			Pattern:    "/dictType/refreshCache",
			Handler:    apis.RefreshCache,
			Middleware: midware.Authorize(nil),
		},
		{
			Method:     "GET",
			Pattern:    "/dictTypes/optionselect",
			Handler:    apis.DictOptionselect,
			Middleware: midware.Authorize(nil),
		},
		// 添加更多的 Router 对象...
	}

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

// 字典类型信息
//
// PATH /dictTypegManage
type SysDictTypeApi struct {
	// 字典类型服务
	sysDictTypeService sysDictTypeService.ServiceSysDictType
}

// 字典类型列表
//
// GET /list
func (s *SysDictTypeApi) List(w http.ResponseWriter, r *http.Request) {
	querys := ctx.QueryMap(r)
	data := s.sysDictTypeService.SelectDictTypePage(querys)
	ctx.JSON(w, 200, result.Ok(data))
}

// 字典类型信息
//
// GET /:dictId
func (s *SysDictTypeApi) Info(w http.ResponseWriter, r *http.Request) {
	dictId := ctx.Param(r, "dictId")
	if dictId == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	data := s.sysDictTypeService.SelectDictTypeByID(dictId)
	if data.DictID == dictId {
		ctx.JSON(w, 200, result.OkData(data))
		return
	}
	ctx.JSON(w, 200, result.Err(nil))
}

// 字典类型新增
//
// POST /
func (s *SysDictTypeApi) Add(w http.ResponseWriter, r *http.Request) {
	var body model.SysDictType
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.DictID != "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查字典名称唯一
	uniqueDictName := s.sysDictTypeService.CheckUniqueDictName(body.DictName, "")
	if !uniqueDictName {
		msg := fmt.Sprintf("Failed to add dictionary '%s', dictionary name already exists", body.DictName)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	// 检查字典类型唯一
	uniqueDictType := s.sysDictTypeService.CheckUniqueDictType(body.DictType, "")
	if !uniqueDictType {
		msg := fmt.Sprintf("Failed to add dictionary '%s', dictionary type already exists", body.DictType)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

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

// 字典类型修改
//
// PUT /
func (s *SysDictTypeApi) Edit(w http.ResponseWriter, r *http.Request) {
	var body model.SysDictType
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.DictID == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查数据是否存在
	dictInfo := s.sysDictTypeService.SelectDictTypeByID(body.DictID)
	if dictInfo.DictID != body.DictID {
		ctx.JSON(w, 200, result.ErrMsg("No permission to access dictionary type data!"))
		return
	}

	// 检查字典名称唯一
	uniqueDictName := s.sysDictTypeService.CheckUniqueDictName(body.DictName, body.DictID)
	if !uniqueDictName {
		msg := fmt.Sprintf("Dictionary modification failed for [%s], dictionary name already exists", body.DictName)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

	// 检查字典类型唯一
	uniqueDictType := s.sysDictTypeService.CheckUniqueDictType(body.DictType, body.DictID)
	if !uniqueDictType {
		msg := fmt.Sprintf("Dictionary modification failed for [%s], dictionary type already exists", body.DictType)
		ctx.JSON(w, 200, result.ErrMsg(msg))
		return
	}

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

// 字典类型删除
//
// DELETE /:dictIds
func (s *SysDictTypeApi) Remove(w http.ResponseWriter, r *http.Request) {
	dictIds := ctx.Param(r, "dictIds")
	if dictIds == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(dictIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		ctx.JSON(w, 200, result.Err(nil))
		return
	}
	rows, err := s.sysDictTypeService.DeleteDictTypeByIDs(uniqueIDs)
	if err != nil {
		ctx.JSON(w, 200, result.ErrMsg(err.Error()))
		return
	}
	msg := fmt.Sprintf("Successfully deleted: %d", rows)
	ctx.JSON(w, 200, result.OkMsg(msg))
}

// 字典类型刷新缓存
//
// PUT /refreshCache
func (s *SysDictTypeApi) RefreshCache(w http.ResponseWriter, r *http.Request) {
	s.sysDictTypeService.ResetDictCache()
	ctx.JSON(w, 200, result.Ok(nil))
}

// 字典类型选择框列表
//
// GET /getDictOptionselect
func (s *SysDictTypeApi) DictOptionselect(w http.ResponseWriter, r *http.Request) {
	data := s.sysDictTypeService.SelectDictTypeList(model.SysDictType{
		Status: "1",
	})

	type labelValue struct {
		Label string `json:"label"`
		Value string `json:"value"`
	}

	// 数据组
	arr := []labelValue{}
	for _, v := range data {
		arr = append(arr, labelValue{
			Label: v.DictName,
			Value: v.DictType,
		})
	}
	ctx.JSON(w, 200, result.OkData(arr))
}
