package controller

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"

	"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/system/model"
	"be.ems/src/modules/system/service"
)

// NewLoginSource 实例化控制层
var NewSysLoginSource = &SysLoginSourceController{
	sysLoginSourceService: service.NewSysLoginSource,
}

// SysLoginSourceController 认证源管理 控制层处理
//
// PATH /sys/login-source
type SysLoginSourceController struct {
	sysLoginSourceService *service.SysLoginSource // 认证源信息服务
}

// List 列表
//
// GET /list
func (s SysLoginSourceController) List(c *gin.Context) {
	query := reqctx.QueryMap(c)
	rows, total := s.sysLoginSourceService.FindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// Info 信息
//
// GET /:id
func (s SysLoginSourceController) Info(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
		return
	}

	info := s.sysLoginSourceService.FindById(parse.Number(id))
	if info.Id == parse.Number(id) {
		c.JSON(200, resp.OkData(info))
		return
	}
	c.JSON(200, resp.ErrMsg("id does not exist"))
}

// Add 新增
//
// POST /
func (s SysLoginSourceController) Add(c *gin.Context) {
	var body model.SysLoginSource
	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.Id > 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id not is empty"))
		return
	}
	if len(body.Config) < 7 || !json.Valid([]byte(body.Config)) {
		c.JSON(200, resp.ErrMsg("config json format error"))
		return
	}
	configStr, err := s.sysLoginSourceService.CheckConfigJSON(body.Type, body.Config)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	body.Config = configStr

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

// Edit 更新
//
// PUT /
func (s SysLoginSourceController) Edit(c *gin.Context) {
	var body model.SysLoginSource
	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.Id <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
		return
	}
	if len(body.Config) < 7 || !json.Valid([]byte(body.Config)) {
		c.JSON(200, resp.ErrMsg("config json format error"))
		return
	}
	configStr, err := s.sysLoginSourceService.CheckConfigJSON(body.Type, body.Config)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	body.Config = configStr

	// 查询信息
	info := s.sysLoginSourceService.FindById(body.Id)
	if info.Id != body.Id {
		c.JSON(200, resp.ErrMsg("modification failed, data not exist"))
		return
	}

	info.Type = body.Type
	info.Name = body.Name
	info.Icon = body.Icon
	info.Config = body.Config
	info.ActiveFlag = body.ActiveFlag
	info.Remark = body.Remark
	info.UpdateBy = reqctx.LoginUserToUserName(c)
	rowsAffected := s.sysLoginSourceService.Update(info)
	if rowsAffected > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// Remove 删除
//
// DELETE /:id
func (s SysLoginSourceController) 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.sysLoginSourceService.DeleteByIds(ids)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
	c.JSON(200, resp.OkMsg(msg))
}
