class ManufactureDetail < CommLogistics::Base::Model::Detail
  include Comm::Module::Model::Logging
  has_many :child_details,
           :class_name => 'ManufactureProductDetail',
           :dependent => :destroy,
           :order => 'seq_number'
  belongs_to :manufacture
  named_scope :child, lambda {|id| {:conditions => ["manufacture_id = ?", id]}}
  named_scope :with_parent, :joins => "INNER JOIN `manufactures` ON `manufacture_details`.`manufacture_id` = `manufactures`.`id`"
  
#  named_scope :print, lambda{ |id| {
#    :conditions => ["`order_details`.`order_id` = ?", id],
#    :joins => "LEFT OUTER JOIN `products` ON `products`.id = `order_details`.`product_id`"
#  }}
  class << columns_hash['ubd']
    def type
      :string
    end
  end
  
  def self.check_uniq(hr)
    ars = self.find(:all, :joins => :manufacture, 
      :conditions=>[' `manufacture_details`.id !=? AND `manufacture_details`.product_id=? AND `manufacture_details`.lot_number=? AND `manufacture_details`.serial_number=? AND `manufacture_details`.ubd=? AND `manufactures`.invalid_flag_code=?', hr['id'], hr['product_id'], hr['lot_number'], hr['serial_number'], hr['ubd'], FLAG_OFF]
      )
    return ars.length > 0 ? 0 : 1
  end
  
  def update_children(parent_id = nil, params = {})
    result = true
    mycls =  self.class
    
    1.times do
      olds = mycls.sassign(@parent_key, parent_id).all
      temps = params.partition {|x| x['id'].blank? }
      # 更新
      up_params = temps[1]
      is_update_logging = @children_logging && respond_to?(:log_detail_update)
      up_params.each do |p|
        p.delete('change')
        mpd_params = p['manufacture_product_details']
        mpd_edit = p['manufacture_product_edit']
        p.delete('manufacture_product_details')
        p.delete('manufacture_product_edit')
        ar = olds.get_by_search_val(p['id'].to_i, 'id')
        ar.attributes = p
        log_detail_update(@log_id, ar) if is_update_logging
        unless ar.save
          errors.add_to_base(EMJ0003 + EMD0004 + "(#{self.class.to_s})")
          result = false
          break
        end
        #ここから加工構成
        update_mpd_children(mpd_params, parent_id, ar, mpd_edit)
      end
      unless result
        break
      end
      
      # 登録
      new_params = temps[0]
      is_create_logging = @children_logging && respond_to?(:log_detail_create)
      new_params.each do |p|
        p[@parent_key] = parent_id
        mpd_params = p['manufacture_product_details']
        mpd_edit = p['manufacture_product_edit']
        p.delete('manufacture_product_details')
        p.delete('manufacture_product_edit')
        ar = mycls.new(p)
        unless ar.save
          errors.add_to_base(EMJ0003 + EMD0004 + "(#{self.class.to_s})")
          result = false
          break
        end
        log_detail_create(@log_id, ar) if is_create_logging
        #ここから加工構成
        update_mpd_children(mpd_params, parent_id, ar, mpd_edit)
      end
      unless result
        break
      end
      
      # 削除
      old_ids = olds.extract('id')
      new_ids = params.map {|x| x['id'].to_i }
      del_ids = old_ids - new_ids
      if @children_logging && respond_to?(:log_detail_destroy) && del_ids.length != 0
        del_ids.each do |i|
          ar = olds.get_by_search_val(i, 'id')
          log_detail_destroy(@log_id, ar)
          #ここから加工構成
          update_mpd_children([], parent_id, ar)
        end
      end
      mycls.destroy(del_ids)
    end
    
    return result
  end
  
  def add_mpd_params(params, manufacture_id)
    num = 1
    params.each do |p|
      p['seq_number'] = num
      p['manufacture_id'] = manufacture_id
      num += 1
    end
  end
  
  def update_mpd_children(mpd_params, parent_id, ar, mpd_edit=0)
    detail_id = ar.id
    if mpd_edit==1
      raise UserOperationError, EMJ0003+LOEMD0022+'<br>※'+ar['seq_number'].to_s+"行目" if ManufactureDetail.check_uniq(ar)!=mpd_edit
    end
    mpd = ManufactureProductDetail.new
    mpd.log_id = self.log_id
    mpd.session = self.session
    mpd.children_logging = self.children_logging
    mpd.parent_key = 'manufacture_detail_id'
    add_mpd_params(mpd_params, parent_id)
    mpd.update_children(detail_id, mpd_params)
  end
end