#encoding: utf-8
class AvatarController < ApplicationController

  include ActionView::Helpers::NumberHelper
  #before_filter :set_cache_buster   
  include AvatarHelper
  include ApplicationHelper

  def upload
    # Make sure that API users get used to set this content type
    # as it won't trigger Rails' automatic parsing of the request body for parameters
    unless request.content_type == 'application/octet-stream'
      @source_type = params[:source_type]
      @source_id = params[:source_id]
      @temp_file = params[:img] || params[:avatar][:image]

      if @temp_file.respond_to?(:original_filename)
        @image_file = @temp_file.original_filename
        #image_file.force_encoding("UTF-8") if filename.respond_to?(:force_encoding)
      else
        @image_file=params[:filename]
      end

      @is_direct = params[:is_direct]
      @auth_type = params[:auth_type]


      #base64转换
      img_base64_head = 'data:image/jpeg;base64,'
      if @temp_file && @temp_file.start_with?(img_base64_head)
        @temp_file = StringIO.new(Base64.decode64(@temp_file[img_base64_head.size,@temp_file.size-img_base64_head.size]))
      end

    else
      unless request.raw_post.nil?
        @source_type = params[:source_type]
        @source_id = params[:source_id]
        @temp_file = request.raw_post
        @is_direct = params[:is_direct]
        @auth_type = params[:auth_type]
        if @temp_file.size > 0
          if @temp_file.respond_to?(:original_filename)
            @image_file = @temp_file.original_filename
            #image_file.force_encoding("UTF-8") if filename.respond_to?(:force_encoding)
          else
            @image_file=params[:filename]
          end
          @temp_file = StringIO.new(@temp_file)
        end
      end
    end

    if @temp_file && (@temp_file.size > 0)
      if @temp_file.size > Setting.upload_avatar_max_size.to_i
        @status = 1
        @msg = l(:error_upload_avatar_to_large, :max_size => number_to_human_size(Setting.upload_avatar_max_size.to_i))
      elsif Trustie::Utils::Image.new(@temp_file).image?
        diskfile=disk_filename(@source_type,@source_id)
        if @source_type == 'UserAuthentication'
          diskfile = disk_auth_filename('UserAuthentication', @source_id, @auth_type)
          diskfile1 = diskfile + 'temp'
          File.delete(diskfile1) if File.exist?(diskfile1)
          @urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),auth_filename(@source_id,@auth_type))
        elsif @source_type == 'edu_coop' || @source_type == 'com_coop'
          diskfile = disk_auth_filename(@source_type, @source_id, '')
          diskfile1 = diskfile + 'temp'
          @urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),auth_filename(@source_id,''))
        elsif @source_type == "Platform"
          diskfile = disk_auth_filename(@source_type, @auth_type, "")
          @urlfile='/' << File.join("images","avatars", avatar_directory(@source_type),auth_filename(@auth_type,''))
        else
          @urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),avatar_filename(@source_id,@image_file))
        end

        # 用户头像上传时进行特别处理
        if @is_direct == '1' && (@source_type == 'User' || @source_type == 'Course' || @source_type == 'Project' || @source_type == 'Organization'|| @source_type == 'Contest' || @source_type == 'UserAuthentication'|| @source_type == 'edu_coop' || @source_type == 'com_coop')
          diskfile += "temp"
          @urlfile += "temp"
        end

        logger.info("Saving avatar '#{diskfile}' (#{@temp_file.size} bytes)")
        path = File.dirname(diskfile)
        unless File.directory?(path)
          FileUtils.mkdir_p(path)
        end
        md5 = Digest::MD5.new
        File.open(diskfile, "wb") do |f|
          if @temp_file.respond_to?(:read)
            @temp_file.rewind
            buffer = ""
            while (buffer = @temp_file.read(8192))
              f.write(buffer)
              md5.update(buffer)
            end
          else
            f.write(@temp_file)
            md5.update(@temp_file)
          end
        end

        if @source_type == 'User' || @source_type == 'UserAuthentication' || @source_type == 'edu_coop' ||
            @source_type == 'com_coop' || @source_type == 'Platform' || @source_type == 'Shixun' ||
            @source_type == 'Subject' || @source_type == 'Competition' || @source_type == 'PortalImage' ||
            @source_type == 'Career' || @source_type == 'School' || @source_type == 'SchoolImage'

        elsif @source_type == 'Contest'
          Trustie::Utils::Image.new(diskfile,true).compress(900)
        else
          Trustie::Utils::Image.new(diskfile,true).compress(300)
          # us = UsersService.new
          # ue = us.edit_user params.merge(id: current_user.id)
        end

        if @source_type == "User"
          reward_grade(User.current, User.current.id, 'Avatar', 100)
        end
        @status = 0
        @msg = ''
      else
        @status = 2
        @msg = l(:not_valid_image_file)
        logger.error "上传失败: "+@msg
      end
    end
    @temp_file = nil

    respond_to do |format|
      format.json{
        render :inline => {status: @status, grade: User.current.grade, message:@msg, url:"#{@urlfile.to_s}?#{Time.now.to_i}"}.to_json,:content_type => 'text/html'
        return
      }
      format.js
      format.api {
        if saved
          render :action => 'upload', :status => :created
        else
          render_validation_errors(@avatar)
        end
      }
    end
  end

  #add by zjc
  #删除图片
  def delete_image
    @source_type = params[:source_type]
    @source_id = params[:source_id]
    @source = nil #eval(@source_type).find(@source_id)
    if params[:m_delete]
      else
      c = Object.const_get(@source_type)
      if c.respond_to?(:find)
        @source = c.find(@source_id)
      end
    end

    diskfile = disk_filename(@source_type,@source_id)
    unless diskfile.nil? || diskfile == ""
      path = File.dirname(diskfile)
      if File.directory?(path)
        # 用户头像进行特别处理
        if @source_type == 'User' || @source_type == 'Course' || @source_type == 'Project'
          diskfile1 = diskfile + 'temp'
          File.open(diskfile1, "wb") do |f|
            buffer = "DELETE"
            f.write(buffer)
          end
        else
          if params[:m_delete] == "1"
            diskfile1 = diskfile +"ID"
            ApplyUserAuthentication.where(:user_id => @source_id,:auth_type => 1).update_all(:is_delete => true)
            File.delete(diskfile1)
            @urlfile = url_to_auth_img(0, 'ID')
          elsif params[:m_delete] == "2"
            diskfile1 = diskfile +"PRO"
            ApplyUserAuthentication.where(:user_id => @source_id,:auth_type => 2).update_all(:is_delete => true)
            File.delete(diskfile1)
            @urlfile = url_to_auth_img(0, 'PRO')
          end
        end
      end
    end
  rescue  Exception => e
    logger.info e.message
      respond_to do |format|
        format.js
        format.api {
          if saved
            render :action => 'upload', :status => :created
          else
            render_validation_errors(@avatar)
          end
        }
      end
  end
  
  private
  
    def set_cache_buster  
      response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"  
      response.headers["Pragma"] = "no-cache"  
      response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"  
    end 


end