package user

import (
	"errors"
	"net/http"
	"spaceofcheng/services/controllers"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/models/system"
	"spaceofcheng/services/service"
	"spaceofcheng/services/utils"
	"time"
)

// UserController 用户
type UserController struct {
	dao *service.UserServ
	controllers.BaseController
}

// Constructor 初始化 Controller
// @Title Constructor
// @Description 初始化 Controller, 系统自动调用
func (c *UserController) Constructor() {
	c.dao = service.NewUserServ(c.Context)
}

// UpdatePassword 更新用户密码
func (c *UserController) UpdatePassword() {
	oriPasswd := c.GetString("oriPasswd")
	newPasswd := c.GetString("newPasswd")

	user := c.Context.Get("user").(model.SysUser)
	err := c.dao.UpdatePassword(oriPasswd, newPasswd, &user)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON("ok")
}

// ResetPassword 重置用户密码
func (c *UserController) ResetPassword() {
	userid := c.GetString("userid")
	err := c.dao.ResetPassword(userid)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON("OK")
}

// GetUserByID 获取用户信息
func (c *UserController) GetUserByID() {
	userid := c.GetString(":userid")
	user, err := c.dao.GetUserByID(userid)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(user)
}

// GetUserList 获取用户列表
func (c *UserController) GetUserList() {
	userName := c.GetString("username")
	typeID := c.GetString("typeid")
	caseids := c.GetString("caseid")
	if caseids == "" {
		cases := c.Context.Get("cases").([]model.SysUserCase)
		caseids = c.GetCaseIDs(cases)
	}
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pagesize")
	userList, err := c.dao.GetUserList(userName, typeID, caseids, page, pageSize)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(userList)
}

// GetUserTypes 获取用户类型
func (c *UserController) GetUserTypes() {
	// cases := c.Context.Get("cases").([]model.SysUserCase)
	// caseIDs := c.GetCaseIDs(cases)
	org := c.Context.Get("org").(model.SysOrg)
	usertypes, err := c.dao.GetUserTypes(org.OrgId)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(usertypes)
}

// UserMapping 用户映射
func (c *UserController) UserMapping() {
	userMapping := model.TaUserMapping{}
	if err := c.ParseForm(&userMapping); err != nil {
		c.ResponseError(err)
	}
	err := c.dao.UserMapping(userMapping)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON("操作成功！")
}

// SaveUser 保存用户信息
func (c *UserController) SaveUser() {
	user := system.SysUserForm{}
	if err := c.ParseForm(&user); err != nil {
		c.ResponseError(err)
	}

	info, err := c.dao.SaveUser(user)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(info)
}

// DelUser 删除用户信息
func (c *UserController) DelUser() {
	userid := c.GetString(":userid")
	err := c.dao.DelUser(userid)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON("删除成功！")
}

// UserMapRole 用户角色保存
func (c *UserController) UserMapRole() {
	userid := c.GetString("userid")
	roles := c.GetString("roles")
	err := c.dao.SaveUserRole(userid, roles)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON("操作成功！")
}

// GetUserCustomer 我的推荐客户
func (c *UserController) GetUserCustomer() {
	userid := c.GetString(":userid")
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pagesize")
	customers, err := c.dao.GetUserCustomer(userid, page, pageSize)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(customers)
}

// SignIn 用户登录
func (c *UserController) SignIn() {
	userName := c.GetString("username")
	userPassword := c.GetString("password")
	token := c.GetString("token")
	doRemember, _ := c.GetInt("doremember")

	if token != "" {
		tokenMap, err := utils.PareseToken(token)
		if err != nil {
			utils.LogError("解析用户 token 失败: " + err.Error())

			c.ResponseError(
				errors.New("登录失败, 用户名或者密码不正确"),
				http.StatusBadRequest,
			)
		}

		userName = tokenMap["user"].(string)
		userPassword = tokenMap["password"].(string)
	}

	user, err := c.dao.CheckUserSignIn(userName, userPassword)
	if err != nil {
		utils.LogError("用户登录失败: " + err.Error())
		c.ResponseError(
			errors.New("登录失败, 用户名或者密码不正确"),
			http.StatusBadRequest,
		)
	}

	// 成功之后, 设置 session
	c.SetSession(controllers.SNUserID, user.UserId)

	if token == "" && doRemember != 0 {
		var err error
		token, err = utils.CreateToken(map[string]interface{}{
			"user":     userName,
			"password": userPassword,
			"exp":      time.Now().Local().Add(7 * 24 * time.Hour), // 有效期是 7 天
		})

		if err != nil {
			utils.LogError("生成 用户登录 token 失败: " + err.Error())
		}
	}

	c.ResponseJSON(map[string]interface{}{
		token: token,
	})
}

// SignOut 用户登出
func (c *UserController) SignOut() {
	c.DestroySession()
	c.ResponseJSON("ok")
}

// GetEnvVars 获取当前用户相关
func (c *UserController) GetEnvVars() {
	vars, err := c.dao.GetCurrentEnvVars()
	if err != nil {
		c.ResponseError(
			err,
			http.StatusInternalServerError,
		)
	}

	c.ResponseJSON(vars)
}

// GetUserRole 获取用户角色
func (c *UserController) GetUserRole() {
	userid := c.GetString("userid")
	roles, err := c.dao.GetUserRoles(userid)
	if err != nil {
		c.ResponseError(
			err,
			http.StatusInternalServerError,
		)
	}
	c.ResponseJSON(roles)
}
