package user

import (
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	userLogic "hongze/hongze_yb/logic/user"
	"hongze/hongze_yb/models/request/user"
	userResp "hongze/hongze_yb/models/response/user"
	userService "hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strings"
)

// Login 登录接口
// @Tags 用户模块
// @Summary  用户登录
// @Description 用户手机号/邮箱登录
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Accept  json
// @Product json
// @Param data body user.LoginReq true "请求参数"
// @Success 200 {object} user.LoginResp
// @Router /user/login [post]
func Login(c *gin.Context) {
	var req user.LoginReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数异常", c)
		return
	}
	userInfo := userService.GetInfoByClaims(c)
	openId := userInfo.OpenID
	if openId == "" {
		response.Fail("参数异常", c)
		return
	}
	if req.LoginType != 1 && req.LoginType != 2 {
		response.Fail("无效的登录方式", c)
		return
	}

	if req.LoginType == 1 {
		//手机登录
		req.Mobile = strings.Trim(req.Mobile, " ")
		if req.Mobile == "" {
			response.Fail("手机号不能为空,请输入手机号", c)
			return
		}
	}
	if req.LoginType == 2 {
		//邮箱登录
		req.Email = strings.Trim(req.Email, " ")
		if req.Email == "" {
			response.Fail("邮箱不能为空,请输入邮箱", c)
			return
		}
		if !utils.ValidateEmailFormatat(req.Email) {
			response.Fail("邮箱格式错误，请重新输入", c)
			return
		}
	}

	token, newUserInfo, err, errMsg := userService.BindWxUser(openId, req.Mobile, req.Email, req.VerifyCode, req.LoginType, req.AreaNum, 1)
	if err != nil {
		if errMsg == "" {
			errMsg = "登录失败"
		}
		response.Fail(errMsg, c)
		return
	}

	response.OkData("登录成功", userResp.LoginResp{
		UserID: int(newUserInfo.UserID),
		Token:  token,
		Email:  newUserInfo.Email,
		Mobile: newUserInfo.Mobile,
	}, c)
}

// GetSmsCode 获取短信验证码接口
// @Tags 用户模块
// @Summary  获取短信验证码
// @Description 获取短信验证码接口
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Param mobile	query string true "手机号"
// @Param area_num	query string true "手机国际区号（中国大陆：86）"
// @Accept  json
// @Product json
// @Success 200 {string} string 获取验证码成功
// @Failure 400 {string} string 手机号不能为空,请输入手机号
// @Router /user/get_sms_code [get]
func GetSmsCode(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	openId := userInfo.OpenID
	if openId == "" {
		response.Fail("参数异常", c)
		return
	}

	mobile := c.DefaultQuery("mobile", "")
	areaNum := c.DefaultQuery("area_num", "")

	err, errMsg := userLogic.SendSmsCode(openId, mobile, areaNum)
	if err != nil {
		if errMsg != "" {
			errMsg = "获取验证码失败"
		}
		response.Fail(errMsg, c)
		return
	}

	response.Ok("获取验证码成功", c)
}

// GetEmailCode 获取邮箱验证码接口
// @Tags 用户模块
// @Summary  获取邮箱验证码
// @Description 获取邮箱验证码
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Param email	query string true "电子邮箱账号"
// @Accept  json
// @Product json
// @Success 200 {string} string 获取验证码成功
// @Failure 400 {string} string 请输入邮箱地址
// @Router /user/get_email_code [get]
func GetEmailCode(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	openId := userInfo.OpenID
	if openId == "" {
		response.Fail("参数异常", c)
		return
	}

	email := c.DefaultQuery("email", "")
	if email == "" {
		response.Fail("请输入邮箱地址", c)
		return
	}
	if !utils.ValidateEmailFormatat(email) {
		response.Fail("邮箱格式错误，请重新输入", c)
		return
	}

	err, errMsg := userLogic.SendEmailCode(openId, email)
	if err != nil {
		if errMsg != "" {
			errMsg = "获取验证码失败"
		}
		response.Fail(errMsg, c)
		return
	}

	response.Ok("获取验证码成功", c)
}

// Info 我的详情
// @Tags 用户模块
// @Summary  我的详情
// @Description 我的详情
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Accept  json
// @Product json
// @Success 200 {object} user.Detail "获取成功"
// @failure 400 {string} string "获取失败"
// @Router /user/info [get]
func Info(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	list, err, errMsg := userLogic.GetUserInfo(userInfo)
	if err != nil {
		if errMsg != "" {
			errMsg = "获取失败"
		}
		response.Fail(errMsg, c)
		return
	}

	response.OkData("获取成功", list, c)
}

// GetLastApplyRecord 获取最近一条申请单信息
// @Tags 用户模块
// @Summary  获取最近一条申请单信息
// @Description 获取最近一条申请单信息
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Accept  json
// @Product json
// @Success 200 {object} user.Record "获取成功"
// @failure 400 {string} string "获取失败"
// @Router /user/get_last_apply_record [get]
func GetLastApplyRecord(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	record, err := userLogic.GetLastApplyInfo(int(userInfo.UserID))

	if err != nil {
		response.Fail("获取失败", c)
		return
	}

	if record.RealName == "" {
		response.Ok("获取成功", c)
	} else {
		response.OkData("获取成功", record, c)
	}
}

// Apply
// @Tags 用户模块
// @Summary  用户申请
// @Description 用户申请
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Accept  json
// @Product json
// @Param data body user.ApplyReq true "请求参数"
// @Success 200 {object} user.LoginResp
// @Router /user/apply [post]
func Apply(c *gin.Context) {
	var req user.ApplyReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数异常", c)
		return
	}
	userInfo := userService.GetInfoByClaims(c)
	userId := userInfo.UserID
	if userId == 0 {
		response.Fail("参数异常", c)
		return
	}
	_, err := userLogic.Apply(int(userInfo.UserID), userInfo.CompanyID, userInfo.Mobile, userInfo.Email, req)

	if err != nil {
		response.Fail("申请失败", c)
		return
	}
	response.Ok("申请成功", c)
}

// GetTabBar 获取用户的菜单栏权限
// @Tags 用户模块
// @Summary  获取用户的菜单栏权限
// @Description 获取用户的菜单栏权限
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Accept  json
// @Product json
// @Success 200 {object} []string "获取成功"
// @failure 400 {string} string "获取失败"
// @Router /user/get_tab_bar [get]
func GetTabBar(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	version := c.Request.Header.Get("version")
	tabBarList, err := userLogic.GetUserTabBar(userInfo, version)

	if err != nil {
		response.Fail("获取失败", c)
		return
	}

	response.OkData("获取成功", tabBarList, c)
}

// SetUserInfo 设置用户个人信息（头像和昵称）
func SetUserInfo(c *gin.Context) {
	var req user.SetUserInfoReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数异常", c)
		return
	}
	// 去掉首尾空格
	req.NickName = strings.Trim(req.NickName, "")
	req.HeadImgUrl = strings.Trim(req.HeadImgUrl, "")
	if req.NickName == "" {
		response.Fail("请输入昵称", c)
		return
	}

	if req.HeadImgUrl == "" {
		response.Fail("请上传头像", c)
		return
	}
	userInfo := userService.GetInfoByClaims(c)

	err := userLogic.SetUserInfo(userInfo, req)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	response.Ok("更新成功", c)
}

// GetTopTab 获取首页顶部Tab
// @Tags 用户模块
// @Summary  获取首页顶部Tab
// @Description 获取首页顶部Tab
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Accept  json
// @Product json
// @Success 200 {object} []string "获取成功"
// @failure 400 {string} string "获取失败"
// @Router /user/get_top_tab [get]
func GetTopTab(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	version := c.Request.Header.Get("version")
	tabBarList, err := userLogic.GetTopTab(userInfo, version)

	if err != nil {
		response.Fail("获取失败", c)
		return
	}

	response.OkData("获取成功", tabBarList, c)
}
