#encoding=UTF-8
require 'json'
require 'rest-client'
class Order < ActiveRecord::Base
    has_paper_trail
    self.table_name = 'orders'
    validates_presence_of :wx_user_id,:total_price
    validates :order_id, presence: true, uniqueness: true

    #belongs_to :user, :foreign_key => :user_id
    #belongs_to :wx_user
    belongs_to :depart_record, :foreign_key => :depart

    has_many :order_details
    has_many :base_details
    # has_and_belongs_to_many :products, join_table: :order_details

    before_save :before_save
    after_update :patch_send_product
    #after_create :import_orders

    def after_import_save(record)
        # 更新order信息
        od = Order.where("id = ?", self.id).first
        if od.source=="sys"
            od.status="processing"
            od.pay_way="weixinpay"
            od.order_type=0
            od.pick_way=0
            od.has_commission=false
            od.paied_at=od.paied_time.to_i
        end
        wxUser = WxUser.where("id = ?", record[:wx_user_id]).first
        unless wxUser.blank?
            od.depart=wxUser.depart
            od.user_id=wxUser.user_id
        end
        od.save
    end

    def before_save

        unless self.express_company.nil?
            if self.express_company.length>0
                express = ExpressCompany.where("express_company = ?", self.express_company).first
                if !express.blank?
                    self.express_code = express.express_code
                end
            end
        end

        wxUser = WxUser.where("id = ?", self.wx_user_id).first

        if !wxUser.blank?
            self.depart=wxUser.depart
            self.user_id=wxUser.user_id
        end


    end


    scope :所有订单, -> {}
    scope :未支付, -> { where("status=?","unpay") }
    scope :已关闭, -> { where("status=?","closed") }
    scope :处理中, -> { where("status=?","processing") }
    scope :待收货, -> { where("status=?","dispatch") }
    scope :已完成, -> { where("status=?","complete") }



    def patch_send_product
        if  self.status=="processing" && self.source!="sys"
            #发放未发放赠品
            url = "#{CONFIG_FILE["api_host"]}/railsadmin/recharge/award/#{self.id}"
            p url
            open(url)
        end
    end

    def after_update
        test_redis = Redis.new(:host=>"r-wz9dtt12y12ns2b97gpd.redis.rds.aliyuncs.com",:db=>"0",:user=>"root",:password=>"Fohow123!@#")
        redis = Redis.new(:host=>"r-wz9dtt12y12ns2b97gpd.redis.rds.aliyuncs.com",:db=>"0",:user=>"root",:password=>"Fohow123!@#")

        orderKey= format("order_model.GetOrderByOId:%s",self.order_id)
        redis.del(orderKey)
        test_redis.del(orderKey)


    end

    STATUS_ENUM = [["未支付","unpay"],["已关闭","closed"],["待确认","unconfirmed"],["处理中","processing"],["已完成","complete"],["待收货","dispatch"],["已退款","refunded"]]
    TYPE_ENUM = [["普通",0],["秒杀",1],["店长",2],["积分",3],["赠品",4]]
    EXP_ENUM =  []
    DEPART_ENUM= [["部门1",1], ["部门2",2], ["部门3", 3], ["部门4", 4], ["部门5", 5]]

    expressCompanys = ExpressCompany.order("id asc")
    expressCompanys.each do |exp|
        a=[exp.express_company,exp.express_company]
        EXP_ENUM.push(a)
    end

    PAY_WAY_ENUM = [
     ["微信支付","weixinpay"],
     ["通联支付","allinpay"],
     ["提货券支付","balance"],
     ["佣金支付","cash"],
     ["积分支付","cent"],
    ]

    PICK_WAY_ENUM = [
        ["快递运输",0],
        ["门店自提",1],
    ]
    SOURCE_ENUM = [["小程序","xcx"],["公众号","gzh"],["外部系统","sys"]]

    def user_tel
      linkUser = User.where("id = ?", self.user_id).first
      if !linkUser.blank?
        if linkUser.is_black_user
            return linkUser.tel + " 【黑名单】"
        else
            return linkUser.tel
        end
      else
        return "不存在"
      end
    end

    def w_user
        wx_user = WxUser.where("id = ?", self.wx_user_id).first
        if !wx_user.blank?
                return wx_user.nickname
        else
            return "--"
        end
    end


    def merchant 

        tmp = "-"
        prod = Product.where("id = ?", self.product_id).first
        if !prod.blank?

            merchant = Merchant.where("id = ?", prod.merchant_id).first
            if !merchant.blank?
                tmp = merchant.name
            end
        end
        return tmp

    end

    def total_price_format
        total_price_f = self.total_price!=0 ? (self.total_price/100.0) :0
        return total_price_f.to_s
    end

    def paied_price_format
        if !self.pay_way.blank? && !self.paied_price.blank?
            #return 0
            case self.pay_way
            when "weixinpay", "allinpay"
                paied_price_f = self.paied_price!=0 ? ((self.paied_price)/100.0) :0
                return paied_price_f.to_s # + "元"
            when "balance"
                paied_price_f = self.paied_price!=0 ? ((self.paied_price)/100.0) :0
                return paied_price_f.to_s #+ "提货券"
            when "integral"
                paied_price_f = self.paied_price!=0 ? ((self.paied_price)/100.0) :0
                return paied_price_f.to_s #+ "提货券"
            end
        end
        return 0
    end

    def cent_price_format
        paied_price_f = self.cent_price!=0 ? ((self.cent_price)/100.0) :0
        return paied_price_f.to_s #+ "提货券"
    end

    def paied_silver_format
        paied_silver_f = self.paied_silver!=0 ? ((self.paied_silver)/100.0) :0
        return paied_silver_f.to_s
    end

    def dis_amount_format
        dis_amount_f = self.dis_amount!=0 ? ((self.dis_amount)/100.0) :0
        return dis_amount_f.to_s
    end

    def paied_cash_format
        paied_cash_f = self.paied_cash!=0 ? ((self.paied_cash)/100.0) :0
        return paied_cash_f.to_s
    end


    def coupon_price_format
        coupon_price_f = self.coupon_price!=0 ? ((self.coupon_price)/100.0) :0
        return coupon_price_f.to_s
    end


    rails_admin do
        navigation_label '商品管理'
        weight -240
=begin
        configure :products do
            inverse_of :order_details
        end
=end
        list do
            scopes [nil,:未支付,:已关闭,:处理中,:待收货,:已完成]
            filters [:order_id,:status,:pay_way,:receive_time,:wx_user_id,:paied_time,:depart]
            field :id do
                visible false
            end
            field :order_id do
                filterable true
            end
            field :pick_way, :enum do
                enum do
                    PICK_WAY_ENUM
                end
            end
            #field :order_id
            field :order_type, :enum do 
                filterable true
                enum do 
                    TYPE_ENUM
                end
            end
            field :user_id do
              visible false
              filterable true
            end
            field :wx_user_id do
                visible true
                filterable true
            end
            field :w_user
            field :user_tel do
                # visible false
            end
            field :total_price do
                visible false
            end

            field :freight do
                visible true
                label "运费(元)"
                formatted_value do
                    value!=0 ? (value/100.0):0
                end
            end
            field :total_price_format do
                visible true
            end
            field :total_price_format do
                visible true
            end
            field :coupon_price_format
            field :paied_silver_format
            field :dis_amount_format
            field :paied_cash_format
            #field :cent_price_format
            field :paied_price_format do
                visible true
            end
            field :trade_no do
                visible false
            end
            field :status, :enum do
                enum do 
                    STATUS_ENUM
                end
            end

            field :pay_way, :enum do 
                enum do 
                    PAY_WAY_ENUM
                end
            end
            field :source, :enum do
                visible false
                enum do
                    SOURCE_ENUM
                end
            end
            field :paied_at do
                formatted_value do
                    (value == 0 || value == nil) ? Time.at(0) : Time.at(value)
                end
            end
            field :paied_time do
                visible false
            end
            field :contact
            field :tel 
            field :address
            field :express_company
            field :express_order_no
            field :dispatch_time
            field :receive_time do
                # visible false
            end
            field :order_remark do
                visible false
            end
            #field :order_details
            field :remark
            field :depart do
                visible false
                filterable true
            end
            field :depart_record
            field :pv do
                formatted_value do # used in form views
                    value.to_f / 100
                end
            end
            field :created_at do
                visible false
            end
        end

        show do
            field :id
            field :order_id
            field :pick_way, :enum do
                enum do
                    PICK_WAY_ENUM
                end
            end
            field :w_user
            field :wx_user_id
            field :freight do
                visible true
                label "运费(元)"
                formatted_value do
                    value!=0 ? (value/100.0):0
                end
            end
            field :coupon_price_format
            #field :cent_price_format
            field :paied_silver_format
            field :dis_amount_format
            field :paied_cash_format
            field :paied_price_format
            field :buy_price
            field :trade_no
            field :status, :enum do
                enum do 
                    STATUS_ENUM
                end
            end
            field :pay_way, :enum do 
                enum do 
                    PAY_WAY_ENUM
                end
            end
            field :source, :enum do
                enum do
                    SOURCE_ENUM
                end
            end
            field :paied_at do
                formatted_value do
                    (value == 0 || value == nil) ? Time.at(0) : Time.at(value)
                end
            end
            field :tel 
            field :address
            field :contact
            field :express_company
            field :express_order_no
            field :remark
            field :order_remark
            field :dispatch_time
            field :receive_time
            field :depart do
                visible false
                filterable true
            end
            field :pv do
                formatted_value do # used in form views
                    value.to_f / 100
                end
            end
            field :depart_record
            field :order_details
            field :created_at
            field :updated_at
        end 
        
         edit do 
            field :order_id
            field :pick_way, :enum do
                enum do
                    PICK_WAY_ENUM
                end
            end
            field :wx_user_id
            field :user_id
            field :total_price
            field :paied_price
            field :paied_at
            field :buy_price
            field :paied_price
            field :cent_price
            field :freight
            field :trade_no
            field :status, :enum do
                enum do 
                    STATUS_ENUM
                end
            end
            field :pay_way, :enum do 
                enum do 
                    PAY_WAY_ENUM
                end
            end
            field :source, :enum do
                enum do
                    SOURCE_ENUM
                end
            end
            field :order_type, :enum do
                enum do
                    TYPE_ENUM
                end
            end
            field :tel 
            field :address
            field :contact

            #field :express_company
            field :express_company, :enum do
                enum do
                    EXP_ENUM
                end
            end
            field :express_order_no
            field :remark
            field :order_remark
            field :dispatch_time
            field :pv
            # field :depart
           # field :products

         end

        export do
            include_all_fields
            field :freight do
                visible true
                label "运费(元)"
                formatted_value do
                    value!=0 ? (value/100.0):0
                end
            end
            field :status, :enum do
                enum do
                    STATUS_ENUM
                end
            end
            field :pay_way, :enum do
                enum do
                    PAY_WAY_ENUM
                end
            end
            field :source, :enum do
                enum do
                    SOURCE_ENUM
                end
            end
            field :paied_at do
                formatted_value do
                    (value == 0 || value == nil) ? Time.at(0) : Time.at(value)
                end
            end
        end

    end 

end

