package controllers

import (
	"encoding/base64"
	"encoding/json"
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/models/request"
	"eta/eta_mini_crm_ht/models/response"
	"eta/eta_mini_crm_ht/services"
	"eta/eta_mini_crm_ht/utils"
	"fmt"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
)

type SysUserController struct {
	BaseAuthController
}

// Add
// @Title 系统用户添加
// @Description 系统用户添加
// @Param	request	body request.UserLoginReq true "type json string"
// @Success 200 {object} models.LoginResp
// @router /add [post]
func (this *SysUserController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.SysUserInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SysUserName == "" {
		br.Msg = "请输入账号"
		return
	}
	if req.Password == "" {
		br.Msg = "请输入密码"
		return
	}
	if req.RealName == "" {
		br.Msg = "请输入姓名"
		return
	}
	// 手机号和邮箱必填一个
	req.Phone = strings.TrimSpace(req.Phone)
	req.Email = strings.TrimSpace(req.Email)
	if req.Phone == "" && req.Email == "" {
		br.Msg = "至少输入一个手机号或邮箱"
		return
	}
	if req.Phone != "" {
		if req.AreaCode == "86" {
			if !utils.ValidateMobileFormatat(req.Phone) {
				br.Msg = "手机号格式有误, 请检查"
				return
			}
		}
	}
	if req.Email != "" {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "邮箱格式有误, 请检查"
			return
		}
	}
	if req.SysDepartmentId <= 0 {
		br.Msg = "请选择部门"
		return
	}
	_, err = models.GetSysDepartmentById(req.SysDepartmentId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "所选部门不存在"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取部门数据失败，Err:" + err.Error()
		return
	}

	sysRole, err := models.GetSysRoleById(req.SysRoleId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "所选角色不存在"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取角色数据失败，Err:" + err.Error()
		return
	}

	// 校验系统用户的密码
	var pwd string
	{
		pwdByte, err := base64.StdEncoding.DecodeString(req.Password)
		if err != nil {
			br.Msg = "解析数据失败"
			br.ErrMsg = "解析数据失败，Err:" + err.Error()
			return
		}
		originPwd := string(pwdByte)
		if !utils.CheckPwd(originPwd) {
			br.Msg = "密码格式错误，请重新输入"
			return
		}
		pwd = utils.MD5(originPwd)
	}

	count, err := models.GetSysUserCountBySysUserName(req.SysUserName)
	if err != nil && err != orm.ErrNoRows {
		br.Msg = "添加用户失败，系统错误"
		br.ErrMsg = "添加用户失败，系统错误 Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "添加用户失败，用户已存在"
		return
	}
	sysUser := &models.SysUser{}
	sysUser.SysUserName = req.SysUserName
	sysUser.SysRealName = req.RealName
	sysUser.Password = pwd
	sysUser.AreaCode = req.AreaCode
	sysUser.Phone = req.Phone
	sysUser.Email = req.Email
	sysUser.SysDepartmentId = req.SysDepartmentId
	sysUser.SysRoleId = req.SysRoleId
	sysUser.SysRoleName = sysRole.SysRoleName
	sysUser.Province = req.Province
	sysUser.City = req.City
	sysUser.IsEnabled = req.IsEnabled
	sysUser.CreateTime = time.Now()
	sysUser.ModifyTime = time.Now()

	depPathIds, err := services.GetSysDepartmentPathIdsById(req.SysDepartmentId)
	if err != nil {
		br.Msg = "编辑角色失败"
		br.ErrMsg = "获得部门路径失败，Err:" + err.Error()
		return
	}
	err = models.SaveSysUser(sysUser, depPathIds)
	if err != nil {
		br.Msg = "用户添加失败"
		br.ErrMsg = "用户添加失败，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "添加成功"
}

// Detail
// @Title 系统用户详情信息
// @Description 用户详情信息
// @Param   SysUserId   query   int  true       "系统用户id"
// @Success 200 {object} models.LoginResp
// @router /detail [get]
func (this *SysUserController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUserId, err := this.GetInt("SysUserId")
	if err != nil {
		br.Msg = "参数解析错误"
		return
	}
	if sysUserId <= 0 {
		br.Msg = "用户参数错误"
		br.ErrMsg = fmt.Sprintf("用户参数错误 <%d>", sysUserId)
		return
	}
	sysUser, err := models.GetSysUserById(sysUserId)
	if err != nil {
		br.Msg = "获取用户失败，用户已删除"
		br.ErrMsg = "获取用户失败，用户已删除，Err" + err.Error()
		return
	}
	sysUser.Password = ""
	sysUser.SysDepartmentId = 0
	br.Data = sysUser
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// Edit
// @Title 系统用户编辑
// @Description 系统用户编辑
// @Param	request	body UserLoginReq true "type json string"
// @Success 200 {object} models.LoginResp
// @router /edit [post]
func (this *SysUserController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.EditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SysUserName == "" {
		br.Msg = "请输入用户名"
		return
	}
	if req.SysUserId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = fmt.Sprintf("参数错误，sysUserId<%d>", req.SysUserId)
		return
	}
	if req.SysRoleId <= 0 {
		br.Msg = "请选择角色"
		br.ErrMsg = "角色ID小于等于0"
		return
	}

	sysUser, err := models.GetSysUserById(req.SysUserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在，请刷新页面"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取用户数据失败，Err:" + err.Error() + ";sysUserId:" + fmt.Sprint(req.SysUserId)
		return
	}
	item, err := models.GetSysUserBySysUserName(req.SysUserName)
	if err != nil && err != orm.ErrNoRows {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error() + ";sysUserName:" + req.SysUserName
		return
	}
	if item != nil && item.SysUserId != req.SysUserId {
		br.Msg = "账号名称已存在,请重新输入"
		return
	}
	//req.Phone = strings.TrimSpace(req.Phone)
	//req.Email = strings.TrimSpace(req.Email)
	//if req.Phone == "" && req.Email == "" {
	//	br.Msg = "至少输入一个手机号或邮箱"
	//	return
	//}
	//if req.Phone != "" {
	//	if req.AreaCode == "86" {
	//		if !utils.ValidateMobileFormatat(req.Phone) {
	//			br.Msg = "手机号格式有误, 请检查"
	//			return
	//		}
	//	}
	//}
	//if req.Email != "" {
	//	if !utils.ValidateEmailFormatat(req.Email) {
	//		br.Msg = "邮箱格式有误, 请检查"
	//		return
	//	}
	//}

	var roleName string
	roleItem, err := models.GetSysRoleById(req.SysRoleId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "角色不存在，请重新选择"
			br.ErrMsg = "角色不存在"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取角色数据失败，Err:" + err.Error()
		return
	}
	if roleItem != nil {
		roleName = roleItem.SysRoleName
	}

	sysUser.SysUserName = req.SysUserName
	//sysUser.SysRealName = req.RealName
	//sysUser.AreaCode = req.AreaCode
	//sysUser.Phone = req.Phone
	//sysUser.Email = req.Email
	sysUser.SysRoleId = req.SysRoleId
	sysUser.SysRoleName = roleName
	//sysUser.Province = req.Province
	//sysUser.City = req.City
	//sysUser.IsEnabled = req.IsEnabled
	sysUser.ModifyTime = time.Now()
	err = sysUser.Save()
	if err != nil {
		br.Msg = "编辑角色失败"
		br.ErrMsg = "编辑角色失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// List
// @Title 系统用户列表
// @Description 系统用户列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   DepartmentId   query   int  true       "部门ID"
// @Param   RoleId   query   int  true       "角色ID"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} models.LoginResp
// @router /list [get]
func (this *SysUserController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	roleId, _ := this.GetInt("RoleId")
	departmentId, _ := this.GetInt("DepartmentId")
	keyWord := this.GetString("KeyWord")

	var condition string
	var pars []interface{}

	if roleId > 0 {
		condition += ` AND sys_role_id=? `
		pars = append(pars, roleId)
	}

	if departmentId > 0 {
		condition += ` AND (sys_department_id1=? OR sys_department_id2=? OR sys_department_id3=?) `
		pars = append(pars, departmentId, departmentId, departmentId)
	}

	if keyWord != "" {
		condition += ` AND (sys_real_name LIKE ? OR sys_user_name LIKE ? OR phone LIKE ? OR email LIKE ?) `
		pars = utils.GetLikeKeywordPars(pars, keyWord, 4)
	}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	total, err := models.GetSysUserCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err := services.GetSysUserList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	sysUserList := make([]models.SysUserView, len(list))
	for i, user := range list {
		sysUserList[i].SysUserId = user.SysUserId
		sysUserList[i].SysUserName = user.SysUserName
		sysUserList[i].SysRealName = user.SysRealName
		sysUserList[i].Email = user.Email
		sysUserList[i].Phone = user.Phone
		sysUserList[i].AreaCode = user.AreaCode
		sysUserList[i].SysRoleId = user.SysRoleId
		sysUserList[i].SysRoleName = user.SysRoleName
		sysUserList[i].SysDepartmentId = user.SysDepartmentId
		var path string
		if user.SysDepartmentName1 != "" {
			path = user.SysDepartmentName1
		}
		if user.SysDepartmentName2 != "" {
			path += "/" + user.SysDepartmentName2
		}
		if user.SysDepartmentName3 != "" {
			path += "/" + user.SysDepartmentName3
		}
		sysUserList[i].SysDepartmentName = path
		sysUserList[i].SysRoleId = user.SysRoleId
		sysUserList[i].Province = user.Province
		sysUserList[i].City = user.City
		sysUserList[i].PositionCode = user.PositionCode
		sysUserList[i].PositionName = user.PositionName
		sysUserList[i].IsEnabled = user.IsEnabled
		sysUserList[i].CreateTime = user.CreateTime
		sysUserList[i].ModifyTime = user.ModifyTime
	}

	page := paging.GetPaging(currentIndex, pageSize, total)

	resp := new(response.SysUserListResp)
	resp.List = sysUserList
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ResetPass
// @Title 重置密码
// @Description 重置密码
// @Param	request	body system.SysUserResetPassReq true "type json string"
// @Success 200 编辑成功
// @router /reset_pass [post]
func (this *SysUserController) ResetPass() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.ResetPasswordReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SysUserId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误，SysUserNameId"
		return
	}
	req.Password = strings.TrimSpace(req.Password)
	req.RePassword = strings.TrimSpace(req.RePassword)
	if req.Password == "" {
		br.Msg = "密码不能为空"
		return
	}
	if req.Password != req.RePassword {
		br.Msg = "两次密码输入不一致"
		return
	}
	sysUser, err := models.GetSysUserById(req.SysUserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户已被删除, 请刷新页面"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error() + ";SysUserId:" + fmt.Sprint(req.SysUserId)
		return
	}
	b, err := base64.StdEncoding.DecodeString(req.Password)
	if err != nil {
		br.Msg = "解析数据失败"
		br.ErrMsg = "解析数据失败，Err:" + err.Error()
		return
	}
	pwd := string(b)
	if !utils.CheckPwd(pwd) {
		br.Msg = "密码格式不对，必须包含8位及以上，包含数字、大写字母、小写字母、特殊字符中的三个类型"
		return
	}
	pwd = utils.MD5(pwd)
	sysUser.Password = pwd
	sysUser.IsEnabled = true
	sysUser.ModifyTime = time.Now()
	err = sysUser.Save()
	if err != nil {
		br.Msg = "密码修改失败"
		br.ErrMsg = "密码修改失败，系统错误，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "重置密码成功"
	br.Success = true
}

// ResetMyPass
// @Title 重置密码
// @Description 重置密码
// @Param	request	body system.SysUserResetPassReq true "type json string"
// @Success 200 编辑成功
// @router /reset_my_pass [post]
func (this *SysUserController) ResetMyPass() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.ResetMyPasswordReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Password != req.RePassword {
		br.Msg = "两次密码输入不一致"
		return
	}

	sysUser := this.SysUser
	// 校验系统用户的密码
	var pwd string
	{
		pwdByte, err := base64.StdEncoding.DecodeString(req.Password)
		if err != nil {
			br.Msg = "解析数据失败"
			br.ErrMsg = "解析数据失败，Err:" + err.Error()
			return
		}
		originPwd := string(pwdByte)
		if !utils.CheckPwd(originPwd) {
			br.Msg = "密码格式错误，请重新输入"
			return
		}
		pwd = utils.MD5(originPwd)

		originPwdByte, err := base64.StdEncoding.DecodeString(req.OriginPassword)
		if err != nil {
			br.Msg = "解析数据失败"
			br.ErrMsg = "解析数据失败，Err:" + err.Error()
			return
		}
		stringPwd := string(originPwdByte)
		if sysUser.Password != utils.MD5(stringPwd) {
			br.Msg = "原密码错误"
			return
		}
	}

	sysUser.Password = pwd
	sysUser.ModifyTime = time.Now()
	err = sysUser.Update([]string{"password", "modify_time"})
	if err != nil {
		br.Msg = "密码修改失败"
		br.ErrMsg = "密码修改失败，系统错误，Err:" + err.Error()
		return
	}
	//将用户对应的token给过期
	services.LogoutSysUser(sysUser.SysUserId)

	br.Msg = "重置密码成功"
	br.Success = true
	br.Ret = 200
}

// @Title 开启/禁用系统用户
// @Description 开启/禁用系统用户接口
// @Param	request	body system.SysuserEditReq true "type json string"
// @Success 200 操作成功
// @router /editEnabled [post]
func (this *SysUserController) EditEnabled() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.SysUserEditEnabledReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	sysUser, err := models.GetSysUserById(req.SysUserId)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error()
		return
	}
	if sysUser.SysRoleName == "admin" && sysUser.SysUserName == "admin" {
		br.Msg = "禁止对admin使用<禁用>功能"
		return
	}
	// 修改系统用户禁用状态
	sysUser.IsEnabled = req.IsEnabled
	err = sysUser.Update([]string{"is_enabled"})
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改系统用户数据失败，Err:" + err.Error()
		return
	}

	//用户被禁用的情况下，需要将他对应的token给过期
	if sysUser.IsEnabled && !req.IsEnabled {
		services.LogoutSysUser(req.SysUserId)
	}

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

// MoveToDepartment
// @Title 移动分组
// @Description 移动分组
// @Param	request	body system.SysUserMoveReq true "type json string"
// @Success 200 编辑成功
// @router /moveToDepartment [post]
func (this *SysUserController) MoveToDepartment() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

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

	count, err := models.GetSysUserCountById(req.SysUserId)
	if err != nil {
		br.Msg = "移动分组失败，系统错误"
		br.ErrMsg = "移动分组失败，系统错误，Err:" + err.Error()
		return
	}
	if count <= 0 {
		br.Msg = "用户已被删除, 请刷新页面"
		return
	}
	count, err = models.GetSysDepartmentCountById(req.SysDepartmentId)
	if err != nil {
		br.Msg = "移动分组失败，系统错误"
		br.ErrMsg = "移动分组失败，系统错误，Err:" + err.Error()
		return
	}
	if count <= 0 {
		br.Msg = "分组已被删除, 请刷新页面"
		return
	}
	depPathIds, err := services.GetSysDepartmentPathIdsById(req.SysDepartmentId)
	if err != nil {
		br.Msg = "移动分组失败，系统错误"
		br.ErrMsg = "获得分组路径失败，系统错误，Err:" + err.Error()
		return
	}
	sysUser := &models.SysUser{}
	sysUser.SysUserId = req.SysUserId
	sysUser.SysDepartmentId1 = depPathIds[0]
	sysUser.SysDepartmentId2 = depPathIds[1]
	sysUser.SysDepartmentId3 = depPathIds[2]
	sysUser.ModifyTime = time.Now()
	if depPathIds[0] != 0 {
		sysUser.SysDepartmentId = depPathIds[0]
	}
	if depPathIds[1] != 0 {
		sysUser.SysDepartmentId = depPathIds[1]
	}
	if depPathIds[2] != 0 {
		sysUser.SysDepartmentId = depPathIds[2]
	}
	err = sysUser.Update([]string{"sys_department_id", "sys_department_id1", "sys_department_id2", "sys_department_id3", "modify_time"})

	// userDepMapping := &models.SysUserDepartmentMapping{}
	// userDepMapping.SysUserId = req.SysUserId
	// userDepMapping.SysDepartmentId1 = depPathIds[0]
	// userDepMapping.SysDepartmentId2 = depPathIds[1]
	// userDepMapping.SysDepartmentId3 = depPathIds[2]
	// err = userDepMapping.Save()
	if err != nil {
		br.Msg = "移动分组失败，系统错误"
		br.ErrMsg = "移动分组失败，系统错误，Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "移动分组成功"
}
