# encoding: utf-8
class AdItem < ActiveRecord::Base
  has_paper_trail
  self.table_name = "ad_items"
  belongs_to :ad_position
  after_destroy :after_destroy
  validates :ad_position_id, :name, :img, presence: true
  attr_accessor  :v_img

  IMG_STORE_PATH = "ad_item" 

  URL_TYPE_ENUM = [["内部链接",0],["外部链接",1],["类别链接",2]]
  
  rails_admin do
    navigation_label '广告渠道管理'
    weight -500
    parent AdPosition
    list do
      filters [:ad_position,:name, :state,:expired_at]
      field :id
      field :ad_position
      field :name
      field :img do
        formatted_value do
            bindings[:view].tag(:img, {:src => bindings[:object].get_img,
              :style => 'width: 100px;height: 100px;cursor: pointer;display: block;max-width: 100px;',
              :onClick => "javascript:window.open('#{bindings[:object].get_img}')"})
          
        end
      end
      field :click_url
      field :url
      field :url_type, :enum do
          enum do 
              URL_TYPE_ENUM
          end
      end
      field :click_times
      field :show_times      
      field :expired_at
      field :state
      field :sort
      field :created_at
      field :updated_at
    end

    show do
      field :id
      field :ad_position
      field :name
      field :img do
        formatted_value do
            bindings[:view].tag(:img, {:src => bindings[:object].get_img,
              :style => 'width: 100px;height: 100px;cursor: pointer;display: block;max-width: 100px;',
              :onClick => "javascript:window.open('#{bindings[:object].get_img}')"})
          
        end
      end
      field :click_url
      field :url
      field :url_type, :enum do
          enum do 
              URL_TYPE_ENUM
          end
      end
      field :click_times
      field :show_times      
      field :expired_at
      field :state
      field :sort
      field :created_at
      field :updated_at
    end

    edit do
      field :ad_position
      field :name
      field :v_img, :file_upload do
        pretty_value do
          bindings[:view].tag(:img, {:src => bindings[:object].get_img, :class => 'preview'})
        end        
      end
      field :click_url
      field :url
      field :url_type, :enum do
          enum do 
              URL_TYPE_ENUM
          end
      end
      field :expired_at
      field :state
      field :sort            
    end
  end

  def v_img=file
    unless file.blank?
      clear_img
      file_name = "#{UUID.new.generate[0...8].downcase}.jpg"
      file_path = "#{IMG_STORE_PATH}/#{file_name}"
      Ali::Oss.store(Ali::Oss::BUCKET_NAME_PUBLIC_READ, file_path, file.read)
      self.img = file_path
      self.save
    end
  end

  def clear_img
    file_path = "#{self.img}"
    Ali::Oss.delete_object(Ali::Oss::BUCKET_NAME_PUBLIC_READ, file_path)
  end

  def get_img
    url = "http://#{Ali::Oss::CDN_URL_FOR_HOST}/#{self.img}"
    return url
  end

  def after_destroy
    clear_img    
  end
end
