require 'rubygems'
require 'zip'

class Competition::ZipApplyTemplateService

  attr_reader :competition_users, :path

  def initialize(competition_users, path)
    @competition_users = competition_users
    @path = path
  end

  def filename
    export_name = "申请表-#{Time.now.strftime('%Y%m%d%H%M%S')}"
    "#{export_name.strip}.zip"
  end

  def zip
    zip_file = Rails.root.join(@path, filename)
    Zip::File.open(zip_file, Zip::File::CREATE) do |attach_zip|
      if @competition_users.present?
        @competition_users.each do |c_user|
          attach = Attachment.where_id_or_uuid(c_user.ext2).first
          next if attach.blank?
          attach_local_path = "#{Rails.root}/files/#{attach.disk_directory}/#{attach.disk_filename}"
          attach_filename = "#{c_user.id}_#{c_user.leader}_#{attach.filename}"
          begin
            attach_zip.add(attach_filename, attach_local_path)
          rescue => ex
            Rails.logger.error("########—————————————2222222#######" + ex.message)
          end
        end
      end
    end
    zip_file
  end

end