package controllers

import (
	"encoding/json"
	"hongze/hongze_open_api/models/request/admin"
	adminTable "hongze/hongze_open_api/models/tables/admin"
	"hongze/hongze_open_api/utils"
	"time"
)

// Admin
// 系统用户模块
type Admin struct {
	BaseAuth
}

// Create
// @Title 创建系统用户
// @Description 创建系统用户
// @Param	request	body admin.CreateUserReq true "type json string"
// @Success 200 创建成功
// @router /create [post]
func (c *Admin) Create() {
	//appid权限校验
	appid := c.GetString("appid", "")
	if utils.RunMode == "release" && appid != "CQWx3EqDLNk7bVHo" {
		c.FailWithMessage("无权限")
		return
	}
	var req admin.CreateUserReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.FailWithMessage("参数解析异常")
		return
	}

	roleType, ok := utils.RoleTypeMap[req.RoleType]
	if !ok {
		c.FailWithMessage("角色类型异常")
		return
	}
	mobile := utils.TrimStr(req.Mobile)
	if mobile == `` {
		c.FailWithMessage("手机号必传")
		return
	}
	realName := utils.TrimStr(req.RealName)
	if realName == `` {
		c.FailWithMessage("真实姓名必传")
		return
	}
	//校验该用户是否存在系统中
	count, err := adminTable.GetSysAdminCountByMobile(mobile)
	if count > 0 {
		c.FailWithMessage("该手机号已存在系统中")
		return
	}

	passWord := `123456a`
	//pwdByte, err := base64.StdEncoding.DecodeString(passWord)
	//if err != nil {
	//	fmt.Println("err:",err)
	//	c.FailWithMessage("解析数据失败")
	//	return
	//}
	//pwdStr := string(pwdByte)
	//pwdStr = strings.ToLower(pwdStr)

	adminInfo := &adminTable.Admin{
		//AdminId:                 0,
		AdminName: mobile,
		RealName:  realName,
		Password:  utils.MD5(passWord),
		//LastUpdatedPasswordTime: time.Now().Format(utils.FormatDateTime),
		Enabled: 0,
		Email:   "",
		//LastLoginTime:           time.Now().Format(utils.FormatDateTime),
		CreatedTime: time.Now(),
		//LastUpdatedTime:         time.Now().Format(utils.FormatDateTime),
		Role:           roleType.Role,
		Mobile:         mobile,
		RoleType:       0,
		RoleId:         roleType.RoleId,
		RoleName:       roleType.RoleName,
		RoleTypeCode:   roleType.RoleTypeCode,
		DepartmentId:   roleType.DepartmentId,
		DepartmentName: roleType.DepartmentName,
		GroupId:        roleType.GroupId,
		GroupName:      roleType.GroupName,
		Authority:      0,
		Position:       "",
	}
	err = adminTable.AddAdmin(adminInfo)
	if err != nil {
		c.OkWithMessage("创建失败")
		return
	}

	// 清除用户列表缓存key
	_ = utils.Rc.Delete(utils.CACHE_KEY_ADMIN)

	c.OkWithMessage("创建成功")
}