class ResumesController < ApplicationController
  before_action :require_login

  before_action :convert_base64_image!, only: [:logo]

  def create
    resume = Resume.new(resume_params)
    resume.user = current_user
    resume.education = params[:resume][:education]
    resume.experience = params[:resume][:experience]
    params[:resume][:job_category].select! { |d|  Resume::JOB_CATEGORY_LIST.include?(d) }
    ActiveRecord::Base.transaction do
      resume.save!
      if params[:resume][:attachment_id].present?
        attachment = current_user.attachments.find(params[:resume][:attachment_id])
        attachment.update!(container: resume)
      end
      
      unless params[:resume][:logo].present?
        file_path = ApplicationController.helpers.disk_filename('ResumeLogo', current_user.id)
        File.delete(file_path) if File.exist?(file_path) # 删除之前没有保存简历时的图片
      end

      render_ok
    end
  rescue Exception => e
    uid_logger(e.message)
    tip_exception(e.message)
  end


  def logo
    Util.write_file(@image, avatar_path)
    render_ok(avatar_url: avatar_url)
  rescue StandardError => ex
    logger_error(ex)
    render_error('修改失败')
  end

  def destroy_logo
    file_path = ApplicationController.helpers.disk_filename('ResumeLogo', current_user.id)
    File.delete(file_path) if File.exist?(file_path) # 删除之前
    render_ok
  end


  # 招聘方查看简历详情
  def preview
    @apply = current_user.apply_candidates.find(params[:id])
    @apply.update(viewed_at: Time.now)
    @resume = @apply.user.resume
  end


  private

  def resume_params
    params.require(:resume).permit(:name, :sex, :birth_on, :mobile, :evaluate, :salary, :job_year, education: [], job_category: [], job_position: [], city:[], experience:[])
  end


  def convert_base64_image!
    max_size = EduSetting.get('upload_avatar_max_size')
    @image = Util.convert_base64_image(params[:image].to_s.strip, max_size: max_size)
  rescue Base64ImageConverter::Error => ex
    render_error(ex.message)
  end

  def avatar_path
    ApplicationController.helpers.disk_filename('ResumeLogo', current_user.id)
  end

  def avatar_url
    ApplicationController.helpers.resume_logo(current_user).to_s + "?#{Time.now.to_i}"
  end
end
