# encoding:utf-8
class Balance < ActiveRecord::Base
  has_paper_trail
  self.table_name = "balances"
  belongs_to :user
  belongs_to :wx_user
  validates_presence_of :user_id, :count, :relate_id, :source
  attr_accessor :remain_sum

  SOURCE_ENUM = [["企业大使兑换", "platform_exchange"],
                 ["兑换商品", "exchange_product"],
                 ["充值", "recharge"],
                 ["店长申请", "shop_applycation"],
                 ["群员购物扣除", "frend_buy"],
                 ["全额退款", "all_refunded"],
                 ["部分退款", "part_refunded"],
                 ["部分退款", "part_refunded"],
                 ["佣金转提货券","cash_to_balance"],
                 ["店长促销赠送","shop_promotion"],
                 ["充值促销赠送","balance_promotion"],
                 ["促销赠送","promotion"]]

  def remain_sum
    b = Balance.where("wx_user_id = ? and id < ?", self.wx_user_id, self.id).last
    if !b.blank?
      return self.count + b.remain_sum
    else
      return self.count
    end
  end
  rails_admin do
    navigation_label '资金管理'
    weight -920

    list do
      items_per_page 10
      filters [:id, :source, :user, :relate_id,:wx_user,:created_at]
      # include_all_fields
      field :id
      field :user
      field :user_id
      field :wx_user
      field :wx_user_id
      field :count do
        formatted_value do
          value.to_f / 100.0
        end
      end
      field :remain_sum do
        formatted_value do
          value.to_f / 100.0
        end
      end
      field :relate_id
      field :source, :enum do
        enum do
          SOURCE_ENUM
        end
      end
      field :remark
      field :created_at
      # field :updated_at
    end

    show do
      field :user_id
      field :wx_user
      field :wx_user_id
      field :count do
        formatted_value do # used in form views
          value.to_f / 100.0
        end
      end
      field :remain_sum do
        formatted_value do
          value.to_f / 100.0
        end
      end
      field :source, :enum do
        enum do
          SOURCE_ENUM
        end
      end
      field :relate_id
      field :remark
      field :created_at
    end

    edit do
      field :user_id
      field :wx_user_id
      field :count do
        label "变动金额，单位(分)"
      end
      field :relate_id
      field :source, :enum do
        enum do
          SOURCE_ENUM
        end
      end
      field :remark
    end
  end
end
