class Admins::WeappBannersController < Admins::BaseController

  def index
    @shixun = WeappSettings::ShixunBanner.first
    @course = WeappSettings::CourseBanner.first
  end

  def create
    ActiveRecord::Base.transaction do
      old_carouse = WeappSettings::CourseBanner.first

      if old_carouse.present?
        old_carouse.destroy!
        file_path = Util::FileManage.source_disk_filename(old_carouse)
        File.delete(file_path) if File.exist?(file_path) # 删除之前的文件
      end

      @course = WeappSettings::CourseBanner.create!
      save_image_file(params[:course_banner], @course)
    end
  end


  def shixun_banner
    ActiveRecord::Base.transaction do
      old_shixun = WeappSettings::ShixunBanner.first

      if old_shixun.present?
        old_shixun.destroy!
        file_path = Util::FileManage.source_disk_filename(old_shixun)
        File.delete(file_path) if File.exist?(file_path) # 删除之前的文件
      end

      @shixun = WeappSettings::ShixunBanner.create!
      save_image_file(params[:shixun_banner], @shixun)
    end
  end




  private

  def save_image_file(file, model)
    return unless file.present? && file.is_a?(ActionDispatch::Http::UploadedFile)

    file_path = Util::FileManage.source_disk_filename(model)
    File.delete(file_path) if File.exist?(file_path) # 删除之前的文件
    Util.write_file(file, file_path)
  end

end