package controllers

import (
	"encoding/json"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/system"
	"eta/eta_mobile/utils"
	"time"
)

// 系统用户
type SysAdminController struct {
	BaseAuthController
}

// SetConfig
// @Title 用户信息配置接口
// @Description 用户信息配置接口
// @Success 200 {object} system.SetAdminConfigReq
// @router /sysuser/config/set [post]
func (this *SysAdminController) SetConfig() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req system.SetAdminConfigReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	item, err := system.GetConfigDetailByCode(this.SysUser.AdminId, req.ConfigCode)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "设置失败"
			br.ErrMsg = "设置失败，Err:" + err.Error()
			return
		}

		// 获取默认配置
		defaultConfig, err := system.GetDefaultConfigDetailByCode(req.ConfigCode)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "获取默认配置失败，Err:" + err.Error()
			return
		}
		adminConfigItem := &system.AdminConfig{
			//ConfigId:    0,
			AdminId:     this.SysUser.AdminId,
			ConfigCode:  req.ConfigCode,
			ConfigValue: req.ConfigValue,
			Remark:      defaultConfig.Remark,
			CreateTime:  time.Now(),
		}
		err = adminConfigItem.Create()

		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "设置失败，Err:" + err.Error()
			return
		}
	} else {
		// 存在配置，那么就修改
		item.ConfigValue = req.ConfigValue
		err = item.Update([]string{"ConfigValue"})

		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "设置失败，Err:" + err.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "设置成功"
}

// ConfigLanguage
// @Title 用户语言配置
// @Description 用户语言配置
// @Success 200 string "获取成功"
// @router /config/language [get]
func (this *SysAdminController) ConfigLanguage() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	sourceKey := this.GetString("SourceKey")

	language := `CN`
	confDetail, _ := system.GetConfigDetailByCode(sysUser.AdminId, sourceKey)
	if confDetail != nil {
		language = confDetail.ConfigValue
	}

	br.Data = language
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// Detail
// @Title 用户详情信息
// @Description 用户详情信息
// @Param	request	body system.SysuserAddReq true "type json string"
// @Success 200 新增成功
// @router /sysuser/detail [get]
func (this *SysAdminController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	br.Data = this.SysUser
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}