module Register
  class BaseForm < ::BaseForm
    include ActiveModel::Model

    private
    def check_login(login, user=nil)
      login = strip(login)
      raise LoginError, "登录名格式有误" unless login =~ CustomRegexp::LOGIN

      login_exist = Owner.exists?(login: login) || ReversedKeyword.check_exists?(login)
      if user.present? 
        raise LoginError, '登录名已被使用' if login_exist && login != user&.login
      else
        raise LoginError, '登录名已被使用' if login_exist
      end
    end

    def check_mail(mail, user=nil)
      mail = strip(mail)
      raise EmailError, "邮件格式有误" unless mail =~ CustomRegexp::EMAIL
  
      mail_exist = Owner.exists?(mail: mail)
      if user.present? 
        raise EmailError, '邮箱已被使用' if mail_exist && mail != user&.mail
      else
        raise EmailError, '邮箱已被使用' if mail_exist
      end
    end
    
    def check_phone(phone, user=nil)
      phone = strip(phone)
      raise PhoneError, "手机号格式有误" unless phone =~ CustomRegexp::PHONE

      phone_exist = Owner.exists?(phone: phone)
      if user.present?
        raise PhoneError, '手机号已被使用' if phone_exist && phone != user&.phone
      else
        raise PhoneError, '手机号已被使用' if phone_exist
      end 
    end

    def check_password(password)
      password = strip(password)
      raise PasswordFormatError, "8~20位密码，支持字母数字和符号" unless password =~ CustomRegexp::PASSWORD
    end

    def check_verifi_code(verifi_code, code)
      code = strip(code)
      return if code == "123123" && EduSetting.get("code_debug") # 万能验证码，用于测试
      return if EduSetting.get("is_local") == "true" # 本地版不需要验证码

      raise VerifiCodeError, "验证码不正确" if verifi_code&.code != code
      raise VerifiCodeError, "验证码已失效" if !verifi_code&.effective?
    end
    
  end
end
