
class Product < ActiveRecord::Base
    has_paper_trail
    self.table_name = 'products'
    #Thread.current[:current_user] = @current_user
    scope :active, -> { where(ptype: "cent_sale") }
    scope :inactive, -> { where(ptype: "direct_sale") }
    belongs_to :product_cat, :foreign_key => :category_id
    belongs_to :product_sale_type, :foreign_key => :sale_zone

    belongs_to :merchant, :foreign_key => :merchant_id
    has_and_belongs_to_many :depart_record

    validates  :product_no,:name,:buy_price,:price,:category_id,:count,:robo_balance_price,:relate_product_id, presence: true
    validate :product_validation
    validates :id, presence: true, uniqueness: true
    validates_numericality_of :pv ,:only_integer => true,:greater_than_or_equal_to => 0, :less_than => 100


    def product_validation
        if self.relate_product_id <= 0
            #主商品默认关联商品
            if self.show_flag
                self.relate_product_id = self.id
            end

            prd = Product.where("id = ?", self.relate_product_id).first
            if prd.blank?
                self.relate_product_id = self.id
            end

            self.save
        end
    end
    attr_accessor :v_share_img,:get_size_enum,:get_color_enum,:gross_interest_rate
    # after_find :get_size_enum
    after_create :after_create
    before_save :before_save
    after_destroy :del_picture
    after_commit :clear_product_cache_after_commit

    def after_create
        #主商品默认关联商品
        if self.show_flag
            self.relate_product_id = self.id
            self.save
        end
    end
    def before_save
        #主商品默认关联商品
        if self.show_flag
            self.relate_product_id = self.id
        end
        if self.size_id.nil?
            self.size_id = 0
        end
        if self.color_id.nil?
            self.color_id = 0
        end
    end

    def del_picture
        # 删除商品图片
        pictures = ProductPicture.find_by_sql("select * from product_pictures where pic_type=0 and product_id = #{self.id}")
        # 创建商品图片
        pictures.each do |u|
            u.delete
        end
    end

    def self.notify_product_cache(product_id)
        return if product_id.blank?
        #清空商品缓存
        url = "#{CONFIG_FILE["api_host"]}/railsadmin/clean_cache/product/#{product_id}"
        p url
        open(url)
    end

    def clear_product_cache
        Product.notify_product_cache(self.id)
    end

    def clear_product_cache_after_commit
        clear_product_cache
    end
    TYPE_ENUM = [["直营","direct_sale"],["店铺专区","shop_sale"],["积分专区","cent_sale"]]
    SIZE_ENUM =  []
    COLOR_ENUM =  []
    def get_size_enum
        SIZE_ENUM.clear
        if SIZE_ENUM.length ==0 && !self.id.nil?
            linkSize = ProductAttrConfig.where("product_id=? and size_type='size'",self.relate_product_id).first
            if !linkSize.blank?
                productAttrs = ProductAttr.where("attr_key_id=? and status=1 ",linkSize.attr_key_id).order("recommend desc")
                productAttrs.each do |attr|
                    a=[attr.name,attr.id]
                    SIZE_ENUM.push(a)
                end
            end
        end
        return SIZE_ENUM
    end

    def get_color_enum
        COLOR_ENUM.clear
        if COLOR_ENUM.length==0 && !self.id.nil?
            linkColor = ProductAttrConfig.where("product_id=? and size_type='color'",self.relate_product_id).first
            if !linkColor.blank?
                productColorAttrs = ProductAttr.where("attr_key_id=? and status=1",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
        return COLOR_ENUM
    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
    end


    rails_admin do

        navigation_label '商品管理'
        weight -240
        list do
            #scopes [:inactive]
            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 :product_no
            #field :category_id
            field :product_cat
            field :product_sale_type
            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 do
                label "零售价（元）"
                formatted_value do
                    value.to_f / 100
                end
            end
            # 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
            #ield :video_state
            field :size_name
            field :color_name
            field :relate_product_id
            field :show_flag
            # field :live
            field :allow_app
            # field :product_cycle
            # field :stock_cycle
            # field :min_purchase
            field :sale_nums
            field :single_purch_limit
            field :package
            field :pv do
                label "pv%"
                formatted_value do # used in form views
                    "#{value}%"
                end
            end
            field :out_nums
            field :key_words
            field :depart_record
            field :created_at
            field :updated_at
        end

        show do
            field :id
            field :merchant_id
            field :merchant
            field :name
            field :name_en
            field :name_ru
            field :name_tw
            # field :ptype, :enum do
            #   enum do
            #     TYPE_ENUM
            #   end
            # end
            field :product_no
            #field :category_id
            field :product_cat
            field :product_sale_type
            field :detail
            field :detail_en
            field :detail_ru
            field :detail_tw
            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 do
                label "零售价（元）"
                formatted_value do
                    value.to_f / 100
                end
            end
            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 :only_delivery_area
            field :video_state
            field :video_url
            field :size_name
            field :color_name
            field :relate_product_id
            field :show_flag
            # field :live
            field :allow_app
            field :single_purch_limit
            field :package
            # field :product_cycle
            # field :stock_cycle
            # field :min_purchase
            field :pv do
                label "pv%"
                formatted_value do # used in form views
                    "#{value}%"
                end
            end
            field :out_nums
            field :silver
            field :use_quan
            field :key_words
            field :depart_record
            field :created_at
            field :updated_at
        end

        edit do
            field :id do
                read_only do
                    bindings[:object].id
                end
            end
            field :name
            field :name_en
            field :name_ru
            field :name_tw
            # field :ptype, :enum do
            #   enum do
            #     TYPE_ENUM
            #   end
            # end
            field :product_no
            #field :category_id
            field :merchant_id
            field :product_cat
            field :product_sale_type
            field :detail, :ck_editor
            field :detail_en, :ck_editor
            field :detail_ru, :ck_editor
            field :detail_tw, :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 :only_delivery_area
            field :video_state
            field :video_url

            field :size_id, :enum do
                enum do
                    bindings[:object].get_size_enum
                end
            end
            field :color_id, :enum do
                enum do
                    bindings[:object].get_color_enum
                end
            end

            field :relate_product_id
            field :show_flag
            # field :live
            field :allow_app
            field :single_purch_limit
            field :package
            # field :product_cycle
            # field :stock_cycle
            # field :min_purchase
            field :pv do
                label "pv%"
            end
            field :out_nums
            field :key_words
            field :silver
            field :use_quan
            field :depart_record
        end

    end

end
