Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
17 kB
5
Indexable
Never
import React, {Component} from 'react';
import {
  ScrollView,
  StyleSheet,
  Text,
  View,
  Image,
  Alert,
  StatusBar,
  ActivityIndicator,
  Dimensions,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import {Hoshi} from 'react-native-textinput-effects';
import {Container, Header, Content, Button, Toast} from 'native-base';
import {connect} from 'react-redux';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {AsysnPass} from '../Utils/Constants';
import styles from './styles';
import APIChangeProfile from '../api/Authentication/APIChangeProfile';
import {
  validateEmail,
  validatePhoneNumber,
  validatePassPortNumber,
} from '../Utils/ValidateString';
import {setObjUser} from '@redux/reducer/userReducer';
import DatePicker from 'react-native-date-picker';
import {setMaxYear} from '../Utils/FormatDateTime';
import moment from 'moment';
import {ActionSheetCustom as ActionSheet} from 'react-native-custom-actionsheet';
import * as ImagePicker from 'react-native-image-picker';
import PostIDViettelOCR from '../api/Authentication/APIPostIDViettelOCR';
var screen = Dimensions.get('window');
const CANCEL_INDEX = 0;
const options = [
  'Hủy',
  {
    component: <Text style={{fontSize: 18, color: '#3366ff'}}>Chụp ảnh</Text>,
    height: 50,
  },
  {
    component: (
      <Text style={{fontSize: 18, color: '#3366ff'}}>Thư viện ảnh</Text>
    ),
    height: 50,
  },
];
class ChangeProfile extends Component {
  constructor(props) {
    super(props);
    const {FullName, DOB, Email, Phone, Address, passport} = this.props;
    if (DOB === null) {
      this.state = {
        fullname: FullName,
        dateOfBirth: '',
        phone: Phone,
        oldPhone: Phone,
        email: Email,
        address: Address,
        isDateTimePickerVisible: false,
        notification: '',
        passPort: passport,
      };
    } else {
      this.state = {
        fullname: FullName,
        dateOfBirth: moment(DOB.toString()).format('DD-MM-YYYY'),
        phone: Phone,
        oldPhone: Phone,
        email: Email,
        address: Address,
        isDateTimePickerVisible: false,
        notification: '',
        passPort: passport,
      };
    }
  }
  async componentWillMount() {
    const oldpassword = await AsyncStorage.getItem(AsysnPass);
    this.setState({
      oldPassword: oldpassword,
    });
  }
  backToLogin() {
    this.props.navigation.navigate('ManHinh_Account');
  }

  changeProfile() {
    const {UserId} = this.props;
    const {fullname, dateOfBirth, phone, email, address, passPort} = this.state;
    if (fullname === '') {
      this.setState(() => ({nameError3: 'Vui lòng nhập họ tên *'}));
    } else {
      this.setState(() => ({nameError3: null}));
    }

    if (dateOfBirth === '') {
      this.setState(() => ({nameError2: 'Vui lòng nhập ngày sinh '}));
    }
    if (moment(dateOfBirth, 'DD-MM-YYYY', true).isValid()) {
      this.setState(() => ({nameError2: null}));
    } else {
      // Alert.alert(dateOfBirth)
      this.setState(() => ({nameError2: 'Nhập sai định dạng ngày sinh '}));
    }

    if (passPort === '') {
      this.setState(() => ({passPortErr: 'Vui lòng nhập số CMT/CCCD/HC *'}));
    } else {
      if (validatePassPortNumber(passPort)) {
        this.setState(() => ({passPortErr: null}));
      } else {
        this.setState(() => ({
          passPortErr: 'Số CMT/CCCD/HC có ít nhất 8 ký tự *',
        }));
      }
    }
    if (phone === '') {
      this.setState(() => ({nameError5: 'Vui lòng nhập số điện thoại *'}));
    } else {
      if (validatePhoneNumber(phone)) {
        this.setState(() => ({nameError5: null}));
      } else {
        this.setState(() => ({nameError5: 'Số điện thoại có ít nhất 10 số *'}));
      }
    }
    if (email === '') {
      this.setState(() => ({nameError6: 'Vui lòng nhập email *'}));
    } else {
      if (validateEmail(email)) {
        this.setState(() => ({nameError6: null}));
      } else {
        this.setState(() => ({
          nameError6: 'Vui lòng nhập đúng định dạng Email *',
        }));
      }
    }
    if (address === '') {
      this.setState(() => ({nameError7: 'Vui lòng nhập địa chỉ *'}));
    } else {
      this.setState(() => ({nameError7: null}));
    }

    if (
      fullname != '' &&
      dateOfBirth != '' &&
      validatePassPortNumber(passPort) &&
      validatePhoneNumber(phone) &&
      validateEmail(email) &&
      address != ''
    ) {
      let dateFormat = moment(dateOfBirth, 'DD-MM-YYYY').add(8, 'hours');
      this.showLoading();
      APIChangeProfile(
        UserId,
        fullname,
        dateFormat,
        phone,
        email,
        address,
        passPort,
      )
        .then(res => {
          if (res.status == 200) {
            this.hideLoading();
            this.props.dispatch(
              setObjUser({
                FullName: fullname,
                DOB: dateFormat,
                passport: passPort,
                Phone: phone,
                Email: email,
                Address: address,
              }),
            );
            Alert.alert('Thông báo', 'Đổi thông tin thành công', [
              {
                text: 'OK',
                onPress: () => {
                  this.props.navigation.goBack();
                },
              },
              // { cancelable: false },
            ]);
          }
        })
        .catch(err => {
          this.setState({notification: 'Đổi thông tin thất bại!'});
          this.hideLoading();
        });
    }
  }

  handlePress = index => {
    if (index == 1) {
      setTimeout(() => this.takeCamera(), 500);
    } else if (index == 2) {
      setTimeout(() => this.selectPhotoTapped(), 500);
    }
  };
  showLoading() {
    this.setState({loading: true});
  }

  hideLoading() {
    this.setState({loading: false});
  }
  showDateTimePicker = () => {
    this.setState({isDateTimePickerVisible: true});
  };

  hideDateTimePicker = () => {
    this.setState({isDateTimePickerVisible: false});
  };

  handleDatePicked = date => {
    this.setState({isDateTimePickerVisible: false});
    const d = moment(date).format('DD-MM-YYYY');
    this.setState({dateOfBirth: d});
    this.hideDateTimePicker();
    // this.passPortInput.focus();
  };
  getActionSheetRef = ref => (this.actionSheet = ref);
  takeCamera() {
    const {tokenVT} = this.props;
    const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      cameraType: 'back',
      includeBase64: false,
      storageOptions: {
        skipBackup: true,
      },
    };
    ImagePicker.launchCamera(options, response => {
      if (response.didCancel) {
        console.log('User cancelled photo picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        const formData = new FormData();
        formData.append('file', {
          uri: response.assets[0].uri,
          type: response.assets[0].type,
          name: 'responsefileName',
        });
        this.showLoading();
        PostIDViettelOCR(tokenVT, formData)
          .then(res => {
            if (res.status == 200) {
              const IDInfo = res.data.information[0];
              const dob = IDInfo.birthday.split('/').join('-');
              if (
                IDInfo.document == 'CMCC_front' ||
                IDInfo.document == 'CCCD_front' ||
                IDInfo.document == 'CMND_front' ||
                IDInfo.document == 'CCCD_FRONT_CHIP'
              ) {
                this.setState({
                  fullname: IDInfo.name,
                  passPort: IDInfo.id,
                  address: IDInfo.address,
                  dateOfBirth: dob,
                });
              } else {
                Alert.alert('Không xác thực được CCCD/CMND vui lòng chụp lại');
              }
            } else {
              Alert.alert('Không xác thực được CCCD/CMND vui lòng chụp lại');
            }
            this.hideLoading();
          })
          .catch(err => {
            Alert.alert('Không xác thực được CCCD/CMND vui lòng chụp lại');
            console.log('err OCR ', err);
            this.hideLoading();
          });
      }
    });
  }

  selectPhotoTapped() {
    const {tokenVT} = this.props;
    const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      cameraType: 'back',
      includeBase64: false,
      storageOptions: {
        skipBackup: true,
      },
    };
    ImagePicker.launchImageLibrary(options, response => {
      if (response.didCancel) {
        console.log('User cancelled photo picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        const formData = new FormData();
        formData.append('file', {
          uri: response.assets[0].uri,
          type: response.assets[0].uri,
          name: 'responsefileName',
        });
        this.showLoading();
        PostIDViettelOCR(tokenVT, formData)
          .then(res => {
            // console.log('res OCR', res.data)
            if (res.status == 200) {
              const IDInfo = res.data.information[0];
              const dob = IDInfo.birthday.split('/').join('-');
              if (
                IDInfo.document == 'CMCC_front' ||
                IDInfo.document == 'CCCD_front' ||
                IDInfo.document == 'CMND_front' ||
                IDInfo.document == 'CCCD_FRONT_CHIP'
              ) {
                this.setState({
                  fullname: IDInfo.name,
                  passPort: IDInfo.id,
                  address: IDInfo.address,
                  dateOfBirth: dob,
                });
              }
            }
            this.hideLoading();
          })
          .catch(err => {
            Alert.alert('Không xác thực được CCCD/CMND vui lòng chụp lại');
            console.log('err OCR ', err);
            this.hideLoading();
          });
      }
    });
  }
  showActionSheet() {
    this.actionSheet.show();
  }

  render() {
    const currentDate = setMaxYear(new Date(), -18);
    const {fullname, dateOfBirth, phone, email, address, passPort, oldPhone} =
      this.state;
    const {UserTypeId} = this.props;
    return (
      <KeyboardAvoidingView
        behavior={Platform.OS === 'android' ? '' : 'padding'}
        enabled
        style={{flex: 1, alignItems: 'center'}}>
        <ScrollView style={{flex: 1}}>
          <View
            style={{
              flex: 1,
              alignItems: 'center',
              width: screen.width,
              height: screen.height * 1.2,
            }}>
            <StatusBar backgroundColor={'#ED1B24'} barStyle="light-content" />
            {this.state.loading && (
              <View style={styles.loading}>
                <ActivityIndicator size="large" color="#ED1B24" />
              </View>
            )}
            <TouchableOpacity
              onPress={() => this.showActionSheet()}
              style={[
                styles.input,
                {
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                },
              ]}>
              <Text style={[{color: 'black', fontWeight: 'bold'}]}>
                Chụp ảnh CMND/CCCD
              </Text>
              <Image
                style={{width: 30, height: 30}}
                source={require('../Media/iconCamera.png')}></Image>
            </TouchableOpacity>
            <Hoshi
              value={fullname}
              style={styles.input}
              label={'Họ tên *'}
              borderColor={'#ED1B24'}
              autoCapitalizes={'words'}
              onChangeText={fullname => {
                this.setState({fullname});
              }}
              returnKeyType={'next'}
            />
            {!!this.state.nameError3 && (
              <Text style={styles.textError}>{this.state.nameError3}</Text>
            )}
            <View style={styles.horizontalView}>
              <Hoshi
                value={dateOfBirth}
                style={styles.inputDateTimeShort}
                label={'Ngày sinh *'}
                borderColor={'#ED1B24'}
                // pointerEvents="none"
                onChangeText={dateOfBirth => {
                  this.setState({dateOfBirth});
                }}
              />
              <TouchableOpacity onPress={() => this.showDateTimePicker()}>
                <Image
                  source={require('../Media/datetime.png')}
                  style={styles.iconDateTime}
                />
              </TouchableOpacity>
            </View>
            <DatePicker
              theme="light"
              open={this.state.isDateTimePickerVisible}
              onConfirm={this.handleDatePicked}
              onCancel={this.hideDateTimePicker}
              modal
              date={currentDate}
              mode="date"
              datePickerModeAndroid="spinner"
              locale="vi-VN"
            />
            {!!this.state.nameError4 && (
              <Text style={styles.textError}>{this.state.nameError4}</Text>
            )}
            <Text style={styles.textNote}>
              Nhập định dạng DD-MM-YYYY hoặc chọn ngày
            </Text>

            <Hoshi
              value={passPort}
              style={styles.input}
              label={'Số CMT/CCCD/HC *'}
              borderColor={'#ED1B24'}
              // keyboardType={'numeric'}
              onChangeText={passPort => {
                this.setState({passPort});
              }}
              returnKeyType={'next'}
            />
            {!!this.state.passPortErr && (
              <Text style={styles.textError}>{this.state.passPortErr}</Text>
            )}

            <Hoshi
              value={phone}
              style={styles.input}
              label={'Số điện thoại *'}
              borderColor={'#ED1B24'}
              keyboardType={'numeric'}
              onChangeText={phone => {
                this.setState({phone});
              }}
              returnKeyType={'next'}
              // editable={oldPhone != '' && oldPhone != null ? false : true}
              editable={UserTypeId == 3 ? true : false}
            />
            {!!this.state.nameError5 && (
              <Text style={styles.textError}>{this.state.nameError5}</Text>
            )}

            <Hoshi
              value={email}
              style={styles.input}
              label={'Email *'}
              borderColor={'#ED1B24'}
              keyboardType={'email-address'}
              autoCapitalize={'none'}
              onChangeText={email => {
                this.setState({email});
              }}
              returnKeyType={'next'}
            />
            {!!this.state.nameError6 && (
              <Text style={styles.textError}>{this.state.nameError6}</Text>
            )}

            <Hoshi
              value={address}
              style={styles.input}
              label={'Địa chỉ *'}
              borderColor={'#ED1B24'}
              onChangeText={address => {
                this.setState({address});
              }}
              // returnKeyType={"done"}
              // onSubmitEditing={() => { this.changeProfile() }}
            />
            {!!this.state.nameError7 && (
              <Text style={styles.textError}>{this.state.nameError7}</Text>
            )}
            <Button
              block
              style={[styles.buttonContinues]}
              onPress={() => this.changeProfile()}>
              <Text style={styles.textCustom}>Cập nhật thông tin</Text>
            </Button>
            <Text style={{color: 'red'}}>{this.state.notification}</Text>
          </View>
          <ActionSheet
            ref={this.getActionSheetRef}
            options={options}
            cancelButtonIndex={CANCEL_INDEX}
            onPress={this.handlePress}
          />
        </ScrollView>
      </KeyboardAvoidingView>
    );
  }
}

const mapStateToProps = state => {
  return {
    tokenVT: state.user.objUser.tokenVT,
    UserId: state.user.objUser.UserId,
    FullName: state.user.objUser.FullName,
    DOB: state.user.objUser.DOB,
    Phone: state.user.objUser.Phone,
    Email: state.user.objUser.Email,
    Address: state.user.objUser.Address,
    passport: state.user.objUser.passport,
    UserTypeId: state.user.objUser.UserTypeId,
  };
};
export default connect(mapStateToProps)(ChangeProfile);