package backstage_service

import (
	"errors"
	"fmt"
	"github.com/gogf/gf/crypto/gmd5"
	g "github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/grand"
	"math/rand"
	"time"
	"youngmini_server/app/dao/backstage_dao"
	"youngmini_server/app/model/backstage_model"
	"youngmini_server/app/utils"
)

var User = serviceUser{}

type serviceUser struct{}

// GetUserPassword 获取密码字符串(保留方法)
func (s *serviceUser) GetUserPassword(password string) (string, error) {
	passwordStr := "young_web_admin:" + password
	encryptPwd, err := gmd5.EncryptString(passwordStr)
	if err != nil {
		return "", err
	}
	return encryptPwd, nil
}

// CreatUser 创建用户
func (s *serviceUser) CreatUser(user *backstage_model.CreatUser) error {
	// 密码加密user.Password, _ = s.GetUserPassword(user.Password)
	// 判断后台用户名是否存在
	err := backstage_dao.UserNameExist(user.UserName)
	if err != nil {
		return err
	}
	// 随机生成用户登录8位id
	rand.Seed(time.Now().UnixNano())
	userId := grand.Digits(8)
	err = backstage_dao.UserExist(userId)
	for err != nil {
		rand.Seed(time.Now().UnixNano())
		userId := grand.Digits(8)
		err = backstage_dao.UserExist(userId)
	}
	user.User = userId
	err = backstage_dao.CreatUser(user)
	if err != nil {
		return err
	}
	return nil
}

// GetUserInfo 系统用户登录服务
func (s *serviceUser) GetUserInfo(user *backstage_model.SysUsersServiceSignReq) (*backstage_model.SysUserModelResp, error) {
	// md5加密在后台实现，后期有可能需要在前端实现,前台实现了该功能
	// user.Password, _ = s.GetUserPassword(user.Password)
	sysUserDate, err := backstage_dao.SysUsers(user)
	if err != nil {
		return nil, err
	}
	return sysUserDate, nil
}

// CheckName 验证用户名是否存在并返回邮箱地址
func (s *serviceUser) CheckName(user string) (string, error) {
	use, err := backstage_dao.SysUserExist(user)
	if err != nil {
		return "", err
	}
	return use.Email, nil
}

// SetEmail 发送邮箱验证码
func (s *serviceUser) SetEmail(email string, user string) error {
	// 获取六位数字随机数
	arr := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	// 根据backstage::verification+用户电子邮箱存储redis值，保存时间为90秒。
	g.Redis().Do("SETEX", "backstage::verification::"+user, 90, arr)
	err := utils.SendMail(email, "修改密码", arr)
	if err != nil {
		return err
	}
	return nil
}

// CheckVerification 验证验证码是否正确
func (s *serviceUser) CheckVerification(verification string, user string) error {
	// 根据backstage::verification+用户电子邮箱获取redis键，以确保验证码正确。
	result, _ := g.Redis().DoVar("GET", "backstage::verification::"+user)
	fmt.Println(result.String())
	if result.String() == "" {
		return errors.New("请先获取验证码")
	}
	if result.String() != verification {
		return errors.New("验证码不正确，请重新输入")
	}
	return nil
}

// ChangePassword 修改密码
func (s *serviceUser) ChangePassword(user string, password string) bool {
	err := backstage_dao.ChangPassword(user, password)
	if err != nil {
		return false
	}
	return true
}

// FindAll 查询用户总数
func (s *serviceUser) FindAll() int {
	num, _ := g.DB().Model("user").Count()
	g.Log("查询所有")
	return num
}

// FindAllUser 查询所有，分页查询
func (s *serviceUser) FindAllUser(users *backstage_model.UserFind) ([]*backstage_model.AllUser, int, error) {
	res, num, err := backstage_dao.FindAllUser(users)
	if err != nil {
		return nil, 0, err
	}
	return res, num, nil
}

// UpdateUser 更新用户
func (s *serviceUser) UpdateUser(user *backstage_model.UpdateUser) error {
	if user.UserName != "" {
		var userOne *backstage_model.UpdateUser
		// 根据用户ID查询单个的
		err := g.DB().Model("user").Where("user", user.User).Scan(&userOne)
		if err != nil {
			return err
		}
		if userOne.UserName != user.UserName {
			err = backstage_dao.UserNameExist(user.UserName)
			if err != nil {
				return err
			}
		}
	}
	_, err := g.DB().Model("user").Data(user).Where("user", user.User).OmitEmpty().Update()
	return err
}

// ChangeStatus 禁用用户
func (s *serviceUser) ChangeStatus(user *backstage_model.ChangeStatus) error {
	_, err := g.DB().Model("user").Data(g.Map{"user_state": user.UserState}).Where("user", user.User).OmitEmpty().Update()
	return err
}

// ChangeListStatus 批量禁用用户
func (s *serviceUser) ChangeListStatus(users *backstage_model.ChangeListStatus) error {
	_, err := g.DB().Model("user").Data(g.Map{"user_state": "0"}).OmitEmpty().Where("user IN(?)", users.User).Update()
	return err
}
