#==============================================================================
# ■ 附加状态后 普通攻击消耗SP
#------------------------------------------------------------------------------
#  使用方法:在状态名字里写[SP消费 xxx]来使用
#   例: 毒[SP消费 50]    => 每次普通攻击消耗50SP
#        沉默[SP消费 50%] => 每次普通攻击消耗一半SP
#   备注:有多个状态时,优先计算百分比扣除,再计算定值扣除。
#         多个百分比扣除会取最大百分比。
#==============================================================================

class RPG::State
  
  REG_SP_COST_STATE = /\[SP消费[ ]*(\d+%?)\]/i
  
  alias name_for_sp_cost_state name
  def name
    name_for_sp_cost_state.gsub(REG_SP_COST_STATE, '')
  end

  def sp_cost_state?
    name_for_sp_cost_state =~ REG_SP_COST_STATE
  end
  
  def sp_cost_percentage?
    (name_for_sp_cost_state =~ REG_SP_COST_STATE) ? $1.include?("%") : false
  end
  
  def sp_cost
    (name_for_sp_cost_state =~ REG_SP_COST_STATE) ? $1.gsub("%", '').to_i : 0
  end
  
end

class Scene_Battle
  #--------------------------------------------------------------------------
  # ● 生成基本行动结果
  #--------------------------------------------------------------------------
  alias make_basic_action_result_for_sp_cost make_basic_action_result
  def make_basic_action_result
    # 攻击的情况下
    if @active_battler.current_action.basic == 0
      # 消耗 SP
      sp_cost_states = @active_battler.states.map{|i|$data_states[i]}.select{|s|s.sp_cost_state?}
      if !sp_cost_states.empty?
        # 百分比消耗
        sp_percentage_states = sp_cost_states.select{|s|s.sp_cost_percentage?}
        if !sp_percentage_states.empty?
          max_cost_percentage = sp_percentage_states.sort_by{|s|s.sp_cost}.first.sp_cost
          max_cost_percentage = [max_cost_percentage.to_i, 100].min
          @active_battler.sp = @active_battler.sp * (100 - max_cost_percentage) / 100
        end
        # 固定值消耗
        sp_states = sp_cost_states - sp_percentage_states
        if !sp_states.empty?
          @active_battler.sp -= sp_states.collect{|s|s.sp_cost}.inject{|s,n|s+n}
        end        
      end
    end
    make_basic_action_result_for_sp_cost
  end
end