package admin

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

func getSysSettings(ctx iris.Context) {
	var res []resSysSettings
	var resSysSettingsData []model.SysSettings
	var currentList []string
	name := ctx.Params().GetString("name")
	for _, sysSetting := range utils.SysSettings {
		if sysSetting.DType == "option" {
			sysSetting.Name = strings.Split(sysSetting.Name, ":")[0]
		}
		if (name != "" && sysSetting.Name != name) || utils.CheckListItem(currentList, sysSetting.Name) {
			continue
		} else {
			resSysSettingsData = nil
			for _, v := range utils.SysSettings {
				if strings.Split(v.Name, ":")[0] == sysSetting.Name {
					resSysSettingsData = append(resSysSettingsData, v)
				}
			}
			currentList = append(currentList, sysSetting.Name)
			res = append(res, resSysSettings{Name: sysSetting.Name, Data: resSysSettingsData})
		}
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func addSysSettings(ctx iris.Context) {
	var params model.SysSettings
	err := ctx.ReadJSON(&params)
	if utils.ErrHandle(ctx, err) {
		return
	}
	db := database.GetInstance().GetMysqlDb()
	if !checkExist(params) {
		if err1 := db.Create(&params).Error; err1 != nil {
			logrus.Errorln("sql执行失败：", err1)
		}
		utils.UpdateSysSettings()
	}
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func delSettings(ctx iris.Context) {
	var params model.SysSettings
	err := ctx.ReadJSON(&params)
	if utils.ErrHandle(ctx, err) {
		return
	}
	db := database.GetInstance().GetMysqlDb()
	if err1 := db.Delete(&params).Error; err1 != nil {
		logrus.Errorln("sql执行失败：", err1)
	}
	utils.UpdateSysSettings()
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func updateSettings(ctx iris.Context) {
	var params model.SysSettings
	err := ctx.ReadJSON(&params)
	if utils.ErrHandle(ctx, err) {
		return
	}
	if !checkExist(params) {
		if utils.ErrHandle(ctx, errors.New("配置信息不存在")) {
			return
		}
	}
	db := database.GetInstance().GetMysqlDb()
	if err1 := db.Save(&params).Error; err1 != nil {
		logrus.Errorln("sql执行失败：", err1)
	}
	utils.UpdateSysSettings()
	err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
	if utils.ErrHandle(ctx, err) {
		return
	}
}

func checkExist(setting model.SysSettings) bool {
	for _, sysSetting := range utils.SysSettings {
		if setting.Name == sysSetting.Name && setting.Value == sysSetting.Value {
			return true
		}
	}
	return false
}
