module CommLogistics::Base::Model
  #
  #在庫関連の上位クラス(Sale, Purchase...)
  #
  class SuperiorStock < Superior
    self.abstract_class = true
    include CommLogistics::Modules::MngStock
    include CommLogistics::Modules::DateUtil
    
    def update_parent_rels(main)
      pid = main['accept_order_id'].to_i
      if pid > 0
        rels = AcceptOrder.get_valid_rels(pid)
        rels_comp_total_quantity = 0
        aar = AcceptOrder.find(pid)
        rels.each do |rel|
          rels_comp_total_quantity = rels_comp_total_quantity + eval("#{rel.table_name.classify}.get_comp_total_quantity(#{rel.record_id}, aar)") unless rel.table_name == 'orders'
        end
        #そもそも受注処理で合計本数が0で登録された場合を考慮する。この場合記録するのは百分率
        rels_comp_total_quantity = rels.length==0 ? 0 : (rels_comp_total_quantity==0 ? 100 : 50) if aar.rels_total_quantity==0
        aar.update_attribute(:rels_comp_total_quantity,rels_comp_total_quantity)
        #AcceptOrder.update(pid, :rels_comp_total_quantity => rels_comp_total_quantity)
      end
    end
    
    def post_checks
      emsg = Stock.check_quantities
      if emsg
        @additional ||= {}
        @additional["error"] ||= ""
        @additional["error"] << "1"
        raise UserOperationError, emsg
      end
      super
    end
    
    #== 締めチェック
    def parameter_checks(main, details)
      closes_checks(main, details)
      super
    end
    def record_checks
      closes_checks(self, nil)
      super
    end
    
    def public_update_stock_info(main, details, is_create=true)
      update_stock_info(main, details, is_create)
    end
  
  private
    #  1,default...締めテーブル
    #  2...........締め日
    #  3...........なし
    def closes_checks(main, details)
      require 'config/site_config'
      $CUTOFF_CHECK_TYPE ||= 1
      case $CUTOFF_CHECK_TYPE
      when 1
        close_table_checks(main, details)
      when 2
        cutoff_date_checks(main, details)
      when 3
        #good through
      else
        close_table_checks(main, details)
      end
    end
    #=== 締めテーブルチェック
    def close_table_checks(main, details)
      closed_date_ar = TransClose.find_close(get_close_table_key)
      unless closed_date_ar
        return
      end
      unless close_table_check_target?(main)
        return
      end
      closed_date = closed_date_ar.close_date
      target_date = get_value_by_name(main, 'target_date').to_date
      if closed_date and closed_date >= target_date
        if User.root_user?(@session[:user_id].to_i)
          Rails.logger.info("[INFO]cutoff error canceled by root user.\n"+main.inspect)
          return
        end
        raise UserOperationError, LOEMJ0014+LOEMD0018+LOEMD0017
      end
    end
    def close_table_check_target?(main)
      #キホン的に完了以外はチェックしない
      #..ということで締め日チェックの方と異なる場合はこちら上書きして
      return cutoff_check_target?(main)
    end
    def get_close_table_key
      #仕入以外はreceivalbesでOK
      return 'receivables'
    end
    #=== 締め日チェック
    def cutoff_date_checks(main, details)
       own_ar = Supplier.own
       cutoff_type = (own_ar.cutoff_type_code || 0)
       cutoff_date_check(main, details, own_ar) unless cutoff_type==MCODE_CUTOFF_NONE #都度払いはチェックしない
    end
    #def cutoff_date_check(main, details, cutoff_date)
    def cutoff_date_check(main, details, par, target_cutoff=nil)
      Rails.logger.debug("\nDEBUG:cutoff_date_check:"+par.inspect)
      unless cutoff_check_target?(main) 
        return
      end
      
      if target_cutoff.blank?
        target_date = get_value_by_name(main, 'target_date').to_date
        cutoff_type = par.cutoff_type_code || 0
        cutoff_day_code = par.cutoff_day_code || ""
        
        target_cutoff = get_target_cutoff(cutoff_type, cutoff_day_code, target_date) 
        Rails.logger.debug("DEBUG:target_date:"+target_date.inspect)
        Rails.logger.debug("DEBUG:cutoff_type:"+cutoff_type.inspect)
        Rails.logger.debug("DEBUG:cutoff_day_code:"+cutoff_day_code.inspect)
        Rails.logger.debug("DEBUG:target_cutoff:"+target_cutoff.inspect)
      end
#      if MCODE_CUTOFF_EOM == cutoff_date
#        #ruby的に末日が-1なのでおきかえ
#        cutoff_date = -1
#        compare_day = target_date.end_of_month.day
#      else
#        compare_day = cutoff_date
#      end
#      Rails.logger.debug("DEBUG:compare:"+compare_day.inspect)
#      Rails.logger.debug("DEBUG:target :"+target_date.inspect)
#      if target_date.day <= compare_day
#        #処理日付 <= 締め日付 そのまま
#        target_month = target_date.month
#      else
#        #処理日付 > 締め日付 翌月の締め日が対象
#        target_month = target_date.month + 1
#      end
#      target_cutoff = Date.new(target_date.year, target_month, cutoff_date)
      
      today = Date.today
      if today > target_cutoff
        cutoff_date_error(main)
      end
    end
    
    def cutoff_check_target?(main)
      #キホン的に完了以外はチェックしない
      if status_complete?(main)
        return true
      end
      return false
    end
    def cutoff_date_error(main)
      if User.root_user?(@session[:user_id].to_i)
        Rails.logger.info("[INFO]cutoff error canceled by root user.<br>"+main.inspect)
        return
      end
      raise UserOperationError, LOEMJ0014+LOEMD0016+LOEMD0017
    end
  end
end