# encoding: utf-8
class AdminUser < ActiveRecord::Base
  has_paper_trail

  SUPER_ADMIN = Rails.env == "production" ? "super@fh666.com" : "super@fohow.com"

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :recoverable and :omniauthable
  devise :database_authenticatable,
    :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model

  has_and_belongs_to_many :admin_roles, :join_table => :admin_roles_admin_users

  rails_admin do
    navigation_label '系统管理'
    weight -20
    configure :admin_roles do
      inverse_of :admin_users
    end

    list do
      filters [:name]
      field :id
      field :name
      field :admin_roles
      field :email
      # field :password
      # field :password_confirmation
      # field :company
      field :created_at
      # field :created_at do
      #   formatted_value do
      #     value.strftime("%Y-%m-%d %H:%m:%S") unless value == 0
      #   end
      # end
      field :updated_at
      field :sign_in_count
      # field :current_sign_in_at
      # field :last_sign_in_at
      # field :current_sign_in_ip
      # field :last_sign_in_ip
    end

    edit do
      field :email, :string
      field :name, :string
      field :password, :password
      field :password_confirmation, :password
      field :admin_roles do
        # 当管理员为超管或有manage_Role权限才能操作 角色列表
        visible do
          perms = bindings[:view].current_admin_user.permissions.collect{ |perm| "#{perm.can}_#{perm.model}"}
          perms.include?("manage_AdminRole") or bindings[:view].current_admin_user.email == SUPER_ADMIN
        end
      end
    end

    show do
      configure :remember_created_at do
        formatted_value do
          value.strftime("%Y-%m-%d %H:%m:%S") unless value == 0
        end
      end
      configure :current_sign_in_at do
        formatted_value do
          value.strftime("%Y-%m-%d %H:%m:%S") unless value == 0
        end
      end
      configure :last_sign_in_at do
        formatted_value do
          value.strftime("%Y-%m-%d %H:%m:%S") unless value == 0
        end
      end
    end
  end



  #def name
  #  email
  #end

  def permissions
    _permissions = []
    self.admin_roles.each do |role|
      role.admin_permissions.each do |permission|
        _permissions << permission
      end
    end
    _permissions
  end


end
