import {Stack, Typography, Grid2 as Grid, Button, MenuItem, Select, FormControl, InputLabel, TextField, Card, CardMedia, CardContent, CardActions} from '@mui/material' import {useShow} from '@refinedev/core' import {Show, TextFieldComponent} from '@refinedev/mui' import {useEffect, useState} from 'react' import axios from 'axios' import {BACKEND_URL} from '../../lib/constants' type MediaItem = { id: string filename: string media_type: string } export const ArticleShow = () => { const {query} = useShow({}) const {data, isLoading} = query const record = data?.data const [media, setMedia] = useState([]) const [linkedMedia, setLinkedMedia] = useState([]) const [selectedMediaId, setSelectedMediaId] = useState('') const [mediaOrder, setMediaOrder] = useState(1) const [mediaLoading, setMediaLoading] = useState(true) useEffect(() => { if (record?.id) { axios .get(`${BACKEND_URL}/article/${record.id}/media`) .then((response) => { setLinkedMedia(response?.data || []) }) .catch(() => { setLinkedMedia([]) }) } }, [record?.id]) useEffect(() => { axios .get(`${BACKEND_URL}/media`) .then((response) => { setMedia(response?.data || []) setMediaLoading(false) }) .catch(() => { setMedia([]) setMediaLoading(false) }) }, []) const availableMedia = media.filter((mediaItem) => !linkedMedia.some((linkedItem) => linkedItem.id === mediaItem.id)) const linkMedia = () => { if (selectedMediaId) { const requestData = { media_id: selectedMediaId, media_order: mediaOrder, } axios .post(`${BACKEND_URL}/article/${record?.id}/media`, requestData, { headers: { accept: 'application/json', 'Content-Type': 'application/json', }, }) .then(() => { axios .get(`${BACKEND_URL}/article/${record?.id}/media`) .then((response) => { setLinkedMedia(response?.data || []) setMediaOrder(mediaOrder + 1) setSelectedMediaId('') }) .catch(() => { setLinkedMedia([]) }) }) .catch((error) => { console.error('Error linking media:', error) }) } } const deleteMedia = (mediaId: string) => { axios .delete(`${BACKEND_URL}/article/${record?.id}/media`, { data: {media_id: mediaId}, }) .then(() => { setLinkedMedia((prevMedia) => prevMedia.filter((item) => item.id !== mediaId)) }) .catch((error) => { console.error('Error deleting media:', error) }) } const fields = [ // {label: 'ID', data: 'id'}, {label: 'Заголовок', data: 'heading'}, {label: 'Контент', data: 'body'}, ] const mediaFields = [ // {label: 'ID', data: 'id' as keyof MediaItem}, {label: 'Имя', data: 'filename' as keyof MediaItem}, {label: 'Тип', data: 'media_type' as keyof MediaItem}, ] return ( {fields.map(({label, data}) => ( {label} ))} Медиа {mediaLoading ? ( Загрузка медиа... ) : linkedMedia.length > 0 ? ( linkedMedia.map((mediaItem) => ( {mediaFields.map(({label, data}) => ( {label}: {mediaItem?.[data]} ))} )) ) : ( Нет привязанных медиа )} {/* sx={{width: '650px'}} */} {' '} Привязать медиа Медиа setMediaOrder(Number(e.target.value))} fullWidth InputLabelProps={{shrink: true}} /> ) }