package controllers

import (
	"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/utils"
	"fmt"
	"time"
)

type UserLoginController struct {
	BaseCommonController
}

// Login
// @Title 用户登录
// @Description 用户登录
// @Param	request	body UserLoginReq true "type json string"
// @Success 200 {object} models.LoginResp
// @router /login [post]
func (this *UserLoginController) Login() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.UserLoginReq
	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 := models.GetSysUserBySysUserName(req.UserName)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "登录失败, 账号或密码错误"
			return
		} else {
			br.Msg = "系统错误"
			br.ErrMsg = "系统错误" + err.Error()
			return
		}
	}
	sysRole, err := models.GetSysRoleById(sysUser.SysRoleId)
	if err != nil {
		br.Msg = "登录失败"
		br.ErrMsg = "查询角色失败, Err:" + err.Error()
		return
	}
	dbPass := utils.MD5(fmt.Sprintf("%s%s%s", sysUser.Password, utils.UserLoginSalt, req.ReqTime))
	if req.Password != dbPass {
		br.Msg = "登录失败, 账号或密码错误"
		return
	}
	account := utils.MD5(sysUser.SysUserName)
	token := utils.GenToken(account)
	sysSession := new(models.SysSession)
	sysSession.UserName = sysUser.SysUserName
	sysSession.SysUserId = sysUser.SysUserId
	sysSession.ExpiredTime = time.Now().AddDate(0, 0, 60)
	sysSession.CreatedTime = time.Now()
	sysSession.LastUpdatedTime = time.Now()
	sysSession.AccessToken = token
	err = sysSession.AddSysSession()
	if err != nil {
		br.Msg = "登录失败"
		br.ErrMsg = "新增session信息失败, Err:" + err.Error()
		return
	}
	resp := new(response.LoginResp)
	resp.Authorization = "authorization=" + token
	resp.SysUserName = sysUser.SysUserName
	resp.SysRealName = sysUser.SysRealName
	resp.SysUserId = sysUser.SysUserId
	resp.RoleName = sysRole.SysRoleName
	resp.RoleId = sysUser.SysRoleId

	// 获取不可信的登录态，并将该登录态重置掉，不允许多次登录
	noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, sysUser.SysUserId)
	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", time.Hour*24)
	}
	// 设置redis缓存，记录用户登录态
	loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, sysSession.SysSessionId)
	utils.Rc.Put(loginKey, "1", time.Hour*24)
	utils.Rc.Put(noTrustLoginKey, sysSession.SysSessionId, time.Hour*24*60)

	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "登录成功"
}

// AreaCodeList
// @Title 手机号区号列表
// @Description 手机号区号列表
// @Success 200 Ret=200 获取成功
// @router /area_code/list [get]
func (this *UserLoginController) AreaCodeList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()

	resp := make([]response.AreaCodeListResp, 0)
	confAuth, e := models.GetConfigDetailByCode(models.ConfAreaCodeListKey)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取手机号区号配置失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "手机号区号配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &resp); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "手机号区号配置有误"
		return
	}

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