namespace :copy_attachment_files do
  desc "copy_attachment_files to out path"
  task done: :environment do
    cp_path = ENV['path'] || "/home/pdl/cp_files"
    container_type = ENV['_type']
    next if container_type.blank?
    Dir.mkdir(cp_path) unless Dir.exist?(cp_path)
    attachments = Attachment.where(container_type: container_type)
    attachments.each do |file|
      file_path = File.join(file.disk_directory.to_s, file.disk_filename.to_s)
      next unless File.exist?("#{Rails.root.to_s}/files/#{file_path}")
      dir_path_year = "#{cp_path}/#{file.disk_directory.to_s.split("/")[0]}"
      Dir.mkdir(dir_path_year) unless Dir.exist?(dir_path_year)
      dir_path = "#{cp_path}/#{file.disk_directory}"
      Dir.mkdir(dir_path) unless Dir.exist?(dir_path)
      puts "cp #{Rails.root.to_s + File.join("/files/", file_path)} #{dir_path}"
      system("cp #{Rails.root.to_s + File.join("/files/", file_path)} #{dir_path}")
    end
  end

  task memo: :environment do
    cp_path = ENV['path'] || "/home/pdl/cp_files"
    memos = Memo.where("content like '%/attachments/send_file/%'")
    att_ids = []
    memos.each do |memo|
      # 附件的格式为（/api/attachments/ + 附件id）的形式，提取出id进行附件属性关联，做附件访问权限控制
      att_ids += memo.content.to_s.scan(/\(\/attachments\/send_file\/.+\)/).map{|s|s.match(/\d+/)[0]}
      att_ids += memo.content.to_s.scan(/\/attachments\/send_file\/.+\"/).map{|s|s.match(/\d+/)[0]}
      att_ids += memo.content.to_s.scan(/\/attachments\/send_file\/\d+/).map{|s|s.match(/\d+/)[0]}
    end
    if att_ids.present?
      attachments = Attachment.where(id: att_ids)
      attachments.each do |file|
        file_path = File.join(file.disk_directory, file.disk_filename)
        dir_path_year = "#{cp_path}/#{file.disk_directory.to_s.split("/")[0]}"
        Dir.mkdir(dir_path_year) unless Dir.exist?(dir_path_year)
        dir_path = "#{cp_path}/#{file.disk_directory}"
        Dir.mkdir(dir_path) unless Dir.exist?(dir_path)
        puts "cp #{Rails.root.to_s + File.join("/files/", file_path)} #{dir_path}"
        system("cp #{Rails.root.to_s + File.join("/files/", file_path)} #{dir_path}")
      end
    end
  end
end