· 6 years ago · Dec 09, 2019, 03:36 AM
1//This is an example code for Navigator//
2import React, { Component } from 'react';
3//import react in our code.
4import { StyleSheet, View, Text, NativeAppEventEmitter, PermissionsAndroid, Platform, Dimensions, BackHandler, TouchableOpacity, ToastAndroid, Switch} from 'react-native';
5import { Image, Button } from 'react-native-elements';
6//import all the components we are going to use.
7import Geolocation from '@react-native-community/geolocation';
8import Geocoder from 'react-native-geocoder'
9// import { Picker } from 'react-native-picker-dropdown'
10import AsyncStorage from '@react-native-community/async-storage';
11import Spinner from 'react-native-loading-spinner-overlay';
12import Axios from 'axios';
13import Moment from 'moment';
14import Icon from 'react-native-vector-icons/FontAwesome';
15import BottomSheet from 'react-native-bottomsheet'
16// import RNGeofence from 'react-native-geo-fence';
17// import GeoFencing from 'react-native-geo-fencing';
18import * as geolib from 'geolib';
19// import _ from 'lodash';
20import { picaSchema, systemMasterSchema, groupItemSchema, chapterSchema, evalItemSchema, questionSchema,
21 evalObjectSchema, evalMethodSchema, bestPracticeSchema, evalMethodChoiceSchema,
22 transHeadSchema,transDetailItemSchema,transDetailQuestionSchema,transDetailObjectSchema,transDetailMethodSchema,
23 transDetailChoiceSchema, TRANS_HEAD_SCHEMA, TRANS_DETAIL_ITEM_SCHEMA, TRANS_DETAIL_QUEST_SCHEMA, TRANS_DETAIL_OBJECT_SCHEMA,
24 TRANS_DETAIL_METHOD_SCHEMA, TRANS_DETAIL_CHOICE_SCHEMA,
25 GROUP_ITEM_SCHEMA, CHAPTER_SCHEMA, EVAL_ITEM_SCHEMA,
26 QUESTION_SCHEMA, EVAL_OBJECT_SCHEMA, EVAL_METHOD_SCHEMA, BEST_PRACTICE_SCHEMA, EVAL_METHOD_CHOICE_SCHEMA,
27 tempGroupSchema, tempChapterSchema, tempItemSchema, tempQuestSchema, tempObjectSchema, tempMethodSchema,
28 TEMP_GROUP_SCHEMA, TEMP_CHAPTER_SCHEMA, TEMP_ITEM_SCHEMA, TEMP_QUEST_SCHEMA, TEMP_OBJECT_SCHEMA, SYSTEM_MASTER_SCHEMA, TEMP_METHOD_SCHEMA, PICA_SCHEMA
29} from '../component/db/Schemas';
30import { StackActions, NavigationActions } from 'react-navigation';
31import { showToast } from './helper';
32import NetInfo from '@react-native-community/netinfo'
33
34const Realm = require('realm');
35let realm;
36
37const { width, height } = Dimensions.get("window");
38
39const RNFS = require('react-native-fs');
40const dirHome = Platform.select({
41 ios: `${RNFS.DocumentDirectoryPath}/Pictures/OutletClassification`,
42 android: `${RNFS.ExternalStorageDirectoryPath}/Pictures/OutletClassification`
43});
44
45const dirPicutures = `${dirHome}/Pictures`;
46
47const downloadFile = async (url, newFilepath) => {
48 return new Promise((resolve, reject) => {
49 RNFS.mkdir(dirPicutures)
50 .then(() => {
51 RNFS.downloadFile({fromUrl:url, toFile: newFilepath, background: true}).promise.then(res => {
52 //console.log('Download result', res)
53 });
54 })
55 .catch(err => {
56 //console.log('mkdir error', err);
57 reject(err);
58 });
59 });
60};
61
62export default class EvaluationScreen extends Component {
63 constructor(props, context) {
64 super(props, context)
65 const data = this.props.navigation.getParam("data", "");
66 //console.log('data', data);
67 this.state = {
68 loading: false,
69 currentDate: new Date(),
70 evalId: data.evalId,
71 progressSts: data.progressSts,
72 evalTitle : '',
73 evalYear : '',
74 csId : '',
75 currentcsId : '',
76 csTitle : '',
77 outletCd : '',
78 outletNm : '',
79 latitude : '',
80 longitude : '',
81 areaCd : '',
82 areaNm : '',
83 subAreaNm : '',
84 dealerCd : '',
85 dealerNm : '',
86 currentLongitude: null,//Initial Longitude
87 currentLatitude: null,//Initial Latitude
88 currentAddress: 'unknown',//Initial Address
89 outletSts: '',
90 outletStsNm: '',
91 sessionCd: '',
92 dataSourceOutlet: [],
93 historyEvaluation: [],
94 historyPica: [],
95 username : '',
96 date : null,
97 textLoading: '',
98 url: null,
99 radius: null,
100 radiusSts: false,
101 em: false,
102 emText: 'EM',
103 roleId: ''
104 }
105
106 realm = new Realm({
107 schemaVersion : 16,
108 path: 'realmOutlet.realm',
109 schema: [picaSchema, systemMasterSchema, groupItemSchema, chapterSchema, evalItemSchema, questionSchema,
110 evalObjectSchema, evalMethodSchema, bestPracticeSchema, evalMethodChoiceSchema,
111 transHeadSchema,transDetailItemSchema,transDetailQuestionSchema,transDetailObjectSchema,transDetailMethodSchema,
112 transDetailChoiceSchema, tempGroupSchema, tempChapterSchema, tempItemSchema, tempQuestSchema,
113 tempObjectSchema, tempMethodSchema
114 ]
115 });
116
117 this.onValueChange = this.handleValueChange.bind(this)
118 //Binding handleBackButtonClick function with this
119 this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
120 }
121
122 handleValueChange(outletSts) {
123 //console.log(outletSts);
124 this.setState({ outletSts })
125 }
126
127 static navigationOptions = {
128 title: 'Evaluation Preparation',
129 //Sets Header text of Status Bar
130 headerStyle: {
131 backgroundColor: 'red',
132 },
133 headerTintColor: '#fff'
134 };
135
136 async componentDidMount(){
137 // trigger geofencing
138 // this.initiateGeofencing();
139 // // listen to native "GeofenceEvent" event triggered by "react-native-geo-fence"
140 // this.listeners = [
141 // NativeAppEventEmitter.addListener('GeofenceEvent', this.handleNativeEvents),
142 // ];
143
144
145 BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
146 //Checking for the permission just after component loaded
147 const session = await AsyncStorage.getItem('sessionCd');
148 const username = await AsyncStorage.getItem('fullName');
149 const url = await AsyncStorage.getItem('url');
150 const roleId = await AsyncStorage.getItem('roleId');
151 const csId = await AsyncStorage.getItem('csId');
152 let radius = realm.objects(SYSTEM_MASTER_SCHEMA).filtered('systemCd = "RADIUS"');
153 //console.log('radius ', radius[0].systemValueNum)
154 this.setState({
155 username : username,
156 sessionCd: session,
157 waiting: true,
158 radius: radius[0].systemValueNum,
159 textLoading: 'Loading...',
160 url: url,
161 roleId: roleId,
162 currentcsId: csId,
163 }, function(){
164 this.fetchData();
165 })
166
167
168 }
169
170 componentWillUnmount() {
171 // This is the Last method in the activity lifecycle
172 // stop geofencing
173 // RNGeofence.stopGeofencing();
174 // // remove listener
175 // _.each(this.listeners, l => l.remove());
176 // Removing Event Listener for the BackPress
177 BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
178
179 }
180
181 checkRadius(){
182 //console.log('check radius', this.state)
183 let check = geolib.isPointWithinRadius(
184 { latitude: parseFloat(this.state.latitude), longitude: parseFloat(this.state.longitude) },
185 { latitude: parseFloat(this.state.currentLatitude), longitude: parseFloat(this.state.currentLongitude) },
186 parseInt(this.state.radius)
187 );
188 if(this.state.roleId.toUpperCase()=="ADMIN_SURVEY" || this.state.roleId.toUpperCase()=="EVALUATOR_SURVEY"){
189 this.setState({radiusSts: true})
190 }else{
191
192 if(!check){
193 showToast('Your Location must near to the outlet to start evaluation')
194 }
195 this.setState({radiusSts: check})
196
197 }
198 // this.setState({radiusSts: true})
199 //console.log('radius is ', check)
200 }
201
202 goBack() {
203 const { navigation } = this.props;
204 navigation.goBack();
205 }
206
207 handleBackButtonClick() {
208 // BackHandler.exitApp();
209 this.goBack();
210 return true;
211 }
212
213 fetchOutletSts(){
214 var that = this;
215
216 let statusObj = realm.objects(SYSTEM_MASTER_SCHEMA).filtered('systemType = "OUTLET_STS"')
217 let optionSts = [];
218 statusObj.reduce((result,val) =>{
219 optionSts.push({ id: val.systemCd, name: val.systemValueTxt})
220 },[])
221
222 this.setState({outletStsNm: optionSts[this.state.outletSts].name})
223 this.setState({
224 textLoading: 'Get Location...'
225
226 },function(){
227 if(Platform.OS === 'ios'){
228 this.callLocation(that);
229 // //console.log('ios device');
230 }else{
231 async function requestLocationPermission() {
232 try {
233 const granted = await PermissionsAndroid.request(
234 PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,{
235 'title': 'Location Access Required',
236 'message': 'This App needs to Access your location'
237 }
238 )
239 if (granted === PermissionsAndroid.RESULTS.GRANTED) {
240 //To Check, If Permission is granted
241 that.callLocation(that);
242
243 } else {
244 alert("Permission Denied");
245 }
246 } catch (err) {
247 alert("err",err);
248 //console.log(err)
249 }
250 }
251 requestLocationPermission();
252 }
253 })
254 }
255
256 fetchData() {
257 //stackexchange User API url
258 // const url = `https://api.stackexchange.com/2.2/users?page=${page}&order=desc&sort=reputation&site=stackoverflow`;
259 //console.log('session state: ' + this.state.sessionCd);
260 const url = this.state.url + 'API/Activity/GetEvalById';
261 this.setState({ loading: true })
262 Axios.get(url,
263 {
264 headers: { sessionCd: this.state.sessionCd
265 },
266 params:{
267 evalId : this.state.evalId
268 } })
269 .then(res => {
270 let data = res.data.data;
271 //console.log('response',res.data)
272
273 if(res.data.result){
274 this.setState({
275 waiting: false,
276 csId: data.csId,
277 csTitle: data.csTitle,
278 outletNm: data.outletNm,
279 outletSts: data.outletSts,
280 latitude: data.latitude,
281 longitude: data.longitude,
282 areaNm: data.areaNm,
283 subAreaNm: data.subAreaNm,
284 dealerNm: data.dealerNm,
285 em: data.withoutEm,
286 emText: data.withoutEm ? 'Non EM' : 'EM'
287 },function(){
288 if(this.state.csId!=this.state.currentcsId){
289 console.log('update checksheet ...')
290 this.synchronizeChecksheet()
291 }else{
292 console.log('no update checksheet ...')
293 this.fetchOutletSts()
294 }
295 })
296 }else{
297 this.setState({
298 loading: false,
299 waiting:false
300 })
301 if(res.data.message=='Session Expired'){
302 showToast(res.data.message)
303 AsyncStorage.removeItem('isLogin');
304 AsyncStorage.removeItem('sessionCd');
305 this.props.navigation.navigate('Auth');
306 }
307 }
308
309 })
310 .catch(error => {
311 //console.warn("No internet");
312 this.setState({ loading: false, waiting: false, error: 'Something just went wrong' })
313 showToast("No Internet Connection")
314 });
315 }
316
317 async synchronizeChecksheet() {
318 const url = this.state.url + 'API/Helper/GetActiveChecksheet';
319 console.log('session state: ' + this.state.sessionCd, url);
320 this.setState({ waiting: true , textLoading: 'Synchronize... Please wait...' })
321 Axios.get(url,
322 {
323 headers: { sessionCd: this.state.sessionCd
324 },
325 })
326 .then(res => {
327 let data = res.data.data;
328 console.log('response synchronize checksheet',res.data)
329 if(res.data.result){
330 this.setState({
331 dataSync: data,
332 waiting: false
333 },function(){
334 this.updateData()
335 })
336 }
337
338 })
339 .catch(error => {
340 // console.warn(error);
341 this.setState({ loading: false, waiting: false, error: 'Something just went wrong' })
342 });
343 }
344
345 updateData(){
346 const items = this.state.dataSync;
347 // console.log('master',master.length)
348 this.setState({waiting: true})
349 try {
350
351 // Create Realm objects and write to local storage
352 realm.write(() => {
353
354 let delGroupItem = realm.objects(GROUP_ITEM_SCHEMA);
355 realm.delete(delGroupItem);
356
357 let delChapter = realm.objects(CHAPTER_SCHEMA);
358 realm.delete(delChapter);
359
360 let delEval = realm.objects(EVAL_ITEM_SCHEMA);
361 realm.delete(delEval);
362
363 let delObject = realm.objects(EVAL_OBJECT_SCHEMA);
364 realm.delete(delObject);
365
366 let delQuest = realm.objects(QUESTION_SCHEMA);
367 realm.delete(delQuest);
368
369 items[0].groupItems.forEach(obj => {
370 realm.create(GROUP_ITEM_SCHEMA, obj, true);
371 });
372
373 items[0].chapters.forEach(obj => {
374 realm.create(CHAPTER_SCHEMA, obj, true);
375 });
376
377 items[0].evalItems.forEach(obj => {
378 // console.log(obj.bestPractices);
379 realm.create(EVAL_ITEM_SCHEMA, obj, true);
380 if(obj.bestPractices.length>0){
381 obj.bestPractices.forEach(bestPractices => {
382 realm.create(BEST_PRACTICE_SCHEMA, bestPractices, true);
383 });
384 }
385
386 });
387
388 let evalMethodChoice = realm.objects(EVAL_METHOD_CHOICE_SCHEMA);
389 realm.delete(evalMethodChoice); // Deletes all eval method choice
390
391 items[0].evalMethods.forEach(obj => {
392 let methodId = obj.methodId;
393 realm.create(EVAL_METHOD_SCHEMA, obj, true);
394 if(obj.typeChoice.length>0){
395 obj.typeChoice.forEach(typeChoice => {
396 realm.create(EVAL_METHOD_CHOICE_SCHEMA, {methodId: methodId, button: typeChoice.button, value: typeChoice.value});
397 });
398 }
399 });
400
401 items[0].evalObjects.forEach(obj => {
402 realm.create(EVAL_OBJECT_SCHEMA, obj, true);
403 });
404
405 items[0].questions.forEach(obj => {
406 realm.create(QUESTION_SCHEMA, obj, true);
407 });
408
409 });
410
411 this.setState({waiting: false},function(){
412 AsyncStorage.setItem('csId', this.state.csId.toString())
413 this.fetchOutletSts()
414 })
415 }catch(err){
416 this.setState({waiting:false})
417 console.log('error', err);
418 }
419 }
420
421 checkHistory = () => {
422 const url = this.state.url + 'API/Activity/GetResultEvaluation';
423 this.setState({ waiting: true })
424 Axios.get(url,
425 {
426 headers: { sessionCd: this.state.sessionCd
427 },
428 params:{
429 evalId : this.state.evalId,
430 csId : this.state.csId,
431 } })
432 .then(res => {
433 let data = res.data.data;
434 //console.log('result',res.data)
435
436 if(res.data.result){
437 this.setState({
438 waiting: false,
439 },function(){
440 // if(data!=null && data[0].group[0].totalFinish>0){
441 if(data!=null){
442 this.setState({historyEvaluation: data}, function(){
443 this.checkHistoryPica()
444 })
445 }else{
446 const resetAction = StackActions.reset({
447 index: 1,
448 actions: [
449 NavigationActions.navigate({ routeName: 'Content' }),
450 NavigationActions.navigate({ routeName: 'GenbaEvaluation',params: {
451 data: this.state,
452 }, }),
453 ],
454 key: null
455 });
456 this.props.navigation.dispatch(resetAction);
457 }
458 })
459 }else{
460 this.setState({
461 loading: false,
462 waiting:false
463 })
464 if(res.data.message=='Session Expired'){
465 ToastAndroid.showWithGravity(
466 res.data.message,
467 ToastAndroid.SHORT,
468 ToastAndroid.CENTER|ToastAndroid.BOTTOM,
469 );
470 AsyncStorage.removeItem('isLogin');
471 AsyncStorage.removeItem('sessionCd');
472 this.props.navigation.navigate('Auth');
473 }
474 }
475
476 })
477 .catch(error => {
478 // //console.warn(error);
479 this.setState({ loading: false, waiting: false, error: 'Something just went wrong' })
480 ToastAndroid.showWithGravity(
481 "No Internet Connection",
482 ToastAndroid.SHORT,
483 ToastAndroid.CENTER,
484 );
485 });
486 }
487
488 checkHistoryPica = () => {
489 const url = this.state.url + 'API/Activity/GetResultPica';
490 this.setState({ waiting: true })
491 Axios.get(url,
492 {
493 headers: { sessionCd: this.state.sessionCd
494 },
495 params:{
496 evalId : this.state.evalId,
497 } })
498 .then(res => {
499 let data = res.data.data;
500 if(res.data.result){
501 this.setState({
502 waiting: false,
503 },function(){
504 this.setState({historyPica: data}, function(){
505 this.fetchHistory()
506 })
507 })
508 }else{
509 this.setState({
510 loading: false,
511 waiting:false
512 })
513 if(res.data.message=='Session Expired'){
514 ToastAndroid.showWithGravity(
515 res.data.message,
516 ToastAndroid.SHORT,
517 ToastAndroid.CENTER|ToastAndroid.BOTTOM,
518 );
519 AsyncStorage.removeItem('isLogin');
520 AsyncStorage.removeItem('sessionCd');
521 this.props.navigation.navigate('Auth');
522 }
523 }
524
525 })
526 .catch(error => {
527 // //console.warn(error);
528 this.setState({ loading: false, waiting: false, error: 'Something just went wrong' })
529 ToastAndroid.showWithGravity(
530 "No Internet Connection",
531 ToastAndroid.SHORT,
532 ToastAndroid.CENTER,
533 );
534 });
535 }
536
537 fetchHistory = async () =>{
538 let dataEval = this.state.historyEvaluation;
539 let dataPica = this.state.historyPica;
540 console.log('Fetch History', dataEval, dataPica)
541 let checkEval = realm.objects(TRANS_HEAD_SCHEMA).filtered('evalId = ' + this.state.evalId)
542 if(checkEval.length>0){
543 this.setState({waiting:false})
544 const resetAction = StackActions.reset({
545 index: 1,
546 actions: [
547 NavigationActions.navigate({ routeName: 'Content' }),
548 NavigationActions.navigate({ routeName: 'GenbaEvaluation',params: {
549 data: this.state,
550 }, }),
551 ],
552 key: null
553 });
554 this.props.navigation.dispatch(resetAction);
555 }else{
556
557 let group = dataEval[0].group;
558 let chapter = dataEval[0].chapter;
559 let item = dataEval[0].item;
560 let quest = dataEval[0].quest;
561 let objects = dataEval[0].objects;
562 let method = dataEval[0].method;
563 let itemPhoto = dataEval[0].itemPhoto;
564 let questPhoto = dataEval[0].questPhoto;
565 let objectPhoto = dataEval[0].objectPhoto;
566 let methodPhoto = dataEval[0].methodPhoto;
567 let arrGroup = []
568 let arrChapter = []
569 let arrItem = []
570 let arrQuest = []
571 let arrObject = []
572 let arrMethod = []
573 let arrTransHead = []
574 let arrTransDetailChoice = []
575 let arrItemPhoto = []
576 let arrQuestPhoto = []
577 let arrObjectPhoto = []
578 let arrMethodPhoto = []
579 let arrPica = []
580
581 let groupItem = realm.objects(GROUP_ITEM_SCHEMA)
582 groupItem.reduce((result,val) =>{
583 let chapter = realm.objects(CHAPTER_SCHEMA).filtered('groupId = ' + val.groupId)
584 let groupFilter = group.filter((item) => item.groupId == val.groupId);
585
586 arrGroup.push({
587 id: this.state.evalId+'.'+val.groupId,
588 evalId: parseInt(this.state.evalId),
589 groupId: parseInt(val.groupId),
590 groupSeq: parseInt(val.groupSeq),
591 totalFinish: parseInt(groupFilter.length>0 ? groupFilter[0].totalFinish : 0),
592 totalPage: parseInt(chapter.length),
593 totalPercent: parseInt(groupFilter.length>0 ? groupFilter[0].totalPercent : 0),
594 })
595 },{})
596
597 chapter.reduce((result,val) =>{
598 arrChapter.push({
599 id: val.evalId +'.'+val.groupId+'.'+val.chapterId,
600 evalId: parseInt(val.evalId),
601 groupId: parseInt(val.groupId),
602 chapterId: parseInt(val.chapterId),
603 chapterSeq: parseInt(val.chapterSeq),
604 totalFinish: parseInt(val.totalFinish),
605 totalPage: parseInt(val.totalPage),
606 totalPercent: parseInt(val.totalPercent),
607 })
608 },{})
609
610 item.reduce((result,val) =>{
611 arrItem.push({
612 id: val.evalId +'.'+val.chapterId+'.'+val.itemId,
613 evalId: parseInt(val.evalId),
614 chapterId: parseInt(val.chapterId),
615 itemId: parseInt(val.itemId),
616 totalFinish: parseInt(val.totalFinish),
617 totalPage: parseInt(val.totalPage),
618 totalPercent: parseInt(val.totalPercent),
619 })
620
621 arrTransHead.push({
622 id: val.evalId +'.'+val.chapterId+'.'+val.itemId,
623 evalId: parseInt(val.evalId),
624 chapterId: parseInt(val.chapterId),
625 itemId: parseInt(val.itemId)
626 })
627 },{})
628
629 quest.reduce((result,val) =>{
630 arrQuest.push({
631 id: val.evalId +'.'+val.questId+'.'+val.itemId,
632 evalId: parseInt(val.evalId),
633 questId: parseInt(val.questId),
634 itemId: parseInt(val.itemId),
635 totalFinish: parseInt(val.totalFinish),
636 totalPage: parseInt(val.totalPage),
637 totalPercent: parseInt(val.totalPercent),
638 })
639 },{})
640
641 objects.reduce((result,val) =>{
642 arrObject.push({
643 id: val.evalId +'.'+val.objectId+'.'+val.questId,
644 evalId: parseInt(val.evalId),
645 objectId: parseInt(val.objectId),
646 questId: parseInt(val.questId),
647 totalFinish: parseInt(val.totalFinish),
648 totalPage: parseInt(val.totalPage),
649 totalPercent: parseInt(val.totalPercent),
650 })
651 },{})
652
653 method.reduce((result,val) =>{
654 arrMethod.push({
655 id: val.evalId +'.'+val.itemId+'.'+val.methodId,
656 evalId: parseInt(val.evalId),
657 itemId: parseInt(val.itemId),
658 objectId: parseInt(val.objectId),
659 methodId: parseInt(val.methodId),
660 button: val.button,
661 result: val.result.toString(),
662 totalFinish: parseInt(val.totalFinish),
663 totalPage: parseInt(val.totalPage),
664 totalPercent: parseInt(val.totalPercent),
665 })
666
667 arrTransDetailChoice.push({
668 id: val.evalId +'.'+val.itemId+'.'+val.methodId,
669 evalId: parseInt(val.evalId),
670 itemId: parseInt(val.itemId),
671 objectId: parseInt(val.objectId),
672 methodId: parseInt(val.methodId),
673 button: val.button,
674 result: val.result.toString()
675 })
676 },{})
677
678 let countItem = realm.objects(TRANS_DETAIL_ITEM_SCHEMA)
679 let xItem = countItem.length
680 itemPhoto.reduce(async (result,val) =>{
681 console.log('loop photo', val)
682 const url = this.state.url+val.picture;
683 const newImageName = `${Moment().format('DDMMYY_HHmmssSSS_'+ xItem +1)}.jpg`;
684 const newFilepath = `${dirPicutures}/${newImageName}`;
685
686 arrItemPhoto.push({
687 id: xItem + 1,
688 itemId: val.itemId,
689 picture: newFilepath,
690 })
691 xItem++;
692 const download = await downloadFile(url, newFilepath);
693
694 },{})
695
696 console.log('arrItemPhoto', arrItemPhoto)
697
698 let countQuest = realm.objects(TRANS_DETAIL_QUEST_SCHEMA)
699 let xQuest = countQuest.length
700 questPhoto.reduce(async (result,val) =>{
701 console.log('loop photo', val)
702 const url = this.state.url+val.picture;
703 const newImageName = `${Moment().format('DDMMYY_HHmmssSSS'+ xQuest +1)}.jpg`;
704 const newFilepath = `${dirPicutures}/${newImageName}`;
705
706 arrQuestPhoto.push({
707 id: xQuest + 1,
708 questId: val.questId,
709 picture: newFilepath,
710 })
711 xQuest++;
712 const download = await downloadFile(url, newFilepath);
713
714 },{})
715
716 console.log('arrQuestPhoto', arrQuestPhoto)
717
718 let countObject = realm.objects(TRANS_DETAIL_OBJECT_SCHEMA)
719 let xObject = countObject.length
720 objectPhoto.reduce(async (result,val) =>{
721 console.log('loop photo', val)
722 const url = this.state.url+val.picture;
723 const newImageName = `${Moment().format('DDMMYY_HHmmssSSS'+ xObject +1)}.jpg`;
724 const newFilepath = `${dirPicutures}/${newImageName}`;
725
726 arrObjectPhoto.push({
727 id: xObject + 1,
728 objectId: val.objectId,
729 picture: newFilepath,
730 })
731 xObject++;
732 const download = await downloadFile(url, newFilepath);
733
734 },{})
735
736 console.log('arrObjectPhoto', arrObjectPhoto)
737
738 let countMethod = realm.objects(TRANS_DETAIL_METHOD_SCHEMA)
739 let xMethod = countMethod.length
740 methodPhoto.reduce(async (result,val) =>{
741 console.log('loop photo', val)
742 const url = this.state.url+val.picture;
743 const newImageName = `${Moment().format('DDMMYY_HHmmssSSS'+ xMethod +1)}.jpg`;
744 const newFilepath = `${dirPicutures}/${newImageName}`;
745
746 arrMethodPhoto.push({
747 id: xMethod + 1,
748 methodId: val.methodId,
749 picture: newFilepath,
750 })
751 xMethod++;
752 const download = await downloadFile(url, newFilepath);
753
754 },{})
755
756 console.log('arrMethodPhoto', arrMethodPhoto)
757
758 if(dataPica!=null){
759 dataPica.reduce(async (result, val) =>{
760 const url = this.state.url+val.imgBefore;
761 const newImageName = `${Moment().format('DDMMYY_HHmmssSSS'+ val.itemId)}.jpg`;
762 const newFilepath = `${dirPicutures}/${newImageName}`;
763 arrPica.push({
764 picaId: val.evalId+'.'+val.itemId,
765 evalId: parseInt(val.evalId),
766 itemId: parseInt(val.itemId),
767 dueDate: val.dueDate,
768 issue: val.issue,
769 action: val.action,
770 priorityId: parseInt(val.prioritySeq),
771 priorityName: val.priority,
772 pic: val.pic,
773 beforePath: newFilepath,
774 })
775 const download = await downloadFile(url, newFilepath);
776 },{})
777 }
778
779 try{
780 realm.write(() => {
781 arrGroup.forEach(obj => {
782 realm.create(TEMP_GROUP_SCHEMA, obj, true);
783 });
784 arrChapter.forEach(obj => {
785 realm.create(TEMP_CHAPTER_SCHEMA, obj, true);
786 });
787 arrItem.forEach(obj => {
788 realm.create(TEMP_ITEM_SCHEMA, obj, true);
789 });
790 arrQuest.forEach(obj => {
791 realm.create(TEMP_QUEST_SCHEMA, obj, true);
792 });
793 arrObject.forEach(obj => {
794 realm.create(TEMP_OBJECT_SCHEMA, obj, true);
795 });
796 arrMethod.forEach(obj => {
797 realm.create(TEMP_METHOD_SCHEMA, obj, true);
798 });
799
800 arrPica.forEach(obj => {
801 realm.create(PICA_SCHEMA, obj, true);
802 });
803
804 arrTransHead.forEach(obj => {
805 let trans = realm.create(TRANS_HEAD_SCHEMA, obj, true);
806 // console.log('trans object', obj.evalId,obj.itemId)
807 let detail = arrItemPhoto.filter((item) => item.itemId==obj.itemId)
808 let question = arrQuest.filter((item) => item.evalId==obj.evalId && item.itemId==obj.itemId)
809 // console.log('trans question', question.length)
810 question.reduce((result,val)=>{
811 let questPic = arrQuestPhoto.filter((item) => item.questId==val.questId);
812 let object = arrObject.filter((item) => item.questId==val.questId);
813
814 if(questPic.length>0){
815 //get quest photo
816 questPic.reduce((result,val) =>{
817 trans.question.push({
818 id: val.id,
819 questId: val.questId,
820 picture: val.picture
821 })
822 },{})
823 }
824
825 //get object photo
826 object.reduce((result,val) =>{
827 let objectPic = arrObjectPhoto.filter((item) => item.objectId==val.objectId);
828 let method = arrMethod.filter((item) => item.objectId==val.objectId);
829 if(objectPic.length>0){
830 objectPic.reduce((result,val) =>{
831 trans.object.push({
832 id: val.id,
833 objectId: val.objectId,
834 picture: val.picture
835 })
836 },{})
837 }
838
839 method.reduce((result,val) =>{
840 let methodPic = arrMethodPhoto.filter((item) => item.methodId==val.methodId);
841 if(methodPic.length>0){
842 methodPic.reduce((result,val) =>{
843 trans.method.push({
844 id: val.id,
845 methodId: val.methodId,
846 picture: val.picture
847 })
848 },{})
849 }
850 },{})
851
852 },{})
853
854
855 },{})
856
857 let choice = arrTransDetailChoice.filter((item) => item.evalId==obj.evalId && item.itemId==obj.itemId)
858 // console.log('trans choice', choice)
859 detail.reduce((result,val) =>{
860 trans.detail.push({
861 id: val.id,
862 picture: val.picture
863 })
864 },{})
865
866 choice.reduce((result,val) =>{
867 trans.choice.push({
868 id: val.evalId+"."+val.itemId+"."+val.methodId,
869 evalId: parseInt(val.evalId),
870 itemId: parseInt(val.itemId),
871 objectId: parseInt(val.objectId),
872 methodId: parseInt(val.methodId),
873 button: val.button,
874 result: val.result
875 })
876 },{})
877
878 });
879
880 arrTransDetailChoice.forEach(obj => {
881 realm.create(TRANS_DETAIL_CHOICE_SCHEMA, obj, true);
882 });
883
884 this.setState({waiting:false})
885 const resetAction = StackActions.reset({
886 index: 1,
887 actions: [
888 NavigationActions.navigate({ routeName: 'Content' }),
889 NavigationActions.navigate({ routeName: 'GenbaEvaluation',params: {
890 data: this.state,
891 }, }),
892 ],
893 key: null
894 });
895 this.props.navigation.dispatch(resetAction);
896
897 })
898 }catch(err){
899 console.log('error', err)
900 }
901 }
902
903
904}
905
906 callLocation(that){
907 //alert("callLocation Called");
908 that.setState({ waiting:true })
909 Geolocation.getCurrentPosition(
910 //Will give you the current location
911 (position) => {
912 const currentLongitude = JSON.stringify(position.coords.longitude);
913 //getting the Longitude from the location json
914 const currentLatitude = JSON.stringify(position.coords.latitude);
915 //getting the Latitude from the location json
916 that.setState({ currentLongitude:currentLongitude });
917 //Setting state Longitude to re re-render the Longitude Text
918 that.setState({ currentLatitude:currentLatitude });
919 //Setting state Latitude to re re-render the Longitude Text
920
921 var NY = {
922 lat: position.coords.latitude,
923 lng: position.coords.longitude
924 };
925
926 that.checkRadius();
927
928 Geocoder.geocodePosition(NY).then(res => {
929 // res is an Array of geocoding object (see below)
930 that.setState({ currentAddress:res[0].formattedAddress, waiting:false },function(){
931
932 });
933
934 // //console.warn(res[0].formattedAddress);
935 })
936 .catch(
937 // err => that.setState({waiting:false})
938 err => {that.error(err)}
939 );
940
941 },
942 (error) => {that.error(error)},
943 { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
944 );
945 that.watchID = Geolocation.watchPosition((position) => {
946 //Will give you the location on location change
947 //console.log(position);
948 const currentLongitude = JSON.stringify(position.coords.longitude);
949 //getting the Longitude from the location json
950 const currentLatitude = JSON.stringify(position.coords.latitude);
951 //getting the Latitude from the location json
952 that.setState({ currentLongitude:currentLongitude });
953 //Setting state Longitude to re re-render the Longitude Text
954 that.setState({ currentLatitude:currentLatitude });
955 //Setting state Latitude to re re-render the Longitude Text
956
957 var NY = {
958 lat: position.coords.latitude,
959 lng: position.coords.longitude
960 };
961
962 that.checkRadius();
963
964 Geocoder.geocodePosition(NY).then(res => {
965 // res is an Array of geocoding object (see below)
966 that.setState({ currentAddress:res[0].formattedAddress, waiting:false });
967 // //console.warn(res[0].formattedAddress);
968 })
969 .catch(err => {that.error(err)});
970 // -6.936444, 107.626346
971 });
972 }
973
974 error = (err) =>{
975 //console.log('error', err);
976 }
977 componentWillUnmount = () => {
978 //console.log('clear watch location')
979 Geolocation.clearWatch(this.watchID);
980 }
981
982 checkConnection = () =>{
983 var that = this;
984 NetInfo.fetch().then(state => {
985 if(state.isConnected){
986 // this.requestStoragePermission()
987 this.startEvaluation()
988 }else{
989 showToast("No Internet Connection")
990 }
991 });
992 }
993
994 async requestStoragePermission () {
995 try {
996 const granted = await PermissionsAndroid.request(
997 PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
998 )
999 if (granted === PermissionsAndroid.RESULTS.GRANTED) {
1000 this.startEvaluation()
1001 } else {
1002 alert("Storage permission denied")
1003 }
1004 } catch (err) {
1005 //console.log(err)
1006 }
1007 }
1008
1009 startEvaluation = () =>{
1010 // //console.log(this.state);
1011 // this.props.navigation.navigate('GenbaEvaluation', {data: this.state});
1012 var that = this;
1013 this.setState({ textLoading: 'Loading...',waiting:true }, function(){
1014 //console.log(Moment(new Date()).format('YYYY-MM-DD'))
1015 const url = this.state.url + 'API/Activity/SetinProgress';
1016 Moment.locale('en');
1017 var params = new URLSearchParams();
1018 params.append('evalId', this.state.evalId);
1019 params.append('startedDt', Moment(new Date()).format('YYYY-MM-DD'));
1020 params.append('location', this.state.currentAddress);
1021 params.append('latitude', this.state.currentLatitude);
1022 params.append('longitude', this.state.currentLongitude);
1023 params.append('outletSts', this.state.outletSts);
1024 params.append('withoutEm', this.state.em ? 1 : 0);
1025
1026 Axios.post(url, params,{headers :{sessionCd: this.state.sessionCd} })
1027 .then(function (response) {
1028 //console.log(response);
1029 if(response.data.result){
1030 //console.log('success');
1031 this.setState({waiting:false})
1032
1033 // this.props.navigation.navigate('GenbaEvaluation', {data: this.state});
1034 AsyncStorage.setItem('em', this.state.em ? 'true' : 'false');
1035 this.checkHistory()
1036
1037 }else{
1038 //console.log('failed');
1039 this.setState({waiting:false})
1040 showToast(response.data.message)
1041 }
1042 }.bind(this))
1043 .catch(function (error) {
1044 //console.log('error');
1045 this.setState({waiting:false})
1046 showToast("Network error occured")
1047 }.bind(this));
1048 }.bind(this))
1049 }
1050
1051 evalMaps = () =>{
1052 this.props.navigation.navigate('EvaluationMaps');
1053 }
1054
1055 optionEM = () => {
1056 BottomSheet.showBottomSheetWithOptions({
1057 options: ['EM', 'Non EM'],
1058 title: 'Status EM',
1059 dark: false,
1060 cancelButtonIndex: 2,
1061 }, (val) => {
1062 //console.log(val)
1063 this.setState({em: val, emText: val > 0 ? 'Non EM' : 'EM'})
1064 });
1065 }
1066
1067 optionStatus = () => {
1068 let statusObj = realm.objects(SYSTEM_MASTER_SCHEMA).filtered('systemType = "OUTLET_STS"')
1069 let optionSts = [];
1070 statusObj.reduce((result,val) =>{
1071 optionSts.push(val.systemValueTxt)
1072 },[])
1073
1074 //console.log(optionSts);
1075
1076 BottomSheet.showBottomSheetWithOptions({
1077 options: optionSts,
1078 title: 'Status',
1079 dark: false,
1080 cancelButtonIndex: 2,
1081 }, (val) => {
1082 //console.log(val,optionSts[val])
1083 this.setState({outletSts: val, outletStsNm: optionSts[val]})
1084 });
1085 }
1086
1087 render() {
1088 Moment.locale('en');
1089 const { navigate } = this.props.navigation;
1090 return (
1091 <View style={styles.container}>
1092 <Spinner
1093 //visibility of Overlay Loading Spinner
1094 visible={this.state.waiting}
1095 //Text with the Spinner
1096 textContent={this.state.textLoading}
1097 //Text style of the Spinner Text
1098 textStyle={styles.spinnerTextStyle}
1099 />
1100 <View style={{margin: 20}}>
1101 <Image
1102 style={{width: 32, height: 32}}
1103 source={require('./images/writing.png')}/>
1104 <Text style={{
1105 position: 'absolute', top : 0,
1106 left: 40,
1107 fontSize: 14
1108 }}>{this.state.outletNm}</Text>
1109 <Text style={{
1110 position: 'absolute', top : 15,
1111 left: 40,
1112 fontSize: 11,
1113 color: 'grey'
1114 }}>{this.state.areaNm!='' ? this.state.areaNm +' - '+ this.state.subAreaNm + ' - ' + this.state.dealerNm: ''}</Text>
1115 </View>
1116 <View style={styles.separator}></View>
1117 <View style={{
1118 marginRight: 20,
1119 marginLeft: 20,
1120 marginTop: 10,
1121 marginBottom: 10,
1122 }}>
1123 <Text style={{
1124 color: 'grey'
1125 }}>Checksheet</Text>
1126 <Text style={{
1127 }}>{this.state.csTitle}</Text>
1128 </View>
1129 <View style={styles.separator}></View>
1130 <View style={{
1131 marginRight: 20,
1132 marginLeft: 20,
1133 marginTop: 10,
1134 marginBottom: 10,
1135 }}>
1136 <Text style={{
1137 color: 'grey'
1138 }}>Evaluator</Text>
1139 <Text style={{
1140 }}>{this.state.username}</Text>
1141 </View>
1142 <View style={styles.separator}></View>
1143 <View style={{
1144 marginRight: 20,
1145 marginLeft: 20,
1146 marginTop: 10,
1147 marginBottom: 10,
1148 }}>
1149 <Text style={{
1150 color: 'grey'
1151 }}>Evaluation Date</Text>
1152 <Text style={{
1153 }}>{Moment(this.state.currentDate).format('DD MMMM YYYY')}</Text>
1154
1155
1156 </View>
1157 <View style={styles.separator}></View>
1158
1159 <View style={styles.separator}></View>
1160 {
1161 this.state.roleId.toUpperCase()=='ADMIN_SURVEY' || this.state.roleId.toUpperCase()=='EVALUATOR_SURVEY' ? null :
1162 <View>
1163 <View style={{
1164 marginRight: 20,
1165 marginLeft: 20,
1166 marginTop: 10,
1167 marginBottom: 10,
1168 }}>
1169 <Text style={{
1170 color: 'grey'
1171 }}>Status</Text>
1172 <TouchableOpacity style={{flexDirection: 'row' }}
1173 onPress={this.optionStatus}>
1174 <Text style={{marginRight: 10,textAlign:'center'}}><Icon style={{
1175 marginRight: 10 }}
1176 name={'chevron-down'} size={15}
1177 />
1178 </Text>
1179 <Text style={{textAlign: 'center'}}>{this.state.outletStsNm}</Text>
1180
1181 </TouchableOpacity>
1182
1183 </View>
1184 <View style={styles.separator}></View>
1185 <View style={{
1186 marginRight: 20,
1187 marginLeft: 20,
1188 marginTop: 10,
1189 marginBottom: 10,
1190 }}>
1191 <Text style={{
1192 color: 'grey'
1193 }}>Status EM</Text>
1194 <TouchableOpacity style={{flexDirection: 'row' }}
1195 onPress={this.state.progressSts==2 ? null : this.optionEM}>
1196 <Text style={{marginRight: 10,textAlign:'center'}}><Icon style={{
1197 marginRight: 10 }}
1198 name={'chevron-down'} size={15}
1199 />
1200 </Text>
1201 <Text style={{textAlign: 'center'}}>{this.state.emText}</Text>
1202
1203 </TouchableOpacity>
1204
1205 </View>
1206 </View>
1207 }
1208 <View style={styles.separator}></View>
1209 <View style={{
1210 marginRight: 20,
1211 marginLeft: 20,
1212 marginTop: 10,
1213 marginBottom: 10,
1214 }}>
1215 <Text style={{
1216 color: 'grey'
1217 }}>Location</Text>
1218 <TouchableOpacity
1219 onPress={this.evalMaps}
1220 style={{flexDirection: 'row'}}>
1221 <Text style={{width:'90%'}}>{this.state.currentAddress}</Text>
1222 <Text style={{margin: 5,textAlign:'center'}}><Icon style={{
1223 marginLeft:10, marginRight: 5, color:'#767DA5' }}
1224 name={'map-marker'} size={24}
1225 />
1226 </Text>
1227
1228 </TouchableOpacity>
1229 </View>
1230
1231
1232 {/* <View style={styles.separator}></View> */}
1233 <View style={styles.bottomView}>
1234 <View style={styles.separator}></View>
1235 <View style={styles.btn_start}>
1236 <Button title={this.state.progressSts==2 ? "Continue Evaluation" : "Start Evaluation"}
1237 buttonStyle={styles.button}
1238 onPress={this.checkConnection}
1239 disabled={!this.state.radiusSts}
1240 />
1241 </View>
1242
1243 </View>
1244 </View>
1245 );
1246 }
1247}
1248const styles = StyleSheet.create({
1249 container: {
1250 flex: 1,
1251 backgroundColor: '#fff',
1252 },
1253 separator:{
1254 width: '100%', height:1, backgroundColor: '#eeeeee'
1255 },
1256 bottomView:{
1257 width: width,
1258 height: 75,
1259 justifyContent: 'center',
1260 alignItems: 'center',
1261 position: 'absolute',
1262 bottom: 0
1263 },
1264 btn_start: {
1265 marginBottom: 15,
1266 marginTop: 10,
1267 width: '90%',
1268 fontSize: 24,
1269 fontFamily: 'Poppins',
1270 },
1271 button: {
1272 backgroundColor: 'red',
1273 borderWidth: 5,
1274 borderRadius: 15,
1275 borderColor: '#fff'
1276 },
1277 spinnerTextStyle: {
1278 color: '#FFF',
1279 },
1280});