class Product < ActiveRecord::Base
    has_paper_trail
    self.table_name = 'products'
    belongs_to :product_cat, :foreign_key => :category_id
    belongs_to :merchant, :foreign_key => :merchant_id
    validates :name,:buy_price,:price,:category_id,:count,:robo_balance_price, presence: true
    attr_accessor :v_share_img,:get_size_enum,:gross_interest_rate
    after_find :get_size_enum
    TYPE_ENUM = [["直营","direct_sale"]]
    #["代销","user_sale"]
    SIZE_ENUM =  []
    COLOR_ENUM =  []
    def get_size_enum
        SIZE_ENUM.clear
        if SIZE_ENUM.length ==0
            linkSize = ProductAttrConfig.where("product_id=? and size_type='size'",self.id).first
            if !linkSize.blank?
                productAttrs = ProductAttr.where("attr_key_id=?",linkSize.attr_key_id).order("recommend desc")
                productAttrs.each do |attr|
                    a=[attr.name,attr.id]
                    SIZE_ENUM.push(a)
                end
            end
        end

        COLOR_ENUM.clear
        if COLOR_ENUM.length==0
            linkColor = ProductAttrConfig.where("product_id=? and size_type='color'",self.id).first
            if !linkColor.blank?
                productColorAttrs = ProductAttr.where("attr_key_id=?",linkColor.attr_key_id).order("recommend desc")
                productColorAttrs.each do |color_attr|
                    b=[color_attr.name,color_attr.id]
                    COLOR_ENUM.push(b)
                end
            end
        end
    end

    IMG_STORE_PATH = "product"

    def size_name
        linkSize = ProductAttr.where("id = ?", self.size_id).first
        if !linkSize.blank?
            return linkSize.name
        else
            return "-"
        end
    end

    def color_name
        linkColor = ProductAttr.where("id = ?", self.color_id).first
        if !linkColor.blank?
            return linkColor.name
        else
            return "-"
        end
    end

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

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

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

    def after_destroy
        clean_share_img
    end

    def gross_interest_rate
        rate = 0
        if self.buy_price != 0 && self.price != 0
            rate = (( self.price.to_f - self.buy_price.to_f )/self.buy_price.to_f)*100
        end 
        return ((rate*100).round.to_f/100).to_s + "%"
    end

    rails_admin do 
        navigation_label '商品管理'
        weight -240

        list do
            filters [:id,:detail,:status,:name]
            field :id
            field :merchant_id
            field :merchant
            field :name do
                filterable true
            end
            field :ptype, :enum do
              enum do 
                TYPE_ENUM
              end
            end 
            #field :category_id
            field :product_cat
            field :detail
            field :price do
                label "现金价格（元）"
                formatted_value do # used in form views
                    value.to_f / 100
                end
            end
            field :robo_balance_price
            field :user_sale_price
            field :buy_price
            field :gross_interest_rate
            field :count
            field :recommend
            field :status
            #field :is_support_poor
            field :virtual_sold_count
            field :purchase_limit_count
            field :share_img do 
              visible false
                formatted_value do
                bindings[:view].tag(:img,{:src => bindings[:object].get_share_img,
                    :style => 'width: 100px;height: 100px;cursor: pointer;display: block;max-width: 100px;',
                    :onClick => "javascript:window.open('#{bindings[:object].get_share_img}')"})
                end
            end
            field :seckill_price do
                label "秒杀显示原价（元）"
                formatted_value do # used in form views
                    value.to_f / 100
                end
            end
            field :is_only_new
            field :video_state
            field :size_name
            field :color_name
            field :relate_product_id
            field :show_flag
            field :created_at
            field :updated_at
        end

        show do
            field :id
            field :merchant_id
            field :merchant
            field :name
            field :ptype, :enum do
              enum do 
                TYPE_ENUM
              end
            end
            #field :category_id
            field :product_cat
            field :detail
            field :price do
                label "现金价格（元）"
                formatted_value do # used in form views
                    value.to_f / 100
                end
            end
            field :robo_balance_price
            field :buy_price
            field :user_sale_price
            field :count
            field :recommend
            field :status
            #field :is_support_poor
            field :virtual_sold_count
            field :purchase_limit_count
            field :share_content
            # field :share_img do 
            #     formatted_value do
            #     bindings[:view].tag(:img,{:src => bindings[:object].get_share_img,
            #         :style => 'width: 100px;height: 100px;cursor: pointer;display: block;max-width: 100px;',
            #         :onClick => "javascript:window.open('#{bindings[:object].get_share_img}')"})
            #     end
            # end
            field :seckill_start
            field :seckill_end
            field :seckill_price do
                label "秒杀显示原价（元）"
                formatted_value do # used in form views
                    value.to_f / 100
                end
            end
            field :deliver_stop_at
            field :deliver_start_at
            field :is_only_new
            field :specification
            field :no_delivery_area
            field :video_state
            field :video_url
            field :size_name
            field :color_name
            field :relate_product_id
            field :show_flag
            field :created_at
            field :updated_at
        end

        edit do 
            field :name
            field :ptype, :enum do
              enum do 
                TYPE_ENUM
              end
            end
            #field :category_id
            field :merchant_id
            field :product_cat
            field :detail, :ck_editor
            field :price
            field :robo_balance_price
            field :buy_price
            field :user_sale_price
            field :count
            field :recommend
            field :status
            #field :is_support_poor
            field :virtual_sold_count
            field :purchase_limit_count
            field :share_content
=begin
            field :v_share_img, :file_upload do
                 pretty_value do
                     bindings[:view].tag(:img, {:src => bindings[:object].get_share_img, :class => 'preview'})
                end
            end
=end
            field :seckill_start
            field :seckill_end
            field :seckill_price
            field :deliver_stop_at
            field :deliver_start_at
            field :is_only_new
            field :specification
            field :no_delivery_area
            field :video_state
            field :video_url
            field :size_id, :enum do
                enum do
                    SIZE_ENUM
                end
            end
            field :color_id, :enum do
                enum do
                  COLOR_ENUM
                end
            end
            field :relate_product_id
            field :show_flag
        end

    end

end