ReactNative 设置手势密码

import React, {Component} from "react";
import {
    Slider,
    ListView,
    Text,
    ScrollView,
    View,
    TouchableOpacity,
    Dimensions,
    StyleSheet,
    Alert,
    Platform,
    Image,
    TextInput,
    AsyncStorage
} from "react-native";
import GesturePassword from "react-native-smart-gesture-password";
import {Navigation} from "react-native-navigation";
import Apis, {LoginForm, LoginRet,UserBase} from "app-js-sdk";
import Commons, {ProgressView, Link, context,HocNavScreen} from "commons";

type Props ={
    isEditGesturePassWord:Number,
    navigator:Object,
    createGesture:Function,
    isLogin:Boolean,
    isSetPassword:Boolean,
    account:String,
    closeModal:Function,
}
const GESTURE_PASSWORD_KEY = "$GesturePassWord";
const GESTURE_PASSWORD_ACCOUNT = "$GestureAccount";
const SETUP_GESTURE_PASSWORD = "$SetupGesturePassWord";
const GESTURE_TOKEN = "$GestureToken";

class GesturePasswordScreen extends Component {
    commons: Commons = new Commons().bind(this);
    state = {
        isWarning: false,
        message: '',
        messageColor: '#A9A9A9',
        password: '',
        thumbnails: [],
        isEditGesturePassWord:1,
        passWordErrorTimes:0,
        _cachedPassword:null,
        mobile:'',
    };
    props:Props;
    constructor(props:Props) {
        super(props);
        this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent);
    }
    componentDidMount() {
        this.getMobile();
        this.setState({
            isEditGesturePassWord:this.props.isEditGesturePassWord,
        });
        AsyncStorage.getItem(GESTURE_PASSWORD_KEY, (error: Error, result: string) => {
            this.setState({
                _cachedPassword:result
            })
        })
    };

    isSuccesLogin = false;
    componentWillUnmount = () => {
        context._onCloseLoginDialog(this.isSuccesLogin);
        if (!this.isSuccesLogin) {
            context.navigatorPopToRoot();
        }
    };

    getMobile =()=>{
        AsyncStorage.getItem(GESTURE_PASSWORD_ACCOUNT, (error: Error, result: string) => {
            this.setState({
                mobile:result
            })
        })
    }

    onNavigatorEvent=(event)=>{
        if(event.id == "didAppear" && !this.props.isLogin && !this.props.isSetPassword){
            this.props.navigator.dismissLightBox();
        }
        if (event.id == 'back') {
            context.navigatorPopToRoot();
            this.props.navigator.dismissModal({
                animationType: 'slide-down'
            });
        }
    }


    render() {
        const {height, width} = Dimensions.get('window');
        return <View style={[styles.wrap]}>
            <GesturePassword
            pointBackgroundColor={'transparent'}
            isWarning={this.state.isWarning}
            color={'#FF4C00'}
            gestureAreaLength={width*0.75}
            gesturePadding={0}
            activeColor={'#FF4C00'}
            warningColor={'red'}
            lineWidth={2}
            showArrow={false}
            warningDuration={1500}
            allowCross={true}
            topComponent={this._renderDescription()}
            bottomComponent={this._renderActions()}
            onFinish={this._onFinish}
            onReset={this._onReset}
        />
    </View>
    }


    _renderThumbnails() {
        let thumbnails = []
        const {height, width} = Dimensions.get('window');
        let thumbSize = width * (13 / 375);
        let margin = width * (5.5 / 375);
        for (let i = 0; i < 9; i++) {
            let active = ~this.state.password.indexOf(i)
            thumbnails.push((
                <View
                    key={'thumb-' + i}
                    style={[
                        {width: thumbSize, height: thumbSize, margin: margin, borderRadius: thumbSize, },
                        active ? {backgroundColor: '#FF4C00'} : {borderWidth: 1, borderColor: '#FF4C00'}
                    ]}
                />
            ))
        }
        return (
            <View
                style={{width: thumbSize*3 + margin*6,flexDirection: 'row', flexWrap: 'wrap',}}>
                {thumbnails}
            </View>
        )
    }

    _renderDescription = () => {
        return (
            <View style={{height: 158, paddingBottom: 10,justifyContent: 'flex-end', alignItems: 'center',}}>
                {(()=>{
                    if(this.state.isEditGesturePassWord==1){
                       return  ([<View key="v1" style={{padding: 10}}><Text>请绘制手势密码</Text></View>,<View key="v2">{this._renderThumbnails()}</View>]);
                    }else if(this.state.isEditGesturePassWord==2){
                        return <Text>绘制手势图形</Text>
                    }else{
                        return <Text>再绘制一次刚才的手势图形</Text>
                    }
                })()
                }
                <Text
                    style={{fontFamily: '.HelveticaNeueInterface-MediumP4', fontSize: 14, marginVertical: 6, color: this.state.messageColor}}>
                    {this.state.message}
                </Text>
            </View>
        )
    };

    _renderActions = () => {
        return (
            <View
                style={{flex:1, justifyContent: 'center', alignItems:'center', flexDirection: 'row', width: Dimensions.get('window').width,}}>
                <View >
                    {(()=>{
                        {/*if(this.props.isLogin==true){*/}
                            {/*return<TouchableOpacity onPress={this.gotoLogin}>*/}
                                {/*<Text style={{color:"#FF5200", textAlign:'center'}}>忘记密码?</Text>*/}
                            {/*</TouchableOpacity>*/}
                            {/*/!*return<TouchableOpacity onPress={this.gotoLoginWithAccount}>*!/*/}
                                {/*/!*<Text style={{color:"#FF5200", textAlign:'center'}}>账户密码登录</Text>*!/*/}
                            {/*/!*</TouchableOpacity>*!/*/}
                        {/*}else */}
                            if(this.state.isEditGesturePassWord==1){
                            return<TouchableOpacity onPress={this.gotoLogin}>
                                <Text style={{color:"#FF5200", textAlign:'center'}}>忘记密码?</Text>
                            </TouchableOpacity>
                        }
                    })()
                    }

                </View>
            </View>
        )
    };

    gotoLogin=()=>{
        Alert.alert('','您需要通过重新登录来设置新的手势密码',[{text:'重新登录',onPress:()=>{
            Navigation.showModal({
                screen: "LoginAndRegister.LoginScreen", // unique ID registered with Navigation.registerScreen
                title: "登录", // title of the screen as appears in the nav bar (optional)
                passProps: {toGestureResetPassword:this.toGestureResetPassword}, // simple serializable object that will pass as props to the modal (optional)
                animationType: 'slide-up' // 'none' / 'slide-up' , appear animation for the modal (optional, default 'slide-up')
            })
            }}]
        )
    }

    toGestureResetPassword =()=>{
        AsyncStorage.removeItem(GESTURE_PASSWORD_KEY);
        AsyncStorage.removeItem(GESTURE_PASSWORD_ACCOUNT);
        AsyncStorage.removeItem(SETUP_GESTURE_PASSWORD);
        this.setState({isEditGesturePassWord:2,message:''});
        this.props.navigator.setTitle({
            title: "创建手势密码" // the new title of the screen as appears in the nav bar
        });
        this.commons.apis.userApi.getUser().then((m:UserBase)=>{
            this.setState({
                mobile:m.mobile
            })
        }).default();
    }

    _onReset = () => {
        let isWarning = false
        //let password = ''
        let message = this.state.message
        let messageColor = '#A9A9A9'
        this.setState({
            isWarning,
            //password,
            message,
            messageColor,
        })
    };

    _onFinish = (password) => {
        if(this.props.isLogin==true && this.state.isEditGesturePassWord==1){
            if(password.length < 4){
                this.setState({
                    isWarning:true,
                    message:'至少链接4个点,请重新输入',
                    messageColor:'red',
                })
            }else if(password === this.state._cachedPassword){
                AsyncStorage.getItem(GESTURE_TOKEN, (error: Error, result: string) => {
                    context.saveToken(result);
                    Apis.setToken(result);
                })
                this.isSuccesLogin = true;
                Navigation.dismissModal({
                    animationType: 'slide-down'
                });

                // this.commons.apis.accountApi.login(LoginForm.form(
                //     null,this.state.mobile
                // )).then((m: LoginRet) => {
                //     this.isSuccesLogin = true;
                //     Navigation.dismissModal({
                //         animationType: 'slide-down'
                //     });
                //     context.saveToken(m.token);
                //     Apis.setToken(m.token);
                //     // this.isSuccesLogin = true;
                //     // if(this.props.toResetPassword){
                //     //     this.props.toResetPassword();
                //     // }
                // }).default();
            }else{
                if(this.state.passWordErrorTimes === 5){
                    Alert.alert('','输错次数过多,请使用账户密码登录并重新设置手势密码',[{text:'账号密码登录',onPress:()=>{
                            Navigation.showModal({
                                screen: "LoginAndRegister.LoginScreen", // unique ID registered with Navigation.registerScreen
                                title: "登录", // title of the screen as appears in the nav bar (optional)
                                passProps: {closeModal:this.toGestureResetPassword}, // simple serializable object that will pass as props to the modal (optional)
                                animationType: 'slide-up' // 'none' / 'slide-up' , appear animation for the modal (optional, default 'slide-up')
                            })
                        }}],{ cancelable: false }
                    )
                }else {
                    let isWarning = true
                    let passWordErrorTimes = this.state.passWordErrorTimes+1
                    let leftPassWordTimes = 6 -passWordErrorTimes
                    let message ='输入错误次数'+passWordErrorTimes+'次,还可以重试'+leftPassWordTimes+'次'
                    let messageColor = 'red'
                    this.setState({
                        isWarning,
                        message,
                        messageColor,
                        passWordErrorTimes,
                        password,
                    })
                }
            }

        }else if(this.props.isLogin==true && this.state.isEditGesturePassWord==2){
            if(password.length < 4){
                this.setState({
                    isWarning:true,
                    message:'至少链接4个点,请重新输入',
                    messageColor:'red',
                })
            }else {
                this.setState({
                    isEditGesturePassWord:this.state.isEditGesturePassWord+1,
                    password,
                    message:'',
                })
            }
        }else if(this.props.isLogin==true && this.state.isEditGesturePassWord==3){
            if(password === this.state.password){
                AsyncStorage.setItem(GESTURE_PASSWORD_KEY,password);
                AsyncStorage.setItem(GESTURE_PASSWORD_ACCOUNT,this.state.mobile);
                Alert.alert('','设置手势密码成功',[{text:'OK',onPress:()=>{
                        if(this.props.createGesture){this.props.createGesture();}
                        Navigation.dismissAllModals({
                            animationType: 'slide-down'
                        });
                    }}],
                { cancelable: false }
                )
            }else{
                this.setState({
                    isWarning:true,
                    messageColor:'red',
                    message:'再绘制的图案不一致,请重新输入'
                })
            }
        }
        else if(this.state.isEditGesturePassWord==1){
            if(password.length < 4){
                this.setState({
                    isWarning:true,
                    message:'至少链接4个点,请重新输入',
                    messageColor:'red',
                })
            }else if(password === this.state._cachedPassword){
                this.setState({
                    isEditGesturePassWord:this.state.isEditGesturePassWord+1,
                    message:'',
                })
            }else{
                if(this.state.passWordErrorTimes === 4){
                    Alert.alert('','输错次数过多,请重新登录并重新设置手势密码',[{text:'重新登录',onPress:()=>{
                        Navigation.showModal({
                            screen: "LoginAndRegister.LoginScreen", // unique ID registered with Navigation.registerScreen
                            title: "登录", // title of the screen as appears in the nav bar (optional)
                            passProps: {toGestureResetPassword:this.toGestureResetPassword}, // simple serializable object that will pass as props to the modal (optional)
                            animationType: 'slide-up' // 'none' / 'slide-up' , appear animation for the modal (optional, default 'slide-up')
                        })
                        }}],
                        { cancelable: false }
                    )
                }else {
                    let isWarning = true
                    let passWordErrorTimes = this.state.passWordErrorTimes+1
                    let leftPassWordTimes = 5 -passWordErrorTimes
                    let message ='输入错误次数'+passWordErrorTimes+'次,还可以重试'+leftPassWordTimes+'次'
                    let messageColor = 'red'
                    this.setState({
                        isWarning,
                        message,
                        messageColor,
                        passWordErrorTimes,
                        password,
                    })
                }
            }
        }else if(this.state.isEditGesturePassWord==2){
            if(password.length < 4){
                this.setState({
                    isWarning:true,
                    message:'至少链接4个点,请重新输入',
                    messageColor:'red',
                })
            }else {
                this.setState({
                    isEditGesturePassWord:this.state.isEditGesturePassWord+1,
                    password,
                    message:'',
                })
            }
        }else{
            if(password === this.state.password){
                AsyncStorage.setItem(GESTURE_PASSWORD_KEY,password);
                AsyncStorage.setItem(GESTURE_PASSWORD_ACCOUNT,this.props.account);
                Alert.alert('','设置手势密码成功',[{text:'OK',onPress:()=>{
                    if(this.props.closeModal){this.props.closeModal();Navigation.dismissAllModals();}
                    if(this.props.createGesture){
                        this.props.createGesture();this.props.navigator.pop();
                    }else{
                        this.props.navigator.pop();
                    }
                    }}]
                    ,{ cancelable: false }
                )
                // this.setState({
                //     _cachedPassword:password,
                // })
                //floating layer 3s
                //jump
            }else{
                this.setState({
                    isWarning:true,
                    messageColor:'red',
                    message:'再绘制的图案不一致,请重新输入'
                })
            }
        }
    };
}
export default HocNavScreen(GesturePasswordScreen);

const styles = StyleSheet.create({
    wrap: {
        backgroundColor: '#fff',
        flex: 1,
    },
    parkbar: {
        height: 20,
        backgroundColor: '#000',
    },
    nav: {
        flexDirection: 'row',
        paddingLeft: 15,
        paddingRight: 15,
        alignItems: 'center',
        borderBottomWidth: 0.5,
        borderStyle: 'solid',
        borderBottomColor: '#dedede',
    },
    arrowBar: {
        flex: 2,
    },
    tab: {
        height: 44,
        justifyContent: 'center',
        alignItems: 'center',
        flex: 8,
        backgroundColor: 'transparent',
    },
    tabText: {
        color: '#333',
        fontSize: 17,
    },
    share: {
        flex: 2,
        height: 44,
        justifyContent: 'center',
        alignItems: 'flex-end',
    },
    stext: {
        color: '#fff',
        fontSize: 17,
    },
    //
    h100: {
        height: 50,
    },
    titlebar: {
        height: 49,
        justifyContent: 'center',
        alignItems: 'center',
    },
    title: {
        color: '#333',
        fontSize: 18,
    },
    //
    gesture: {
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    circle: {
        width: 60,
        height: 60,
        borderBottomLeftRadius: 60,
        borderBottomRightRadius: 60,
        borderTopLeftRadius: 60,
        borderTopRightRadius: 60,
        borderWidth: 1,
        borderStyle: 'solid',
        borderColor: '#FF7A21',
        overflow: 'hidden',
        marginLeft: 27,
        marginRight: 27,
        marginBottom: 27,
        marginTop: 27,
    },
    //
    warning: {
        height: 50,
        alignItems: 'center',
    },
    warn: {
        color: '#ff0d0d',
        fontSize: 15,
        marginTop: 25,
    },
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值