package service

import (
	"time"

	"SSO/enums"
	"SSO/models"
	"SSO/utils"
)

func IsMobileRegister(mobile string) bool {
	var count int
	err := readUserDb.
		Model(&models.AdminUser{}).
		Where("mobile = ?", mobile).
		Count(&count).
		Error
	if err != nil {
		utils.ErrorLog("判断手机号是否被注册时失败: %v", err)
		return true
	}
	return count > 0
}

func RegisterSuperAdmin(mobile string, password string) (*models.AdminUser, *enums.SGJError) {
	tx := writeUserDb.Begin()
	now := time.Now().Unix()
	admin := models.AdminUser{
		Mobile:       mobile,
		Password:     password,
		IsSuperAdmin: true,
		Status:       1,
		CreateTime:   now,
		ModifyTime:   now,
	}
	registerSuccess := false
	if createAdminErr := tx.Create(&admin).Error; createAdminErr != nil {
		utils.ErrorLog("创建 AdminUser 失败：%v", createAdminErr)
		tx.Rollback()
	} else {
		registerSuccess = true
	}
	tx.Commit()
	if registerSuccess == true {
		return &admin, nil
	} else {
		return nil, &enums.SGJError{Code: enums.ErrorCodeRegisterFail}
	}
}

func ModifyPassword(mobile string, newPwd string) error {
	tx := writeUserDb.Begin()
	if err := tx.Exec("UPDATE sgj_user_admin SET password = ?, mtime = ? WHERE mobile = ?", newPwd, time.Now().Unix(), mobile).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}
