# app/pages/Admin/Media/index.coffee # Добавление стилей страницы if globalThis.stylFns and globalThis.stylFns['app/pages/Admin/Media/index.styl'] styleElement = document.createElement('style') styleElement.type = 'text/css' styleElement.textContent = globalThis.stylFns['app/pages/Admin/Media/index.styl'] document.head.appendChild(styleElement) else log '⚠️ Стили медиа-менеджера не найдены' FileUpload = require 'app/components/Admin/FileUpload/index.coffee' LazyImage = require 'app/components/Admin/LazyImage/index.coffee' MediaService = require 'app/services/MediaService' module.exports = { components: { 'file-upload': FileUpload 'lazy-image': LazyImage } data: -> { files: [] visibleFiles: [] selectedFiles: [] uploading: false uploadProgress: 0 filterType: '' searchQuery: '' loading: false loadingMore: false currentPage: 1 pageSize: 24 hasMoreFiles: true } computed: filteredFiles: -> files = @files if @filterType files = files.filter (file) => file.type == @filterType if @searchQuery query = @searchQuery.toLowerCase() files = files.filter (file) => file.name.toLowerCase().includes(query) return files.sort (a, b) -> new Date(b.createdAt) - new Date(a.createdAt) watch: filteredFiles: -> @currentPage = 1 @updateVisibleFiles() methods: initializeMediaService: -> try await MediaService.init() log '✅ MediaService инициализирован' return true catch error log '❌ Ошибка инициализации MediaService: '+error.message @$emit('show-notification', 'Ошибка инициализации медиа-сервиса', 'error') return false loadMediaFiles: -> @loading = true try # ✅ Сначала инициализируем сервис initialized = await @initializeMediaService() if not initialized return @files = await MediaService.getAllFiles() log '✅ Медиа-файлы загружены: '+@files.length @updateVisibleFiles() catch error log '❌ Ошибка загрузки медиа-файлов: '+error.message @$emit('show-notification', 'Ошибка загрузки файлов', 'error') finally @loading = false updateVisibleFiles: -> startIndex = 0 endIndex = @currentPage * @pageSize @visibleFiles = @filteredFiles.slice(startIndex, endIndex) @hasMoreFiles = endIndex < @filteredFiles.length loadMoreFiles: -> @loadingMore = true setTimeout (=> @currentPage += 1 @updateVisibleFiles() @loadingMore = false ), 300 onFilesSelect: (files) -> log 'Выбрано файлов для загрузки: '+files.length uploadFiles: (files) -> # ✅ Инициализируем сервис перед загрузкой initialized = await @initializeMediaService() if not initialized return @uploading = true @uploadProgress = 0 try for file, index in files # Имитация загрузки с прогрессом for i in [0..100] by 10 await new Promise (resolve) -> setTimeout(resolve, 50) @uploadProgress = ((index * 100) + i) / files.length await MediaService.uploadFiles(files) @$emit('show-notification', 'Файлы успешно загружены', 'success') @loadMediaFiles() catch error log '❌ Ошибка загрузки файлов: '+error.message @$emit('show-notification', 'Ошибка загрузки файлов', 'error') finally @uploading = false @uploadProgress = 0 getFileUrl: (file) -> # Формирование URL для доступа к файлу в CouchDB return '/d/braer_color_shop/'+file._id+'/'+file.name toggleSelect: (fileId) -> if @selectedFiles.includes(fileId) @selectedFiles = @selectedFiles.filter (id) -> id != fileId else @selectedFiles.push(fileId) deleteFile: (file) -> if not confirm('Удалить файл "'+file.name+'"?') return # ✅ Инициализируем сервис перед удалением initialized = await @initializeMediaService() if not initialized return try await MediaService.deleteFile(file._id) @$emit('show-notification', 'Файл удален', 'success') @loadMediaFiles() catch error log '❌ Ошибка удаления файла: '+error.message @$emit('show-notification', 'Ошибка удаления файла', 'error') deleteSelected: -> if not confirm('Удалить '+@selectedFiles.length+' выбранных файлов?') return # ✅ Инициализируем сервис перед удалением initialized = await @initializeMediaService() if not initialized return try await MediaService.deleteFiles(@selectedFiles) @$emit('show-notification', 'Файлы удалены', 'success') @selectedFiles = [] @loadMediaFiles() catch error log '❌ Ошибка удаления файлов: '+error.message @$emit('show-notification', 'Ошибка удаления файлов', 'error') formatFileSize: (bytes) -> if bytes == 0 return '0 Bytes' k = 1024 sizes = ['Bytes', 'KB', 'MB', 'GB'] i = Math.floor(Math.log(bytes) / Math.log(k)) return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i] formatDate: (dateString) -> return new Date(dateString).toLocaleDateString('ru-RU') mounted: -> @loadMediaFiles() log '🖼️ Медиа-менеджер загружен' render: (new Function '_ctx', '_cache', globalThis.renderFns['app/pages/Admin/Media/index.pug'])() }