import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import { Field, Button } from '@antmjs/vantui';
import md5 from 'md5';

export default (props) => {
  const { onPrev, onSubmit } = props;

  const [loading, setLoading] = React.useState(false);
  const [pwd1, setPwd1] = React.useState();
  const [pwd1Err, setPwd1Err] = React.useState();
  const [pwd2, setPwd2] = React.useState();
  const [pwd2Err, setPwd2Err] = React.useState();
  
  const handlePrev = () => {
    onPrev();
  }

  const handleSubmit = () => {
    if (!pwd1) {
      setPwd1Err('请输入密码');
    } else{
      setPwd1Err();
    }
    if (!pwd2) {
      setPwd2Err('请确认密码');
    } else {
      setPwd2Err();
    }

    if (!pwd1 || !pwd2) {
      return;
    }

    if (pwd1 != pwd2) {
      setPwd2Err('两次密码不一致');
      return;
    } else {
      setPwd2Err();
    }

    setLoading(true)
    onSubmit({ password: md5(pwd1) }).then(() => {
      setLoading(false);

      Taro.navigateBack({
        delta: 1,
        fail: () => {
          Taro.reLaunch({
            url: '/pages/login/index',
          })
        }
      })
    }).catch(() => {
      setLoading(false);
    });
  }
  
  return (
    <View>
      <View className="title">重置密码</View>
      <View className="form-box">
        <Field
          value={pwd1}
          placeholder="请设置新密码"
          errorMessage={pwd1Err}
          onChange={e => setPwd1(e.detail)}
        ></Field>
        <Field
          value={pwd2}
          placeholder="再次确认新密码"
          errorMessage={pwd2Err}
          onChange={e => setPwd2(e.detail)}
        ></Field>
      </View>
      <View className="form-act">
        <View>
          <Button block hairline plain type="primary" size="small" onClick={handlePrev}>上一步</Button>
        </View>
        <View>
          <Button block type="primary" size="small" loading={loading} onClick={handleSubmit}>确定</Button>
        </View>
      </View>
    </View>
  )
}
