package controller

import (
	"fmt"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/modules/ne/model"
	"be.ems/src/modules/ne/service"

	"github.com/gin-gonic/gin"
)

// 实例化控制层 NeSoftwareController 结构体
var NewNeSoftware = &NeSoftwareController{
	neSoftwareService: service.NewNeSoftware,
}

// 网元软件包请求
//
// PATH /software
type NeSoftwareController struct {
	neSoftwareService *service.NeSoftware // 网元软件包服务
}

// 网元软件包列表
//
// GET /list
//
//	@Tags			ne
//	@Accept			json
//	@Produce		json
//	@Param			neType		query		string	false	"NE Type"	Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
//	@Param			name		query		string	false	"Name"
//	@Param			version		query		string	false	"Version"
//	@Param			pageNum		query		number	true	"pageNum"	default(1)
//	@Param			pageSize	query		number	true	"pageSize"	default(10)
//	@Success		200			{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		List of Network Element Software Packages
//	@Description	List of Network Element Software Packages
//	@Router			/ne/software/list [get]
func (s NeSoftwareController) List(c *gin.Context) {
	query := reqctx.QueryMap(c)
	rows, total := s.neSoftwareService.FindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}

// 网元软件包信息
//
// GET /:id
func (s NeSoftwareController) Info(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	id := parse.Number(c.Param("id"))
	if id <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
		return
	}

	neSoftware := s.neSoftwareService.FindById(id)
	if neSoftware.ID != id {
		// 没有可访问网元包信息数据！
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neSoftware.noData")))
		return
	}

	c.JSON(200, resp.OkData(neSoftware))
}

// 网元软件包新增
//
// POST /
//
//	@Tags			ne
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Additions to the Net Element package
//	@Description	Additions to the Net Element package
//	@Router			/ne/software [post]
func (s NeSoftwareController) Add(c *gin.Context) {
	var body model.NeSoftware
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.Path == "" || body.ID > 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: path is empty or id is not empty"))
		return
	}
	// 找到已存在的删除后重新添加
	neSoftwares := s.neSoftwareService.Find(model.NeSoftware{
		NeType:  body.NeType,
		Name:    body.Name,
		Version: body.Version,
	})
	if len(neSoftwares) > 0 {
		neSoftware := neSoftwares[0]
		s.neSoftwareService.DeleteByIds([]int64{neSoftware.ID}, false)
	}

	// 检查属性值唯一
	// uniqueSoftware := s.neSoftwareService.CheckUniqueTypeAndNameAndVersion(body.NeType, body.Name, body.Version, "")
	// if !uniqueSoftware {
	// 	// 网元软件包操作【%s】失败，网元类型与文件名版本已存在
	// 	msg := i18n.TTemplate(language, "neSoftware.errKeyExists", map[string]any{"name": body.Name})
	// 	c.JSON(200, resp.ErrMsg(msg))
	// 	return
	// }

	body.CreateBy = reqctx.LoginUserToUserName(c)
	insertId := s.neSoftwareService.Insert(body)
	if insertId > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 网元软件包修改
//
// PUT /
func (s NeSoftwareController) Edit(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.NeSoftware
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.Path == "" || body.ID == 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: path or id is empty"))
		return
	}

	// 检查属性值唯一
	uniqueSoftware := s.neSoftwareService.CheckUniqueTypeAndNameAndVersion(body.NeType, body.Name, body.Version, body.ID)
	if !uniqueSoftware {
		// 网元软件包操作【%s】失败，网元类型与文件名版本已存在
		msg := i18n.TTemplate(language, "neSoftware.errKeyExists", map[string]any{"name": body.Name})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	// 检查是否存在
	neSoftware := s.neSoftwareService.FindById(body.ID)
	if neSoftware.ID != body.ID {
		// 没有可访问网元包信息数据！
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neSoftware.noData")))
		return
	}

	body.UpdateBy = reqctx.LoginUserToUserName(c)
	rows := s.neSoftwareService.Update(body)
	if rows > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 网元软件包删除
//
// DELETE /:id
func (s NeSoftwareController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	id := c.Param("id")
	if id == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
		return
	}

	// 处理字符转id数组后去重
	uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
	// 转换成int64数组类型
	ids := make([]int64, 0)
	for _, v := range uniqueIDs {
		ids = append(ids, parse.Number(v))
	}

	rows, err := s.neSoftwareService.DeleteByIds(ids, true)
	if err != nil {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
	c.JSON(200, resp.OkMsg(msg))
}

// 网元软件包设为网元新版本
//
// POST /newNeVersion
//
//	@Tags			ne
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Net Element package set to Net Element new version
//	@Description	Net Element package set to Net Element new version
//	@Router			/ne/software/newNeVersion [post]
func (s NeSoftwareController) NewNeVersion(c *gin.Context) {
	var body model.NeSoftware
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	// 找到已存在的软件包信息
	neSoftwares := s.neSoftwareService.Find(model.NeSoftware{
		NeType:  body.NeType,
		Name:    body.Name,
		Version: body.Version,
	})
	if len(neSoftwares) > 0 {
		neSoftware := neSoftwares[0]
		s.neSoftwareService.UpdateVersions(neSoftware, model.NeVersion{
			NeType:   neSoftware.NeType,
			UpdateBy: reqctx.LoginUserToUserName(c),
		})
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}
