package api

import (
	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	"main/database"
	"main/model"
	"main/utils"
	"strings"
)

func getSysIcons(ctx iris.Context) {
	var icons []model.SysIcons
	db := database.GetInstance().GetMysqlDb()
	if err := db.Find(&icons).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", icons))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func addSysIcons(ctx iris.Context) {
	var params sysIconsParam
	var icons []model.SysIcons
	var sysIcons []model.SysIcons
	err := ctx.ReadJSON(&params)
	if utils.ErrHandle(ctx, err) {
		return
	}
	db := database.GetInstance().GetMysqlDb()
	if err1 := db.Find(&sysIcons).Error; err1 != nil {
		logrus.Errorln("sql执行失败：", err1)
	}
	for _, iconStr := range strings.Split(params.Icons, ",") {
		icon := strings.Join([]string{"bi", iconStr}, "-")
		if !checkIconExist(icon, sysIcons) {
			icons = append(icons, model.SysIcons{Icon: icon})
			sysIcons = append(sysIcons, model.SysIcons{Icon: icon})
		}
	}
	if err1 := db.Create(&icons).Error; err1 != nil {
		logrus.Errorln("sql执行失败：", err1)
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func checkIconExist(icon string, sysIcons []model.SysIcons) bool {
	for _, sysIcon := range sysIcons {
		if sysIcon.Icon == icon {
			return true
		}
	}
	return false
}
