import React, { useState, useEffect } from 'react';
import ActionSheetItem from "@vkontakte/vkui/dist/components/ActionSheetItem/ActionSheetItem";
import ScreenSpinner from '@vkontakte/vkui/dist/components/ScreenSpinner/ScreenSpinner';
import ActionSheet from "@vkontakte/vkui/dist/components/ActionSheet/ActionSheet";
import BottomNavigationAction from "@material-ui/core/BottomNavigationAction";
import Snackbar from '@vkontakte/vkui/dist/components/Snackbar/Snackbar';
import Avatar from '@vkontakte/vkui/dist/components/Avatar/Avatar';
import BottomNavigation from "@material-ui/core/BottomNavigation";
import View from '@vkontakte/vkui/dist/components/View/View';
import Card from "@vkontakte/vkui/dist/components/Card/Card";
import FormControl from "@material-ui/core/FormControl";
import IconError from '@vkontakte/icons/dist/24/error';
import useEventListener from "@use-it/event-listener";
import TextField from "@material-ui/core/TextField";
import bridge from '@vkontakte/vk-bridge';
import {Gallery} from "@vkontakte/vkui";
import '@vkontakte/vkui/dist/vkui.css';
import firebase from "firebase";
import InfoRoundedIcon from '@material-ui/icons/InfoRounded';
import {MonetizationOnRounded, ContactPhoneRounded} from '@material-ui/icons';
import {contactsStable, infoBlock} from './variables/configs'
import './styles/App.css'
import Home from './panels/Home';
import Intro from './panels/Intro';
import Stable from './panels/Stable';
import Merop from './panels/Merop';
import Shop from './panels/Shop';
import Shops from './panels/Shops';
const ROUTES = {
HOME: 'home',
INTRO: 'intro',
STABLE: 'stable',
MEROP: 'merop',
SHOP: 'shop',
SHOPS: 'shops',
};
const STORAGE_KEYS = {
STATUS_START: 'status',
STATE: 'state',
};
const App = () => {
const [activePanel, setActivePanel] = useState(ROUTES.INTRO);
const [fetchedUser, setUser] = useState(null);
const [popout, setPopout] = useState(<ScreenSpinner size='large' />);
const [userHasSeeIntro, setUserHasSeeIntro] = useState(false);
const [fetchedState, setFethedState] = useState(false);
const [snackbar, setSnackBar] = useState(false);
const [bodyStablePopup, setBodyStablePopup] = useState(0);
useEffect(() => {
bridge.subscribe(({ detail: { type, data }}) => {
if (type === 'VKWebAppUpdateConfig') {
const schemeAttribute = document.createAttribute('scheme');
schemeAttribute.value = data.scheme ? data.scheme : 'client_light';
document.body.attributes.setNamedItem(schemeAttribute);
}
});
async function fetchData() {
const user = await bridge.send('VKWebAppGetUserInfo');
const storageData = await bridge.send('VKWebAppStorageGet', {
keys: Object.values(STORAGE_KEYS)
});
const data = {};
storageData.keys.forEach(({key, value}) => {
try {
data[key] = value ? JSON.parse(value): {};
switch ( key) {
case STORAGE_KEYS.STATUS_START:
if (data[key].hasSeeIntro){
setActivePanel(ROUTES.HOME);
setUserHasSeeIntro(true);
}
break;
case STORAGE_KEYS.STATE:
setFethedState(data[key]);
break;
default:
break;
}
} catch(error){
setSnackBar(<Snackbar
layout= 'vertical'
onClose={() => setSnackBar(null)}
before={<Avatar size={24} style={{backgroundColor: 'var(--dynamic-red)'}}>
<IconError fill='#fff' width='14' height='14'/></Avatar>}
duration={980}
>
Произошла проблема получении из Storage
</Snackbar>)
}
})
setUser(user);
setPopout(null);
}
fetchData()
}, []);
const go = panel => {
setActivePanel(panel);
};
const viewIntro = async function () {
try {
await bridge.send('VKWebAppStorageSet', {
key: STORAGE_KEYS.STATUS_START,
value: JSON.stringify({
hasSeeIntro: true
})
});
go(ROUTES.HOME)
} catch (error){
setSnackBar(<Snackbar
className='snackError'
layout= 'vertical'
onClose={() => setSnackBar(null)}
before={<Avatar size={24} style={{backgroundColor: 'var(--dynamic-red)'}}>
<IconError fill='#fff' width='14' height='14'/></Avatar>}
duration={980}
>
Произошла проблема отправлении в Storage
</Snackbar>)
}
}
const goStable = function () {
go(ROUTES.STABLE)
}
const goMerop = function () {
go(ROUTES.MEROP)
}
const goHome = function () {
go(ROUTES.HOME)
}
const goShop = function () {
go(ROUTES.SHOP)
}
function handler({key}) {
if (['27', 'Escape'].includes(String(key))){
if (activePanel !== ROUTES.HOME) {
go(ROUTES.HOME)
}
}
}
useEventListener('keydown', handler)
function showPoput() {
function showLoginCode() {
let xml = <FormControl fullWidth variant="outlined" >
<TextField id="outlined-basic" label="Код из смс" variant="outlined" />
</FormControl>;
setPopout(
<ActionSheet
onClose={() => setPopout(null)}
iosCloseItem={<ActionSheetItem autoclose mode="cancel">Отменить</ActionSheetItem>}
header={xml}
toggleRef={React.createRef()}
>
<ActionSheetItem autoclose onClick={() => showLoginCode()}>
Проверить
</ActionSheetItem>
</ActionSheet>
)
}
if (localStorage.getItem('id') === 'sheet') {
if (localStorage.getItem('type') === 'stable') {
let pictures = []
let value = 0
let text = 'Конюшня'
let photo;
for (let i = 0; i < 3; i++) {
if (localStorage.getItem('pic' + (i + 1)) === 'undefined') {
photo = 'url(https://a...content-available-to-author-only...c.ru/wp-content/uploads/ovsyanaya-kasha-pri-saharnom-diabete3.png';
}else{
photo = "url(" + localStorage.getItem('pic' + (i + 1)) + ')';
}
if (localStorage.getItem('text') !== 'undefined') {
text = localStorage.getItem('text');
}
pictures = pictures.concat(
[<div style={{
height: 270,
backgroundImage: photo,
backgroundPosition: 'center',
backgroundSize: 'cover'
}} /> ]
)
}
let bodyInfo = [infoBlock(localStorage.getItem('name'), text, localStorage.getItem('cost'), localStorage.getItem('city'), localStorage.getItem('note'))];
let bodyCost = [infoBlock('Стоимость аренды: ' + localStorage.getItem('cost_postoy'), 'Средняя стоимость тренировки: ' + localStorage.getItem('cost_traning'), localStorage.getItem('cost_more'))];
let bodyCont = [contactsStable()]
let temp = [
<Card>
<div id='xmlll' style={{backgroundColor: '#fff', borderRadius: 20}}>
<Gallery
slideWidth="90%"
style={{ height: 270, borderRadius: '10px 10px 0px 0px'}}
bullets="dark"
showArrows
>
{pictures}
</Gallery>
<Gallery
slideWidth="100%"
align="center"
style={{ height: '100%' }}
slideIndex={bodyStablePopup}
isDraggable={false}
showArrows={false}
>
<div>
{bodyInfo}
</div>
<div>
{bodyCost}
</div>
<body>
{bodyCont}
</body>
</Gallery>
<div style={{margin: '0px auto'}}>
<BottomNavigation
value={bodyStablePopup}
onChange={(event, newValue) => {
setBodyStablePopup(newValue);
alert(bodyStablePopup)
}}
showLabels
style={{width: '100%', margin: '10, 10, 10, 10'}}
>
<BottomNavigationAction label="Иформация" icon={<InfoRoundedIcon />} />
<BottomNavigationAction label="Стоимость" icon={<MonetizationOnRounded />} />
<BottomNavigationAction label="Контакты" icon={<ContactPhoneRounded />} />
</BottomNavigation>
</div>
</div>
</Card>
];
setPopout(<ActionSheet
onClose={() => setPopout(null)}
iosCloseItem={<ActionSheetItem autoclose mode="cancel">Отменить</ActionSheetItem>}
toggleRef={React.createRef()}
style={{padding: 0}}
>
{temp}
</ActionSheet>)
}
if (localStorage.getItem('type') === 'typeEquine_edit') {
function setEquineType(text) {
try {
bridge.send('VKWebAppStorageSet', {
key: 'type_equine',
value: text
});
} catch (error){
setSnackBar(<Snackbar
className='snackError'
layout= 'vertical'
onClose={() => setSnackBar(null)}
before={<Avatar size={24} style={{backgroundColor: 'var(--dynamic-red)'}}>
<IconError fill='#fff' width='14' height='14'/></Avatar>}
duration={980}
>
Произошла проблема отправлении в Storage
</Snackbar>)
}
}
setPopout(<ActionSheet
onClose={() => setPopout(null)}
iosCloseItem={<ActionSheetItem autoclose mode="cancel">Отменить</ActionSheetItem>}
toggleRef={React.createRef()}>
<ActionSheetItem autoclose onClick={() => setEquineType('Конкур')}>
Конкур
</ActionSheetItem>
<ActionSheetItem autoclose onClick={() => setEquineType('Выездка')}>
Выездка
</ActionSheetItem>
</ActionSheet>)
}
if (localStorage.getItem('type') === 'ad') {
let url = localStorage.getItem('url')
let xml = <h4>Перейти ли на {url}</h4>
function openUrl() {
var win = window.open(url, '_blank');
win.focus();
}
setPopout(<ActionSheet
onClose={() => setPopout(null)}
iosCloseItem={<ActionSheetItem autoclose mode="cancel">Отменить</ActionSheetItem>}
header={xml}
toggleRef={React.createRef()}>
<ActionSheetItem autoclose onClick={() => openUrl()}>
Перейти
</ActionSheetItem>
</ActionSheet>)
}
if (localStorage.getItem('type') === 'login') {
// const window = {
// recaptchaVerifier: undefined
// }
firebase.auth().useDeviceLanguage();
// window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('go-to', {
// 'size': 'invisible',
// 'callback': () => {
// alert('ok')
// },
// 'expired-callback': () => {
// const open = false
// setSnackBar(
// <Snackbar open={open} autoHideDuration={6000} onClose={() => setSnackBar(null)}>
// <Alert onClose={() => setSnackBar(null)} severity="error">
// Ошибка в полученнии данных...
// </Alert>
// </Snackbar>
// )
// }
// })
const handleChange = (event) => {
currency = event.target.value;
};
const currencies = [
{
value: '+7',
label: 'Россия',
},
];
let currency = '+7';
let xml = <FormControl fullWidth variant="outlined" >
<div>
<TextField
id="outlined-select-currency-native"
select
label="Код страны"
value={currency}
onChange={handleChange}
SelectProps={{
native: true,
}}
variant="outlined"
style = {{width: 100}}
>
{currencies.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</TextField>
<TextField id="phone-number" label="Телефон" variant="outlined" />
</div>
</FormControl>;
setPopout(
<ActionSheet
onClose={() => setPopout(null)}
iosCloseItem={<ActionSheetItem autoclose mode="cancel">Отменить</ActionSheetItem>}
header={xml}
toggleRef={React.createRef()}
>
<ActionSheetItem autoclose id='go-to' className={'go-to'} onClick={() => showLoginCode(document.getElementsByTagName("phone-number")[0])}>
Отправить код
</ActionSheetItem>
</ActionSheet>
)
localStorage.setItem('id', '');
localStorage.setItem('type', '')
}
if (localStorage.getItem('type') === 'tovar') {
let pictures = [];
let text = localStorage.getItem('text')
//
for (var i = 0; i < 3; i++){
pictures = pictures.concat([<div style={{
height: 200,
backgroundImage: "url(" + localStorage.getItem('img' + (i + 1)) + ')',
backgroundPosition: 'center',
backgroundSize: 'cover'
}} />])
}
setPopout(
<ActionSheet
className='tovarSheet'
onClose={() => setPopout(null)}
iosCloseItem={<ActionSheetItem autoclose mode="cancel">Отменить</ActionSheetItem>}
header={
<div>
<Gallery
slideWidth="90%"
style={{ height: 200}}
bullets="dark"
showArrows
>
{pictures}
</Gallery>
<h4> {text} </h4>
</div>
}
toggleRef={React.createRef()}
>
<ActionSheetItem autoclose>
Позвонить
</ActionSheetItem>
</ActionSheet>
)
localStorage.setItem('id', '');
localStorage.setItem('type', '');
}
}
}
return (
<View activePanel={activePanel} popout={popout} onSwipeBack={goHome}>
<Home id={ROUTES.HOME} fetchedUser={fetchedUser} fetchedState={fetchedState} snackbarError={snackbar} goStable={goStable} goMerop={goMerop} goShop={goShop} popup={showPoput}/>
<Intro id={ROUTES.INTRO} fetchedUser={fetchedUser} go={viewIntro} snackbarError={snackbar} userHasSeeIntro={userHasSeeIntro}/>
<Stable id={ROUTES.STABLE} fetchedUser={fetchedUser} snackbarError={snackbar} goHome={goHome} popup={showPoput}/>
<Merop id={ROUTES.MEROP} fetchedUser={fetchedUser} fetchedState={fetchedState} snackbarError={snackbar} goHome={goHome} />
<Shop id={ROUTES.SHOP} fetchedUser={fetchedUser} goHome={goHome} popup={showPoput} snackbarError={snackbar}/>
<Shops id={ROUTES.SHOPS} />
</View>
);
}
export default App;