#
#= 顧客／仕入先の統一IF用
#
module Comm::Module::Model::UnifiedIF
  module Partners
    def update_payment_condition(cur_group, payment_params)
      if cur_group.payments.length > 1
        logger.debug("good through")
      elsif cur_group.payments.length == 1
        payment = cur_group.payments.first
        payment.update_attributes!(payment_params)
        MasterRevision.up_rev_number(payment.class.name.tableize)
      else
        cur_group.payments.create(payment_params)
        MasterRevision.up_rev_number(cur_group.payments.first.class.name.tableize)
      end
    end
    
    def destroy_payment_condition(cur_group)
      if cur_group.payments.length > 1
        logger.debug("good through")
      elsif cur_group.payments.length == 1
        table_name = cur_group.payments.first.class.name.tableize
        cur_group.payments.destroy_all
        MasterRevision.up_rev_number(table_name)
      end
    end
  end
  
  module Common
    def extract_shared_params(from, to, to_model, excludes=nil)
      Rails.logger.debug("from: "+from.inspect)
      Rails.logger.debug("to: "+to.inspect)
      column_names = to_model.column_names
      excludes = excludes ? excludes : ['id', 'disp_sort', 'note', 'invalid_flag_code', 'deleted_at', 'created_at', 'updated_at']
      from.each do |key, val|
        if column_names.include?(key) && !excludes.include?(key)
          to[key] = val
        end
      end
    end
    
    def fill_disp_sort(params, klass=self.class)
      if params[:disp_sort].blank?
        max_disp = klass.maximum(:disp_sort)
        params[:disp_sort] = max_disp.to_i + 1 if max_disp
      end
    end
    
    def fill_disp_sort_eager(params)
      if params.include?(:disp_sort) && params[:disp_sort].blank?
        tablename = self.class.name.tableize
        ars = self.class.find_by_sql("SELECT MIN(T0.disp_sort) + 1 AS min_blank FROM #{tablename} AS T0 LEFT JOIN #{tablename} AS T1 ON T0.disp_sort + 1 = T1.disp_sort WHERE T1.disp_sort IS NULL")
        if ars.length > 0
          Rails.logger.debug("min_blank: "+ars.first.min_blank.inspect)
          params[:disp_sort] = ars.first.min_blank
        end
      end
    end
  end
end