require 'rubygems'
require 'zip'

class Competition::ZipWorkFileService

  attr_reader :competition_users, :path, :file_index

  def initialize(competition_users, path, file_index = nil)
    @competition_users = competition_users
    @path = path
    @file_index = file_index
  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).to_s.encode('UTF-8')
    file_count =0
    Zip::File.open(zip_file, Zip::File::CREATE) do |attach_zip|
      if @competition_users.present?
        competition_info = @competition_users.last.competition_info
        @competition_users.each do |c_user|
          next if c_user.attachments.blank?
          c_user.attachments.each_with_index do |attach, index|
            # Rails.logger.info("########—————@file_index==#{@file_index},#{index},#{@file_index.to_i != index + 1}")
            next if @file_index.present? && @file_index.to_i != index + 1
            file_count += 1
            # attach = c_user.attachments.last
            attach_local_path = "#{Rails.root}/files/#{attach.disk_directory}/#{attach.disk_filename}"
            attach_filename = "#{c_user.id}_#{c_user.leader}_#{attach.filename}"
            attach_filename = "#{file_count}_#{c_user.ext3}.#{attach.filename.split(".").last}" if competition_info.identifier.to_s.downcase.include?("kxsysj-2024-2")
            begin
              attach_zip.add(attach_filename.to_s.encode('UTF-8'), attach_local_path)
            rescue => ex
              Rails.logger.error("########—————————————2222222#######" + ex.message)
            end
          end
        end
      end
    end
    Rails.logger.info("########—————Competition::ZipWorkFileService.file_count==#{file_count}")
    zip_file
  end

end