package controllers

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/eta_forum"
	"hongze/hz_crm_api/utils"
	"time"
)

// 系统相关
type SysUserController struct {
	BaseCommonController
}

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

	if req.Username == "" {
		br.Msg = "请输入账号"
		return
	}

	if req.Password == "" {
		br.Msg = "请输入密码"
		return
	}
	sysUser, err := system.CheckSysUser(req.Username, req.Password)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "登录失败,账号或密码错误"
			br.ErrMsg = "登录失败，账号或密码错误,Err:" + err.Error()
			br.IsSendEmail = false
			return
		}
		br.IsSendEmail = false
		br.Msg = "登录失败,账号或密码错误"
		br.ErrMsg = "登录失败，Err:" + err.Error()
		return
	}
	if sysUser == nil {
		br.IsSendEmail = false
		br.Msg = "登录失败,账号或密码错误"
		br.ErrMsg = "登录失败，sysUser is nil "
		return
	}
	if sysUser.Enabled == 0 {
		br.Msg = "您的账号已被禁用，如需登录，请联系管理员"
		br.ErrMsg = fmt.Sprintf("您的账号已被禁用，登录账号:%s，账户名称：%s，如需登录，请联系管理员", sysUser.AdminName, sysUser.RealName)
		return
	}
	// 是否记住密码
	var isRemember int
	if req.IsRemember {
		isRemember = 1
	}
	account := utils.MD5(req.Username)
	token := utils.GenToken(account)
	sysSession := new(system.SysSession)
	sysSession.UserName = req.Username
	sysSession.SysUserId = sysUser.AdminId
	sysSession.ExpiredTime = time.Now().AddDate(0, 0, 90)
	sysSession.IsRemember = isRemember
	sysSession.CreatedTime = time.Now()
	sysSession.LastUpdatedTime = time.Now()
	sysSession.AccessToken = token
	err = system.AddSysSession(sysSession)
	fmt.Println("id:", sysSession.Id)
	if err != nil {
		br.ErrMsg = "新增session信息失败，Err:" + err.Error()
		br.Msg = "登录失败"
		return
	}

	// 修改最后登录时间
	{
		sysUser.LastLoginTime = time.Now().Format(utils.FormatDateTime)
		sysUser.LastUpdatedTime = time.Now().Format(utils.FormatDateTime)
		sysUser.Update([]string{"LastLoginTime", "LastUpdatedTime"})
	}

	resp := new(system.LoginResp)
	resp.Authorization = token
	resp.Authorization = "authorization=" + token + "$account=" + account
	resp.RealName = sysUser.RealName
	resp.AdminName = sysUser.AdminName
	resp.RoleName = sysUser.RoleName

	resp.SysRoleTypeCode = sysUser.RoleTypeCode //系统角色编码
	resp.RoleTypeCode = sysUser.RoleTypeCode

	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
		resp.RoleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
	}

	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
		resp.RoleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
	}

	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
		resp.RoleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
	}

	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
		resp.RoleTypeCode = utils.ROLE_TYPE_CODE_RAI_SELLER
	}

	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
		resp.RoleTypeCode = utils.ROLE_TYPE_CODE_RAI_SELLER
	}

	if sysUser.RoleName == utils.ROLE_NAME_FICC_DIRECTOR {
		resp.RoleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
	}

	resp.AdminId = sysUser.AdminId
	var productName string
	productId := services.GetProductId(sysUser.RoleTypeCode)
	//if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
	//	productName = utils.COMPANY_PRODUCT_FICC_NAME
	//} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
	//	productName = utils.COMPANY_PRODUCT_RAI_NAME
	//} else {
	//	productName = "admin"
	//}
	if productId == 1 {
		productName = utils.COMPANY_PRODUCT_FICC_NAME
	} else if productId == 2 {
		productName = utils.COMPANY_PRODUCT_RAI_NAME
	} else {
		productName = "admin"
	}
	resp.ProductName = productName
	resp.Authority = sysUser.Authority
	br.Ret = 200
	br.Success = true
	br.Msg = "登录成功"
	br.Data = resp
	//新增登录记录
	{
		record := new(system.SysUserLoginRecord)
		record.Uid = sysUser.AdminId
		record.UserName = req.Username
		record.Ip = this.Ctx.Input.IP()
		record.Stage = "login"
		record.CreateTime = time.Now()
		go system.AddSysUserLoginRecord(record)
	}

	// 设置redis缓存
	{

		// 获取不可信的登录态，并将该登录态重置掉，不允许多次登录
		noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, sysUser.AdminId)
		noTrustLoginId, _ := utils.Rc.RedisString(noTrustLoginKey)
		fmt.Println("noTrustLoginId:", noTrustLoginId)
		if noTrustLoginId != `` { // 如果存在不可信设备，那么将其下架
			oldNoTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, noTrustLoginId)
			utils.Rc.Put(oldNoTrustLoginKey, "0", 30*time.Minute)
		}

		if !req.IsRemember { // 如果当前是不可信设备，那么将其加入到不可信名单
			loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, sysSession.Id)
			utils.Rc.Put(loginKey, "1", 30*time.Minute)

			noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, sysUser.AdminId)
			utils.Rc.Put(noTrustLoginKey, sysSession.Id, 30*time.Minute)
		}
	}
}

type SysUserAuthController struct {
	BaseAuthController
}

// @Title 修改密码
// @Description 修改密码
// @Param	request	body models.ModifyPwdReq true "type json string"
// @Success 200 {object} models.LoginResp
// @router /modify/pwd [post]
func (this *SysUserAuthController) ModifyPwd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.ModifyPwdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "登录失败,账号或密码错误"
		br.ErrMsg = "登录失败，sysUser is nil "
		return
	}
	if req.OldPwd == "" {
		br.Msg = "原始密码不能为空"
		return
	}

	if req.NewPwd == "" {
		br.Msg = "新密码不能为空"
		return
	}

	if sysUser.Password != req.OldPwd {
		br.Msg = "旧密码错误，请重新输入"
		return
	}
	err = system.ModifyPwd(sysUser.AdminId, req.NewPwd)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "修改成功"
}

// CheckPwd
// @Title 校验是否初始密码
// @Description 校验是否初始密码
// @Success 200 {bool} true "是否初始密码；false代表不是初始密码，直接进去；true代表是初始密码，需要强制修改密码"
// @router /check_pwd [get]
func (this *SysUserAuthController) CheckPwd() {
	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 nil "
		return
	}

	br.Data = false
	if sysUser.Password == utils.MD5("123456a") {
		br.Data = true
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "校验成功"
}

// @Title 获取系统用户UUID
// @Description 获取系统用户UUID
// @Success 200 {object} system.SysuserListResp
// @router /uuid [get]
func (this *SysUserController) Uuid() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	nowTime := time.Now().Format(utils.FormatDateTimeUnSpace)
	randBigint := utils.GetRandDigit(4)
	randStr := utils.GetRandStringNoSpecialChar(4)
	uuid := nowTime + randBigint + randStr
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = uuid
}

// GetEtaAuthCode
// @Title 免密登录-获取登录ETA系统的编码
// @Description 免密登录-获取登录ETA系统的编码
// @Success 200 Ret=200 获取成功
// @router /get_eta_auth_code [get]
func (this *SysUserAuthController) GetEtaAuthCode() {
	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
	}

	code, e := services.GetAuthCodeFromMiddleServer(sysUser.AdminName)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取登录编码失败, Err: " + e.Error()
		return
	}

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

// AuthCodeLogin
// @Title 编码登录
// @Description 编码登录
// @Success 200 Ret=200 操作成功
// @router /auth_code_login [get]
func (this *SysUserController) AuthCodeLogin() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	authCode := this.GetString("AuthCode", "")
	if authCode == "" {
		br.Msg = "参数有误"
		br.ErrMsg = "参数缺失, AuthCode"
		return
	}

	data, e := services.CodeLoginFromMiddleServer(authCode)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取登录Token失败, Err: " + e.Error()
		return
	}

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

// GetEtaForumAdminAuthCode
// @Title 免密登录-获取登录ETA社区管理后台系统的编码
// @Description 免密登录-获取登录ETA社区管理后台系统的编码
// @Success 200 Ret=200 获取成功
// @router /forum_admin/auth_code [get]
func (this *SysUserAuthController) GetEtaForumAdminAuthCode() {
	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
	}

	code, e := eta_forum.GetForumAdminAuthCode(sysUser.AdminName)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取登录编码失败, Err: " + e.Error()
		return
	}

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