package account

import (
	"context"
	"fmt"
	account "fonchain-fiee/api/accountFiee"
	"fonchain-fiee/pkg/e"
	"fonchain-fiee/pkg/model/login"
	"fonchain-fiee/pkg/model/union"
	"fonchain-fiee/pkg/service"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

func UserApproval(c *gin.Context) {
	var req account.CheckRealNameRequest
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}
	res, err := service.AccountFieeProvider.CheckRealName(c, &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
	return
}
func UserList(c *gin.Context) {
	var req account.UserListRequest
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}
	req.Domain = "app"
	res, err := service.AccountFieeProvider.UserList(context.Background(), &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
	return
}
func UserInfo(c *gin.Context) {
	var req account.InfoRequest
	user := login.GetUserInfoFromC(c)
	req.ID = user.ID
	req.Domain = user.Domain
	res, err := service.AccountFieeProvider.Info(c, &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
	return
}

func UserUpdate(c *gin.Context) {
	var req account.UpdateRequest
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}
	user := login.GetUserInfoFromC(c)
	req.ID = user.ID
	req.Domain = user.Domain
	res, err := service.AccountFieeProvider.Update(c, &account.UpdateRequest{
		ID:       req.ID,
		Domain:   req.Domain,
		Language: req.Language,
		NickName: req.NickName,
	})
	if err != nil {
		service.Error(c, err)
		return
	}
	service.Success(c, res)
	return
}

// SendMsg 用户发送验证码
func SendMsg(c *gin.Context) {
	var req account.SendMsgRequest
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}
	data, err := service.AccountFieeProvider.VerifySliderStatus(c, &account.VerifySliderStatusRequest{
		NonceStr: req.NonceStr,
	})
	fmt.Println("data=============>", data, err)
	if err != nil {
		service.Error(c, err)
		return
	}
	req.Project = "fiee"
	req.TelNum = req.Zone + req.TelNum
	if req.Zone != e.ZoneCn && req.Zone != "" {
		// ============================== redis检查ip开始
		ip := c.ClientIP()
		fmt.Println("当前ip：", ip, ";手机号：", req.TelNum, ";domain：", req.Domain)
		//daykey := "day_sms_limit:" + ip
		//minutekey := "minute_sms_limit:" + ip
		//duration := time.Second
		//isBlacklisted, blackErr := cache.RedisClient.SIsMember("nation_sms_blacklist", ip).Result()
		//if blackErr != nil {
		//	service.Error(c, errors.New("Redis error"))
		//	return
		//}
		//if isBlacklisted {
		//	fmt.Println("当前ip手机号在黑名单中：", ip, ";手机号：", req.TelNum, ";domain：", req.Domain)
		//	service.Success(c, "succes！!")
		//	return
		//}
		//
		//// 一分钟5次，一天30次
		//if dayCount, redisErr := cache.RedisClient.Get(daykey).Int(); redisErr == redis.Nil {
		//	cache.RedisClient.Set(daykey, 1, 24*time.Hour)
		//} else if redisErr != nil {
		//	service.Error(c, errors.New("Redis error"))
		//	return
		//} else if dayCount >= 30 {
		//	cache.RedisClient.SAdd("nation_sms_blacklist", ip)
		//	cache.RedisClient.Expire("nation_sms_blacklist", 24*time.Hour) // 黑名单记录有效期为24小时
		//	fmt.Println("当前ip手机号在黑名单中：", ip, ";手机号：", req.TelNum, ";domain：", req.Domain)
		//	service.Success(c, "succes！!")
		//	return
		//}
		//if minuteCount, redisErr := cache.RedisClient.Get(minutekey).Int(); redisErr == redis.Nil {
		//	cache.RedisClient.Set(minutekey, 1, duration)
		//} else if redisErr != nil {
		//	service.Error(c, errors.New("Redis error"))
		//	return
		//} else if minuteCount >= 5 {
		//	fmt.Println("当前ip触发每分钟5次限制：", ip, ";手机号：", req.TelNum, ";domain：", req.Domain)
		//	service.Success(c, "succes！!")
		//	return
		//}
		//cache.RedisClient.Incr(daykey)
		//cache.RedisClient.Incr(minutekey)
		// ============================== redis检查ip结束

		tempReq := &account.SendNationMsgRequest{
			Domain:  req.Domain,
			TelNum:  req.TelNum,
			Project: req.Project,
			SignNo:  req.SignNo,
			MId:     req.MId,
			Scope:   req.Scope,
		}
		res, err := service.AccountFieeProvider.SendNationMsg(context.Background(), tempReq)
		if err != nil {
			service.Error(c, err)
			return
		}
		service.Success(c, res)
		return
	} else {
		res, err := service.AccountFieeProvider.SendMsg(context.Background(), &req)
		if err != nil {
			service.Error(c, err)
			return
		}

		service.Success(c, res)
		return
	}

	//req.Domain = "app"
	//req.SignNo = uint32(config.DefaultSignNo)
	//res, err := service.AccountFieeProvider.SendMsg(context.Background(), &req)
	//if err != nil {
	//	service.Error(c, err)
	//	return
	//}

}
func RealName(c *gin.Context) {
	var req account.RealNameRequest

	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}
	user := login.GetUserInfoFromC(c)
	req.Id = user.ID
	res, err := service.AccountFieeProvider.RealName(context.Background(), &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
	return
}

// CheckMsg 验证码是否正确
func CheckMsg(c *gin.Context) {

	var req account.CheckMsgRequest

	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}
	req.TelNum = req.Zone + req.TelNum
	res, err := service.AccountFieeProvider.CheckMsg(context.Background(), &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
	return
}
func GenerateCaptcha(c *gin.Context) {

	req := account.GenerateSliderCaptchaRequest{}

	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}

	res, err := service.AccountFieeProvider.GenerateSliderCaptcha(context.Background(), &req)

	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)

}

func ValidateCaptcha(c *gin.Context) {

	req := account.VerifySliderCaptchaRequest{}

	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}

	res, err := service.AccountFieeProvider.VerifySliderCaptcha(context.Background(), &req)

	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)

}
func UserLogout(c *gin.Context) {
	req := account.DecryptJwtRequest{}
	req.Token = c.GetHeader(e.Authorization)
	res, err := service.AccountFieeProvider.Logout(c, &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
	return
}
func UserRegister(c *gin.Context) {
	var req account.RegistRequest
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}
	req.Domain = "app"
	res, err := service.AccountFieeProvider.Register(context.Background(), &req)
	if err != nil {
		service.Error(c, err)
		return
	}
	tokenInfo, err := service.AccountFieeProvider.Login(context.Background(), &account.LoginRequest{
		Domain:      req.Domain,
		TelNum:      req.TelNum,
		Code:        req.Code,
		TelAreaCode: req.TelAreaCode,
	})
	if err != nil {
		service.Error(c, err)
		return
	}
	res.Token = tokenInfo.Token
	service.Success(c, res)
	return
}

// UserLogin 用户登录操作
func UserLogin(c *gin.Context) {
	var req account.LoginRequest
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}
	req.Ip = c.ClientIP()
	req.Domain = "fontree"
	res, err := service.AccountFieeProvider.Login(c, &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	accountInfo := &union.AccountInfo{
		ID:           res.AccountInfo.ID,
		Account:      res.AccountInfo.Account,
		NickName:     res.AccountInfo.NickName,
		Domain:       res.AccountInfo.Domain,
		TelNum:       res.AccountInfo.TelNum,
		Avatar:       res.AccountInfo.Avatar,
		CreatedAt:    res.AccountInfo.CreateAt,
		IsNeedChange: res.AccountInfo.IsNeedChange,
		Sex:          res.AccountInfo.Sex,
	}
	resInfo := &union.Login{
		Token:        res.Token,
		RefreshToken: res.RefreshToken,
		AccountInfo:  accountInfo,
		//JumpToWhere:  jumpToWhere,
	}

	service.Success(c, resInfo)

	return
}
