class MerchantUserRelation < ActiveRecord::Base
    has_paper_trail
    self.table_name = "merchant_user_relations"
    belongs_to :user, :foreign_key => :user_id
    belongs_to :merchant, :foreign_key => :merchant_id
    validates :user_id, :merchant_id, :manage_product_ids, presence: true

    validate :check_user_no_more_merchant, :on => :create
    validate :check_merchant_is_exist

    def check_user_no_more_merchant
      sql = "select * from merchant_user_relations where user_id = #{self.user_id} and is_effect = 1"
      cs = MerchantUserRelation.find_by_sql(sql).first
      if !cs.blank?
          self.errors.add(:user_id,"暂不支持一个用户对应多个商家")
      end
    end

    def check_merchant_is_exist
      sql = "select * from merchants where id = #{self.merchant_id}"
      merchant = Merchant.find_by_sql(sql).first
      if merchant.blank?
        self.errors.add(:merchant_id,"该商家信息不存在")
      end
    end

    def wx_user
      wxUser = WxUser.where("user_id = ?", self.user_id).first
      if !wxUser.blank?
        return wxUser.nickname
      else
        return "不存在"
      end
    end


    rails_admin do 

        navigation_label '商品管理'
        weight -100

        list do 
          filters [:id,:user,:merchant]
          field :id      
          field :user_id
          field :user
          field :wx_user
          field :merchant_id
          field :merchant 
          field :is_effect  
          field :is_super_admin
          field :manage_product_ids  
          field :created_at
        end

        show do
          field :id      
          field :user_id
          field :user
          field :wx_user
          field :merchant_id
          field :merchant
          field :is_effect  
          field :is_super_admin
          field :manage_product_ids   
          field :created_at
          field :updated_at
        end

        edit do     
          field :user_id
          field :merchant_id
          field :is_effect
          field :is_super_admin
          field :manage_product_ids do
            label "管理的商品ids(0表示所有商品,不填0则商品id之间用逗号隔开)"
          end
        end
    end
end