import { useEffect, useRef, useState } from 'react'; import {View,Text, StyleSheet, ScrollView, TouchableOpacity, Image, Animated, TextInput, Button, Alert, StatusBar, Pressable, FlatList} from 'react-native'; import MapLibreGL from '@maplibre/maplibre-react-native'; import { MapView,ShapeSource,Camera,UserLocation,PointAnnotation,FillLayer,LineLayer,VectorSource } from "@maplibre/maplibre-react-native"; import { SelectList } from 'react-native-dropdown-select-list'; import { RadioButton } from 'react-native-paper'; import DatePicker from 'react-native-date-picker'; import Moment from 'moment'; import { launchCamera, launchImageLibrary } from 'react-native-image-picker'; import NetInfo from "@react-native-community/netinfo"; import AwesomeAlert from 'react-native-awesome-alerts'; import AsyncStorage from '@react-native-async-storage/async-storage'; import turfcenter from '@turf/center'; const {points,polygon,lineString} = require('@turf/helpers'); import RNFetchBlob from 'rn-fetch-blob'; import Modal from "react-native-modal"; import {useIsFocused} from '@react-navigation/native'; import { PDAM_API_URL } from "../../urlConfig"; import React from 'react'; type collectLineScreenProps = {route: any,navigation: any}; export default function CollectLineScreen({route,navigation}:collectLineScreenProps) { console.log("route",route.params); const apiKey = "JoJs2pcDv5o0yQlQLMfI"; const [basemap, setBasemap] = useState("streets-v2"); const styleURL = `https://api.maptiler.com/maps/${basemap}/style.json?key=${apiKey}`; const Pipe_Type = [ {key:'Pipa 24"', value:'Pipa 24"'}, {key:'Pipa 20"', value:'Pipa 20"'}, {key:'Pipa 16"', value:'Pipa 16"'}, {key:'Pipa 10"', value:'Pipa 10"'}, ] const [centerCoords,setCenterCoords] = useState([]); const isFocused = useIsFocused(); const [userID,setUserID] = useState(); useEffect(()=>{ if(isFocused){ const getKey = async () =>{ const jsonValue = await AsyncStorage.getItem('USER_DATA') console.log(JSON.parse(jsonValue!)); const data = JSON.parse(jsonValue!); console.log("user_data",data.id); setUserID(data.id) }; getKey() let centCord = turfcenter(points(route.params.coordinates)); // console.log('center'); // console.log(centCord.geometry.coordinates); setCenterCoords(centCord.geometry.coordinates); const unsubscribe = NetInfo.addEventListener((state) => { setConnected(state.isConnected!) }); return () => { unsubscribe(); }; }; },[isFocused]) const ref = useRef(); const [connected, setConnected] = useState(true); const [currentIndex, setCurrentIndex] = useState(0); const [imgUrl, setImgUrl] = useState([]); const [files, setFiles] = useState([]); const [pipeName, setPipeName] = useState(''); const [selectedPipeType, setselectedPipeType] = useState(""); const [checkedStatus, setCheckedStatus] = useState('Baik'); const [Information, setInformation] = useState(''); const [open, setOpen] = useState(false); const [install_date, setInstallDate] = useState(new Date()); const momentDate = Moment(install_date).format('YYYY-MM-DD'); const [alertOnline, setAlertOnline] = useState(false); const [alertOffline, setAlertOffline] = useState(false); const [pipeNameError, setPipeNameError] = useState(false); const [pipeTyeError, setPipeTypeError] = useState(false); const [pipeStatusError, setPipeStatusError] = useState(false); const [pipeInfoError, setPipeInfoError] = useState(false); const [ModalAttachment, setModalAttachment] = useState(false); const openCameraLib = async () => { const result = await launchCamera({ mediaType: 'photo', quality: 1, includeBase64: true, saveToPhotos: true }); const newObj = { file_type: result?.assets![0]?.type, file: result?.assets![0]?.base64, fileSize: result?.assets![0]?.fileSize, } setFiles([...files,newObj]); setImgUrl([...imgUrl,result?.assets![0]?.base64]); }; const openLib = async () => { const result = await launchImageLibrary({ quality: 1, mediaType: 'photo', selectionLimit: 0, includeExtra: true, includeBase64: true }); result?.assets?.forEach(asset => { const newObj = { file_type: asset.type, file: asset.base64, fileSize: asset.fileSize } setFiles(oldArray => [...oldArray,newObj]); setImgUrl(oldArray => [...oldArray,asset.base64]); }); }; const PrevImg = ({isIndex}) => { if(isIndex===0){ return ( ) } return ( { setCurrentIndex(currentIndex-1) ref.current.scrollToIndex({ animated: true, index: currentIndex-1 }); }}> ) }; const NextImg = ({isIndex}) => { if(imgUrl.length<=1){ return ( ) } else{ if (isIndex === (imgUrl.length-1)) { return ( ) } else{ return ( { setCurrentIndex(currentIndex+1) ref.current.scrollToIndex({ animated: true, index: currentIndex+1 }); }}> ) } } }; const showDialog = () => { if(!pipeName){ setPipeNameError(true) }else{ setPipeNameError(false) } if(!selectedPipeType){ setPipeTypeError(true) }else{ setPipeTypeError(false) } if(!checkedStatus){ setPipeStatusError(true) }else{ setPipeStatusError(false) } if(!Information){ setPipeInfoError(true) }else{ setPipeInfoError(false) } if(!pipeName || !selectedPipeType || !checkedStatus || !Information) { return false } if(connected){ setAlertOnline(true); } else{ setAlertOffline(true) } }; const handleCancelAlertOnline = () => { setAlertOnline(false); }; const handleCancelAlertOffline = () => { setAlertOffline(false); }; const collectDataOnline = async() => { try { const result = { status: 0, body: {}, } let date = new Date(); const milliseconds = Date.UTC( date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), ); const localTime = new Date(milliseconds); const geom = route.params.coordinates.map((item:any)=>{ return String(item).replace(',',' ') }) const obj = { nama: pipeName, jenis: selectedPipeType, tanggal_installasi: momentDate, status: checkedStatus, keterangan: Information, geom: `MULTILINESTRING((${geom}))`, created_by: userID, created_at: localTime } await RNFetchBlob.config({ trusty : true }).fetch('POST', `${PDAM_API_URL}/addData`,{ "Accept": 'application/json', "Content-Type": "application/json", }, JSON.stringify(obj) ).then(async (resp) => { const json = resp.json() const status = resp.respInfo.status; result.status = status; result.body = json; if (status == 201) { insertAttachment(json,files) const storeData = async () => { try { await AsyncStorage.setItem(json[0].id+" / "+pipeName+" / "+selectedPipeType+" / "+momentDate+" / "+checkedStatus+" / "+Information+" / "+geom+" / sentPDAM","Value"); } catch (e) { } }; storeData() } }) } catch (error) { } }; const collectDataOffline = () => { const geom = route.params.coordinates.map((item:any)=>{ return String(item).replace(',',' ') }) const storeData = async () => { try { await AsyncStorage.setItem(pipeName+" / "+selectedPipeType+" / "+momentDate+" / "+checkedStatus+" / "+Information+" / "+geom+" / draftPDAM","Value"); } catch (e) { } }; storeData() setAlertOffline(false); navigation.navigate('Survey Pipa PDAM', { screen: 'Survey Pipa PDAM'}) }; const insertAttachment = async (json: any,files: any) => { try { files.forEach(async function(file:any) { const url = `${PDAM_API_URL}/addAttachment`; await RNFetchBlob.config({ trusty : true }).fetch('POST', url,{ "Content-Type": "application/json", }, JSON.stringify({pdam_id:json[0].id, file:file.file, mimetype:file.file_type, size:file.fileSize}) ).then(async (resp) => { Alert.alert("Success") navigation.navigate('Survey Pipa PDAM', { screen: 'Survey Pipa PDAM'}) setAlertOnline(false); } ) }); } catch (error) { console.log(error); } }; const renderItem = ({item,index}:any) => { return ( ); }; return ( { route.params.coordinates.map((item:any,index:number)=>( } key={index} id={String(index)} coordinate={item} draggable={false} /> )) } {/* */} navigation.navigate('PDAM Map Collect', { screen: 'PDAM Map Collect'})}> Change Location {/* Name* */} Pipe Name { setPipeName(text) }} onChange={()=> { setPipeNameError(false) }} /> {pipeNameError ? Pipe Name is Required!:null} {/* PJU Type * */} Pipe Type ( [setPipeTypeError(false)] )} /> {pipeTyeError ? Pipe Type is Required!:null} {/* Status* */} Status {setCheckedStatus('Baik'); setPipeStatusError(false)}} /> Baik {setCheckedStatus('Rusak'); setPipeStatusError(false); }} /> Rusak {pipeStatusError ? Status is Required!:null} Information { setInformation(text) }} onChange={()=> { setPipeInfoError(false) }} /> {pipeInfoError ? Information is Required!:null} Installation Date setOpen(true)} value={String(momentDate)} /> { setOpen(false) setInstallDate(survey_date) }} onCancel={() => { setOpen(false) }} /> Attachment Lampirkan foto / gambar { imgUrl.length === 0 ? setModalAttachment(true)}> Klik untuk menambahkan foto / gambar : setModalAttachment(true)}> } contentContainerStyle={{flexDirection:'row',flexWrap:'wrap',columnGap:25,rowGap:10}} data={imgUrl} renderItem={({item,index})=>renderItem({item,index})} /> } SEND { handleCancelAlertOnline(); }} onConfirmPressed={() => { collectDataOnline(); }} overlayStyle={{width:'100%'}} contentContainerStyle={{width:'70%',borderRadius:10}} titleStyle={{fontSize:20}} messageStyle={{fontSize:16}} /> {/* Offline Mode Alert */} { handleCancelAlertOffline(); }} onConfirmPressed={() => { collectDataOffline(); }} overlayStyle={{width:'100%'}} contentContainerStyle={{width:'70%',borderRadius:10}} titleStyle={{fontSize:20}} messageStyle={{fontSize:16}} /> setModalAttachment(false)} style={{top:'18%',alignSelf:'center'}}> Select Mode setModalAttachment(false)} style={{alignSelf:'flex-end',padding:10}}> {openCameraLib(),setModalAttachment(false)}} style={{height:50,backgroundColor:'#FFFFFF',alignItems:'center',justifyContent:'center',borderTopLeftRadius:10,borderTopRightRadius:10,borderWidth:1,borderColor:'#A6A6A6'}}> Take photo {openLib(),setModalAttachment(false)}} style={{height:50,backgroundColor:'#FFFFFF',alignItems:'center',justifyContent:'center',borderBottomLeftRadius:10,borderBottomRightRadius:10,borderWidth:1,borderColor:'#A6A6A6'}}> Choose photo ); }; const styles = StyleSheet.create({ errorInput: { color: 'red', marginLeft: 20 }, inputLong: { height: 40, borderWidth: 1, padding: 10, width: 180, marginRight: 20 }, inputLat: { height: 40, borderWidth: 1, padding: 10, borderRadius: 50, width: 180, color: 'black' }, input: { width:352, height: 45, borderWidth: 1, padding: 10, borderRadius: 10, color: '#6B5E5E', borderColor:'#A6A6A6' }, container: { padding: 10, flexGrow: 1 }, mainContainer: { flex: 1, }, label: { fontSize: 16, fontWeight:'semibold', color: '#434343', // marginBottom: 20 }, title: { alignItems: 'center', justifyContent: 'center', alignSelf: 'center', fontWeight: 'bold', fontSize: 22, color: 'black', marginBottom: 10 }, borderImg: { borderColor: 'black', borderWidth: 1, borderRadius: 20, }, img: { width: 295, height: 500, borderRadius: 6, }, btnCameraContainer: { flexDirection: 'row', justifyContent: 'space-around', top:10, }, btnCamera: { alignItems: 'center', justifyContent: 'center', alignSelf: 'center', width: 100, height: 40, bottom:20, borderRadius: 6, backgroundColor: '#80CBD3' }, textBtn: { color: '#fff' }, buttonImageIconStyle: { padding: 10, margin: 5, height: 25, width: 25, resizeMode: 'stretch', }, });