package dao

import (
	"crypto/md5"
	"demo/configs"
	"demo/data/domain"
	"demo/share"
	"fmt"
	"math/big"
	"strconv"
)

func Logins(username, password, t string) (domain.User, error) {
	user := domain.User{}
	var err error
	fmt.Println("username", username, "password", password)
	hash := md5.New()
	hash.Write([]byte("kkc-" + password))

	pwd := Md5_KKC(password)
	fmt.Println("678", username, pwd, t)
	//md5摘要
	if t == "email" {
		_, err = configs.Engine.Table("user").Where("email = ?", username).Where("password = ?", pwd).Get(&user)
	} else if t == "phone" {
		_, err = configs.Engine.Table("user").Where("phone = ?", username).Where("password = ?", pwd).Get(&user)
	}

	if err == nil {
		return user, err
	}
	return domain.User{}, err
}
func SendSms(matched bool, username string) string {
	mins := big.NewInt(100000)
	maxs := big.NewInt(999999)
	randomNum := share.RandomInt(mins, maxs)
	if matched {
		//bools, err = configs.Engine.Table("user").Where("username = ?", username).Exist(&user)

		share.SendMail(username, strconv.Itoa(int(randomNum.Int64())))

	} else {
		share.SendSms(strconv.Itoa(int(randomNum.Int64())), username)
	}
	return randomNum.String()
}

func SaveNewUser(user domain.User) (domain.User, error) {
	insert, err := configs.Engine.Table("user").Insert(user)
	if err != nil {
		return user, err
	}
	if insert > 0 {
		configs.Engine.Select("id").Where("phone = ?", user.Phone).Get(&user)
		fmt.Println("user666:", user)
	}

	return user, nil
}
func GetUserByPhoneOrEmail(phone, email string) (bool, error) {
	var user = domain.User{}
	_, err := configs.Engine.Select("id").Where("phone = ?", phone).Or("email = ?", email).Get(&user)
	if err != nil {
		fmt.Println("err:", err)
	}
	return user.Id > 0, err
}

// 判断手机号数量
func ExistsPhone(phone string) (bool, error) {
	count, err := configs.Engine.Table("user").Where("phone = ?", phone).Count()
	if err != nil {
		return false, err
	}
	return count > 0, nil
}

func saveUser(username, password, code, phone string) bool {
	return true

}

func Md5_KKC(str string) string {
	hash := md5.New()
	hash.Write([]byte("kkc-" + str))
	return fmt.Sprintf("%x", hash.Sum(nil))
}

func SetName(id int, newName string) (domain.User, error) {
	user := domain.User{}
	_, err := configs.Engine.Table("user").Where("id = ?", id).Get(&user)
	if err != nil {
		return user, err
	}
	user.Name = newName
	_, err = configs.Engine.Table("user").ID(id).Update(user)
	if err != nil {
		return user, err
	}
	return user, nil
}
