HomeContainer.js 12.8 KB
Newer Older
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
1 2 3
/* eslint-disable prettier/prettier */
import Moment from 'moment';
import React, {useCallback, useEffect, useState} from 'react';
4 5
import {
  Alert,
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
6
  BackHandler,
7
  Image,
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
8 9 10 11
  Linking,
  Platform,
  TouchableOpacity,
  View,
12 13 14 15
} from 'react-native';
import {launchImageLibrary} from 'react-native-image-picker';
import Swiper from 'react-native-swiper';
import Toast from 'react-native-toast-message';
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
16 17 18 19 20 21 22 23 24
import {useDispatch} from 'react-redux';
import AppText from '../../components/AppText';
import {
  getBirthDayUserByDate,
  getNotificationOfUser,
  getPersonnel,
  sendNotification,
} from '../../store/actions/UserAction';
import {IMAGES} from '../../values/images';
25
import ProfileUserComponent from './components/ProfileUserComponent';
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
26 27 28 29 30 31 32 33
import homePropsProvider from './homePropsProvider';
import {
  getBirthDayUser,
  getRadomQuotation,
  getUserDirectManagers,
} from './homeSlice';
import styles from './style';
import HomeMainView from './template/HomeMainView';
34

quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
35
const HomeContainer = props => {
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
36
  const {userInfo, quotationList, birthdayListInMonth, randomQuotation} = props;
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  const dispatch = useDispatch();

  const [arrPersonnel, setArrPersonnel] = useState([]);
  //console.log('userDetails', userDetails);
  const dataBirthday = [
    {
      id: 0,
      name: 'Tiến Dũng',
      position: 'Phó giám đốc',
    },
    {
      id: 1,
      name: 'Vĩnh Lộc',
      position: 'Trưởng phòng nhân sự',
    },
    {
      id: 2,
      name: 'Phước Vũ',
      position: 'Trường phòng test',
    },
    {
      id: 3,
      name: 'Thanh Bình',
      position: 'Trưởng phòng test',
    },
  ];

  const [openView, setOpenView] = useState([
    {enable: false},
    {enable: false},
    {enable: false},
    {enable: false},
  ]);
  const [bdUserCurrentMonth, setArrBdCurrentMonth] = useState();
  const [birthdayOfUser, setBirthOfUser] = useState();
  //deep link imcheckin
  const supportedURL = 'im-checkin://login_step_2';
  const chPlayLink =
    'https://play.google.com/store/apps/details?id=com.imchecking';
  const appStore = 'https://apps.apple.com/vn/app/imcheckin/id1545100199?l=vi';

  {
    /* modal - item birthdayArr - Image*/
  }
  const [modalVisible, setModalVisible] = useState({
    isVisible: false,
    birthdayArr: null,
    day: '',
    managerOpenWish: [],
  });

quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
88
  const [openProfileComponent, setOpenProfileComponent] = useState(false);
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  {
    /**wish birthday */
  }
  const [wishTxt, setWishTxt] = useState();
  const [wishList, setWishList] = useState([]);

  // main function
  const loadListPersonnel = async () => {
    const res = await dispatch(getPersonnel());
    if (res && res.length > 0) {
      //console.log(res);
      setArrPersonnel(res);
    }
  };

  const handleOpenDesBirthday = useCallback(
    day => {
      const formatDate = `${day.day < 10 ? `0${day.day}` : `${day.day}`}-${
        day.month < 10 ? `0${day.month}` : `${day.month}`
      }-${day.year}`;
      let arrBdUser = [];
      let lengthKey = [];
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
111
      for (const [key, value] of Object.entries(birthdayListInMonth)) {
112 113 114 115 116 117 118 119 120 121 122 123 124
        if (key.includes(formatDate)) {
          arrBdUser.push(...value);
          value.forEach(item => lengthKey.push({enable: false}));
        }
      }
      // console.log("lengthKey", lengthKey)
      setModalVisible({
        isVisible: true,
        birthdayArr: arrBdUser,
        day: day,
        managerOpenWish: lengthKey,
      });
    },
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
125
    [birthdayListInMonth],
126
  );
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
127
  const handleCloseDesBirthday = () =>
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    setModalVisible({
      isVisible: false,
      birthdayArr: null,
      day: '',
      managerOpenWish: [],
    });
  const OpenURLButton = async () => {
    const supported = await Linking.canOpenURL(supportedURL);

    if (supported) {
      // Opening the link with some app, if the URL scheme is "http" the web link should be opened
      // by some browser in the mobile
      await Linking.openURL(supportedURL);
    } else {
      if (Platform.OS === 'ios') {
        await Linking.openURL(appStore);
      } else {
        await Linking.openURL(chPlayLink);
      }
    }
  };
  const openModalHappyBirthday = index => {
    //console.log("item", index)
    let newState = [...openView];
    newState[index].enable = true;
    setOpenView(newState);
    //setOpenView(state => ({ ...state, [openView[index].enable]: true }))
  };
  const closeModalHappyBirthday = index => {
    let newState = [...openView];
    newState[index].enable = false;
    setOpenView(newState);
  };
  const openModalWishBirthday = index => {
    //console.log("item", index)
    let managerOpenWish = [...modalVisible.managerOpenWish];
    managerOpenWish[index].enable = true;
    setModalVisible(prev => ({...prev, managerOpenWish}));
    // console.log("clone", clone)
  };
  const closeModalWishBirthday = index => {
    let managerOpenWish = [...modalVisible.managerOpenWish];
    managerOpenWish[index].enable = false;
    setModalVisible(prev => ({...prev, managerOpenWish}));
  };
  const sendWishBirthday = async (approver, index) => {
    //console.log('user', user);

    if (!wishTxt) {
      return;
    }
    const {imgArr} = modalVisible.birthdayArr[0];
    //console.log('imgArr', imgArr);
    const res = await dispatch(
      sendNotification(
        approver.id,
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
184
        userInfo.id,
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        imgArr,
        'Lời chúc sinh nhật',
        wishTxt,
        208,
        'sinh nhật',
      ),
    );
    if (res) {
      setWishTxt();
      closeModalWishBirthday(index);
      Toast.show({
        type: 'success',
        text1: `Hệ thống`,
        text2: `Gửi lời chúc thành công`,
        style: {zIndex: 1001},
        visibilityTime: 2000,
      });
    }
  };
  const loadWishUser = async () => {
    const arrNoti = await dispatch(
      getNotificationOfUser(
        `?Filters=${encodeURIComponent(
          `created_at>=${Moment()
            .startOf('year')
            .format('YYYY-MM-DD')},sub_category_type==208`,
        )}`,
      ),
    );

    //console.log('arrNoti', arrNoti);
    if (arrNoti) {
      setWishList(arrNoti);
    }
  };
  const formatDateList = async () => {
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    if (birthdayListInMonth) {
      var size = Object.keys(birthdayListInMonth).length;
      const today = new Date();
      const formatToday = Moment(today).format('DD-MM-YYYY');
      // console.log(formatToday)
      // console.log('size', size)
      if (size >= 1) {
        let lstBdUser = [];
        for (const [key, value] of Object.entries(birthdayListInMonth)) {
          if (value.length > 0) {
            //console.log("key", value)
            if ([key].length > 0) {
              const formatToday = [key];
              const arr = formatToday[0].split('-');
              const res = arr[2] + '-' + arr[1] + '-' + arr[0];
              // console.log('formatToday', arr[2] + '-' + arr[1] + '-' + arr[0])
              lstBdUser.push({
                [res]: {marked: true, dotColor: 'red', activeOpacity: 0},
              });
            }
241
          }
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
242 243 244 245 246 247 248 249 250 251
          if (key.includes(formatToday)) {
            const lengthObj = birthdayListInMonth[key];
            //console.log("lengthObj", lengthObj);
            if (lengthObj.length <= 0) {
            } else {
              lengthObj.forEach(o => {
                //console.log("nameUser", name)
                setBirthOfUser(lengthObj);
              });
            }
252 253
          }
        }
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
254

quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
255 256
        const convertArr = Object.assign({}, ...lstBdUser);
        setArrBdCurrentMonth(convertArr);
257 258 259
      }
    }
  };
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
260

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
  const onCalendarChangeMonth = time => {
    dispatch(getBirthDayUserByDate(time.month, time.year));
  };
  const addMoreImgFromGallery = index => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: true,
      },
      response => {
        //console.log('res', response);
        if (!response.didCancel) {
          //console.log('res', response.assets)
          const {assets} = response;
          //console.log('res', assets)
          let clone = modalVisible.birthdayArr;
          //console.log("index", clone[index])
          clone[index].imgArr = assets;
          //console.log('index', clone);

          setModalVisible(prev => ({...prev, birthdayArr: clone}));
          //console.log("index", clone[index])
        }
      },
    );
  };
  // component
  const SlidePersonnel = () => {
    // console.log('arrPersonnel', arrPersonnel);
    return (
      <Swiper
        style={{
          height: 300,
        }}
        showsButtons={false}
        loop={false}
        showsPagination={false}
        autoplay
        autoplayTimeout={5}
        activeDot={
          <View
            style={{
              backgroundColor: '#007aff',
              width: 25,
              height: 8,
              borderRadius: 4,
            }}
          />
        }>
        {arrPersonnel &&
          arrPersonnel.length > 0 &&
          arrPersonnel.map((item, index) => {
            //console.log(item);
            return (
              <View
                key={index}
                style={[
                  styles.viewContent,
                  {
                    justifyContent: 'center',
                    alignItems: 'center',
                  },
                ]}>
                <Image
                  source={
                    (item.cover_image && {
                      uri: 'https://meu.anawork.com' + item.cover_image,
                    }) ||
                    IMAGES.ImageCoverBg
                  }
                  style={styles.coverImage}
                />
                <TouchableOpacity
                  style={styles.viewAvatar}
                  onPress={() => OpenProfileUserComponent(item)}>
                  <Image
                    source={{
                      uri: 'https://meu.anawork.com' + item.avatar,
                    }}
                    style={styles.imgAvatar}
                  />
                </TouchableOpacity>
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
343
                <AppText style={{color: 'black', fontSize: 18}}>
344 345 346
                  {`${item.first_name} ${
                    item.middle_name ? item.middle_name : ''
                  } ${item.last_name}`}{' '}
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
347 348
                </AppText>
                <AppText style={{marginBottom: 20}}>{item.position}</AppText>
349 350 351 352 353 354 355 356 357
              </View>
            );
          })}
      </Swiper>
    );
  };
  const openCheckInPage = () => {
    // setOpenCheckIn(<CheckInPage />);
  };
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
358

359 360 361 362 363 364 365 366 367 368
  const chooseSettingView = () => {
    if (chooseSetting.title == 'Slide personnel') {
      setSettingView({
        isVisible: false,
        view: <SlidePersonnel />,
        title: 'Quotes',
      });
    } else {
      setSettingView({
        isVisible: false,
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
369
        view: <QuotesComponent quotation={quotationList} />,
370 371 372 373
        title: 'Slide personnel',
      });
    }
  };
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
374

375 376 377 378 379 380 381 382 383 384 385 386 387 388
  const OpenProfileUserComponent = info => {
    //console.log('info', info);
    return setOpenProfileComponent(
      <ProfileUserComponent
        userDetails={info}
        onClose={onCloseProfileComponent}
      />,
    );
  };
  const onCloseProfileComponent = () => {
    //console.log('onCloseProfileComponent');
    return setOpenProfileComponent();
  };

quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
  // fetch data
  const fetchQuotations = () => {
    dispatch(getRadomQuotation());
  };
  const fetchDirectManagers = () => {
    dispatch(getUserDirectManagers());
  };
  const fetchBirthDayUser = () => {
    const date = new Date();
    const month =
      date.getMonth() > 8 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
    //console.log(month)
    dispatch(getBirthDayUser({month, year: date.getFullYear()}));
  };
  const initialFetchData = () => {
    fetchQuotations();
    fetchBirthDayUser();
    loadWishUser();
    loadListPersonnel();
    fetchDirectManagers();
  };
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
  // useEffect
  useEffect(() => {
    const backAction = () => {
      Alert.alert('Hold on!', 'Are you sure you want to go back?', [
        {
          text: 'Cancel',
          onPress: () => null,
          style: 'cancel',
        },
        {text: 'YES', onPress: () => BackHandler.exitApp()},
      ]);
      return true;
    };
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
427
    initialFetchData();
428 429 430 431 432 433
    return () => {
      backHandler.remove();
    };
  }, []);

  useEffect(() => {
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
434 435
    birthdayListInMonth && formatDateList();
  }, [birthdayListInMonth]);
436 437 438

  //props
  const homeProps = {
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
439
    userInfo,
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
440
    quotationList,
441 442 443 444 445 446 447 448 449
    birthdayOfUser,
    dataBirthday,
    openView,
    bdUserCurrentMonth,
    modalVisible,
    arrPersonnel,
    wishTxt,
    wishList,
    openProfileComponent,
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
450
    randomQuotation,
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    chooseSettingView,
    OpenProfileUserComponent,
    setWishTxt,
    sendWishBirthday,
    SlidePersonnel,
    openModalHappyBirthday,
    closeModalHappyBirthday,
    openModalWishBirthday,
    closeModalWishBirthday,
    OpenURLButton,
    handleOpenDesBirthday,
    handleCloseDesBirthday,
    addMoreImgFromGallery,
    onCalendarChangeMonth,
    openCheckInPage,
  };
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
467
  return <HomeMainView {...homePropsProvider(homeProps)} />;
468 469 470
};

export default HomeContainer;