package controllers

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/utils"
	"fmt"
	"html"
	"strconv"
	"strings"
	"time"
)

// BusinessConfController 商家配置
type BusinessConfController struct {
	BaseAuthController
}

type BusinessConfOpenController struct {
	BaseCommonController
}

// Save
// @Title 保存配置
// @Description 保存配置
// @Param	request	body map[string]interface{} true "type json string"
// @Success 200 Ret=200 操作成功
// @router /save [post]
func (this *BusinessConfController) Save() {
	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
	}
	var req map[string]interface{}
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}

	// 获取配置信息
	confOb := new(models.BusinessConf)
	list, e := confOb.GetItemsByCondition("", make([]interface{}, 0), []string{}, "")
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "获取配置列表失败, Err: " + e.Error()
		return
	}
	confMap := make(map[string]*models.BusinessConf)
	for _, c := range list {
		confMap[c.ConfKey] = c
	}

	// 根据配置类型取值
	updates := make([]models.BusinessConfUpdate, 0)
	for k, v := range req {
		// 过滤掉表中没有的key
		conf := confMap[k]
		if conf == nil {
			continue
		}

		switch conf.ValType {
		case 1: // 字符串
			str, ok := v.(string)
			if !ok {
				continue
			}
			str = strings.TrimSpace(str)
			if conf.Necessary == 1 && str == "" {
				br.Msg = conf.Remark + "不可为空"
				return
			}
			updates = append(updates, models.BusinessConfUpdate{
				ConfKey: k,
				ConfVal: str,
			})
		case 2: // 数值
			num, ok := v.(float64)
			if !ok {
				continue
			}
			if conf.Necessary == 1 && num <= 0 {
				br.Msg = conf.Remark + "不可为空"
				return
			}
			val := strconv.FormatFloat(num, 'f', 0, 64)
			updates = append(updates, models.BusinessConfUpdate{
				ConfKey: k,
				ConfVal: val,
			})
		case 3: // 字符串数组
			arr, ok := v.([]interface{})
			if !ok {
				continue
			}
			if conf.Necessary == 1 && len(arr) == 0 {
				br.Msg = conf.Remark + "不可为空"
				return
			}
			strArr := make([]string, 0)
			for _, a := range arr {
				if s, ok2 := a.(string); ok2 {
					strArr = append(strArr, s)
				}
			}
			val := strings.Join(strArr, ",")
			updates = append(updates, models.BusinessConfUpdate{
				ConfKey: k,
				ConfVal: val,
			})
		case 4: // 富文本
			content, ok := v.(string)
			if !ok {
				continue
			}
			content = strings.TrimSpace(content)
			if conf.Necessary == 1 && content == "" {
				br.Msg = conf.Remark + "不可为空"
				return
			}
			content = html.EscapeString(content)
			updates = append(updates, models.BusinessConfUpdate{
				ConfKey: k,
				ConfVal: content,
			})
		}
	}

	if len(updates) > 0 {
		if e = models.UpdateBusinessConfMulti(updates); e != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存商家配置失败, Err: " + e.Error()
			return
		}
	}

	// 操作日志
	go func() {
		b, e := json.Marshal(req)
		if e != nil {
			return
		}
		recordOb := new(models.BusinessConfOperationRecord)
		recordOb.SysUserId = sysUser.AdminId
		recordOb.SysRealName = sysUser.RealName
		recordOb.Content = string(b)
		recordOb.CreateTime = time.Now().Local()
		_ = recordOb.Create()
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Fetch
// @Title 获取配置
// @Description 获取配置
// @Success 200 Ret=200 获取成功
// @router /fetch [get]
func (this *BusinessConfController) Fetch() {
	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
	}

	list, e := models.GetBusinessConf()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取商家配置失败, Err: " + e.Error()
		return
	}

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

// CodeEncrypt
// @Title 商家编码加密
// @Description 商家编码加密
// @Success 200 Ret=200 获取成功
// @router /code_encrypt [get]
func (this *BusinessConfOpenController) CodeEncrypt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()

	res := ""
	if utils.BusinessCode != "" {
		res = utils.MD5(fmt.Sprintf("%s%s", utils.BusinessCode, utils.BusinessCodeSalt))
	}

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