class Admins::PageThemesController <   Admins::BaseController 
    before_action :require_admin
    before_action :finder_page_theme, only: [:edit, :update, :destroy]

    def index
        params[:sort_by] = params[:sort_by].presence || 'created_at'
        params[:sort_direction] = params[:sort_direction].presence || 'desc'
    
        page_themes = Admins::PageThemesQuery.call(params)
    
        @page_themes = paginate page_themes
    end

    def show
        render 'edit'
    end

    def edit
    end  

    def create 
        @page_theme = PageTheme.new theme_params
        if @page_theme.save 
            save_image_file(params[:image])
            redirect_to admins_page_themes_path
            flash[:success] = "新增主题成功"
        else
            redirect_to admins_page_themes_path
            flash[:danger] = "新增主题失败: #{@page_theme.errors.messages.values.flatten.join(',')}"
        end
    end

    def destroy
        if PageTheme.where(language_frame: @page_theme.language_frame).count <= 1
            flash[:danger] = "删除主题失败,必须存在一个主题"
            return redirect_to admins_page_themes_path
        end
        
        if @page_theme.destroy 
            redirect_to admins_page_themes_path
            flash[:success] = "删除主题成功"
        else  
            redirect_to admins_page_themes_path
            flash[:danger] = "删除主题失败"
        end
    end

    def new
        @page_theme = PageTheme.new
    end

    def update
        @page_theme.attributes = theme_params
        if @page_theme.save 
            save_image_file(params[:image])
            redirect_to admins_page_themes_path
            flash[:success] = "更新成功"
        else  
            redirect_to admins_page_themes_path
            flash[:danger] = "更新失败"
        end
    end

    private
    def finder_page_theme
        @page_theme = PageTheme.find(params[:id])
    end

    def theme_params
        params.require(:page_theme).permit(:language_frame, :name, :cate, :image_url, :clone_url, :order_index)
    end

    def save_image_file(file)
        return unless file.present? && file.is_a?(ActionDispatch::Http::UploadedFile)
        file_path = Util::FileManage.source_disk_filename(@page_theme, "image")
        File.delete(file_path) if File.exist?(file_path) # 删除之前的文件
        Util.write_file(file, file_path)
    end

end
