require 'rubygems'
require 'zip'

class Competition::ZipEnrollTemplateService

  attr_reader :competition_users, :path, :file_attr_name

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

  def filename
    export_name = @file_attr_name == "bm_file_id" ? "bm审查文件-#{Time.now.strftime('%Y%m%d%H%M%S')}" : "报名资料-#{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|
          file_uuid = @file_attr_name.nil? ? c_user.send("enroll_template_id") : c_user.send("#{@file_attr_name}")
          attach = Attachment.where_id_or_uuid(file_uuid).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