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
  end
end
