index.js 9.85 KB
Newer Older
xuzhenghua committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 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 184 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 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
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import classnames from 'classnames';
import { studentLogin } from '@/store/userAction';
import { http } from '@/utils';
import { Formik, Form, Field } from 'formik';
import { Toast } from "antd-mobile";
import { HeaderBar } from "@/common";
import Captcha from '@/common/Captcha'
import Header from '../common/Header';
import Input from '../common/inputWithCountryCodes';
import VeriCodeInput from '../common/veriCodeInput';

import './index.scss';

@connect(
  state => ({
    country: state.country,
  }),
  {
    studentLogin
  }
)
class StudentRoot extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      validate: null,
      captchaInstance: null,
      disabled: false,
      isSchool: false,
      isCollege: false,
      list: [],
      schoolList: [],
      schoolName: '',
    };
  }

  componentDidMount() {
    this.fetchSchoolInfo();
  }

  fetchSchoolInfo = () => {
    http.get(`${API['home']}/sys/schools `).then(res => {
      const { code, data } = res.data;
      if(code === 200) {
        const schoolList = [];
        data.forEach(item => {
          schoolList.push(item.school);
        });
        this.setState({
          list: data,
          schoolList
        });
      }
    });
  }

  handleToLogin = ({ tel, password, code, school, college, uid, name}) => {
    const { validate, captchaInstance } = this.state;
    const { country, studentLogin, location } = this.props;
    const from = location.state && location.state.from;
    studentLogin({
      validate,
      tel,
      password,
      code,
      num: `00${country.num}`,
      school,
      college,
      uid,
      name,
      redirect: from && window.location.origin + from.pathname + from.search + from.hash,
    }).then(res => {
      if (res.hasError) {
        captchaInstance.refresh();
        Toast.info(res.msg, 2, null, false);
      }
    });
  }

  getCaptchaInstance = instance => {
    this.setState({
      captchaInstance: instance
    });
  }
  
  onVerify = (err, data) => {
    if (!err) {
      this.setState({
        validate: data.validate
      });
    }
  }

  selectSwitch = (key, value) => {
    let param = {};
    param[key] = value;
    this.setState(param);
  }

  changeToCollege = (school = '') => {
    this.setState({
      schoolName: school
    });
  }

  fetchCollegeInfo = () => {
    const { list, schoolName } = this.state;
    const data = list.filter(item => item['school'] === schoolName);
    if(data.length > 0) {
      return data[0]['colleges']
    }
    return [];
  }

  render() {
    const { country } = this.props;
    const { validate, captchaInstance, isSchool, isCollege, schoolList, schoolName } = this.state;
    const collegeList = this.fetchCollegeInfo();
    return (
      <>
        <HeaderBar title={'助学计划'} arrow={true}/>
        <Header/>
        <Formik
          initialValues={{ 
            tel: '',
            password: '',
            code: '',
            school: '',
            college: '',
            uid: '',
            name: '',
          }}
          validate={({ tel, password, code, school, college, uid, name }) => {
            let errors = {}
            if (!/\d/.test(tel)) {
              errors.tip = '请填写正确格式的手机号~';
              return errors;
            }
            if(password.length < 6 || !/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/.test(password)) {
              errors.tip = '密码需要包含6-16位字母和数字~';
              return errors;
            }
            if (!/[0-9]{6}/.test(code)) {
              errors.tip = '请填写验证码(先滑块验证呦)~';
              return errors;
            }
            if (!school) {
              errors.tip = '请选择学校~';
              return errors;
            }
            if (!college) {
              errors.tip = '请选择学院~';
              return errors;
            }
            if (!uid) {
              errors.tip = '请填写学号~';
              return errors;
            }
            if (!name) {
              errors.tip = '请填写姓名~';
              return errors;
            }
            return {};
          }}
          onSubmit={(values, errors) => {
            this.handleToLogin(values);
          }}
        >
          {props => {
            const isSubmit =  Object.values(props.values).join('') !== '' && props.errors.tip === undefined;
            return (
              <Form className="student-form">
                <Field
                  name='tel'
                  render={({field}) => (
                    <Input
                      {...field}
                      type={'tel'}
                      placeholder={'手机号快捷登录(免注册)'}
                      wrapperClass={'tel-input'}
                      country={country}
                    />
                  )}
                />
                <div className="student-form__item">
                  <Field 
                    className="student-form__input" 
                    type="password" 
                    name="password" 
                    minLength="6"
                    maxLength="16"
                    placeholder="密码需要包含6-16位字母和数字"
                  />
                </div>
                <Captcha 
                  mrBtm={'15px'} 
                  getInstance={this.getCaptchaInstance}
                  onVerify={this.onVerify}
                />
                {
                  validate &&
                  <Field
                    type='number'
                    name='code'
                    render={({field}) => (
                      <VeriCodeInput
                        {...field}
                        className={'student-form__code'}
                        icon={<i className={'iconfont iconduanxin'} style={{fontSize: '20px', left: '12px'}}/>}
                        tel={props.values.tel}
                        challenge={validate}
                        errors={props.errors}
                        placeholder={'请输入验证码'}
                        instance={captchaInstance}
                        country={country}
                      />
                    )}
                  />
                }
                <div className="student-form__item">
                  <label className="student-form__label">学校</label>
                  <StudentSelect 
                    name="school"
                    value={props.values.school}
                    schoolName={schoolName}
                    data={{
                      key: 'isSchool',
                      val: isSchool
                    }}
                    options={schoolList}
                    placeholder="请选择"
                    onChange={props.setFieldValue}
                    clearToCollege={() => {
                      props.setFieldValue('college', '')
                    }}
                    selectSwitch={this.selectSwitch}
                    changeToCollege={this.changeToCollege} 
                  />
                </div>
                <div className="student-form__item">
                  <label className="student-form__label">学院</label>
                  <StudentSelect 
                    name="college"
                    value={props.values.college}
                    data={{
                      key: 'isCollege',
                      val: isCollege
                    }}
                    isClick={props.values.school !== ''}
                    options={collegeList}
                    placeholder="请先选择学校"
                    onChange={props.setFieldValue}
                    selectSwitch={this.selectSwitch} 
                  />
                </div>
                <div className="student-form__item">
                  <label className="student-form__label">学号</label>
                  <Field className="student-form__input" type="text" name="uid" placeholder="不区分大小写"/>
                </div>
                <div className="student-form__item">
                  <label className="student-form__label">姓名</label>
                  <Field className="student-form__input" type="text" name="name" placeholder="请准确填写"/>
                </div>
                <div className="student-form__footer">
                  {
                    props.errors.tip &&
                    <p className="student-form__tip">*{props.errors.tip}</p>
                  }
                  <button className="student-form__submit" type="submit" disabled={!isSubmit}>注册</button>
                </div>
              </Form>
            )
          }}
        </Formik>
      </>
    )
  }
}

const StudentSelect = (props) => {
  const { 
    options = [], 
    data: { key = '' , val = false },
    schoolName,
    isClick = true,
    name,
    value,
    onChange,
    placeholder,
    selectSwitch,
    clearToCollege,
    changeToCollege
  } = props;
  return (
    <div className="student-select">
      <input 
        className={classnames({'active': val})}
        value={value}
        type="text" 
        placeholder={placeholder} 
        readOnly
        onClick={() => {
          isClick && selectSwitch(key, true);
        }} 
      />
      {
        val &&
        <ul className="student-select__list">
          {
            options.length > 0 && options.map((item, index) => (
              <li 
                className="student-select__option" 
                key={index}
                onClick={() => {
                  selectSwitch(key, false);
                  onChange(name, item);
                  if(schoolName !== item && typeof clearToCollege === 'function') {
                    clearToCollege();
                  }
                  typeof changeToCollege === 'function' && changeToCollege(item);
                }}
              >{item}</li>
            ))
          }
        </ul>
      }
    </div>
  )
}

export default StudentRoot;