# encoding:utf-8
# 提现失败时，手动操作返回余额
module RailsAdmin
  module Config
    module Actions     

      class CorrectTakecash < RailsAdmin::Config::Actions::Base
            register_instance_option :visible? do
          if not bindings[:object].blank?
            authorized? && bindings[:object].audit_state == 1 && bindings[:object].pay_state==2
          else
            authorized?
          end
        end
        # We want the action on members, not the Users collection
        register_instance_option :member do
          true
        end

        register_instance_option :link_icon do
          'icon-share'
        end
        # You may or may not want pjax for your action
        register_instance_option :pjax? do
          false
        end

        register_instance_option :controller do
          Proc.new do
            n = "提现冲正成功。"
            if @object.audit_state == 1 && @object.pay_state==2
              #先判断是否已经返回余额
              rId = @object.order_id + "_COR"
              source = "correct"
              wxUid = @object.wx_uid
              existBalance = CashBalance.where(" source = ? and relate_id = ? and wx_uid = ?", source, rId, wxUid).first
              if !existBalance.nil?
                n = "已成功返回余额。"
              else
                #返回余额
                @cashBalance = CashBalance.new
                @cashBalance.wx_uid = wxUid
                @cashBalance.count = @object.count
                @cashBalance.source = source
                @cashBalance.relate_id = rId
                @cashBalance.remark = "提现-冲正"
                begin
                  @cashBalance.save
                rescue Exception => e
                  p "************ correct takecash return cashBalance save fail . #{e.to_s}"
                  n = "提现冲正失败，请稍后重试！"
                end
              end
            else
              n = "此状态不支持操作。"
            end                  
            # redirect_to back_or_index, notice: "已审批!"
            redirect_to :back, notice: "#{n}"
          end
        end
      end

    end
  end
end