import React, { Component } from 'react'
import './set-password.scss'
import { withFormik, Form, Field } from "formik"
import PasswordInput from '../common/passwordInput'
import Button from '../common/Button'
import classnames from 'classnames'
import { compose } from 'redux'
import { HeaderBar } from "@/common"
import { http } from "@/utils"
import { Toast } from "antd-mobile"
import { encrypt } from "@/components/passport/encryption"
import { Link } from "react-router-dom"
import { isEmpty } from "lodash"
import { connect } from "react-redux"
import { setCurrentUser } from '@/store/userAction'

class SetPassword extends Component {
  render() {
    let {values, errors, location} = this.props
    let {from} = location.state || {from: {pathname: '/'}}
    return (
      <>
        <HeaderBar arrow={true} title={'设置密码'}/>
        <div className={'set-password'}>
          <p className='title'>密码需要包含6-16位字母及数字</p>
          <Form>
            <Field
              name='password'
              render={({field}) => {
                return (
                  <PasswordInput
                    autoComplete={'on'}
                    placeholder={'设置密码'}
                    onChange={this.handleChange}
                    {...field}
                  />
                )
              }}
            />
            <Button className={'btn-active'}
                    active={values.password && values.agreement && isEmpty(errors)}>完成</Button>
            <label htmlFor="agreement" className='user-agreement'>
              <Field type='checkbox'
                     name='agreement'
                     id='agreement'
                     className={classnames([
                       this.props.values.agreement ? 'iconfont iconiconfront-3' : 'disagree'
                     ])}
              />
              同意<span>《七月在线用户使用协议》</span>
            </label>
          </Form>
          <div className="skip"
               style={{display: from && from.pathname.includes('forgot-password') ? 'none' : 'block'}}>
            <Link replace to='/passport/account-login'>跳过</Link>
          </div>
        </div>
      </>
    )
  }
}

const formikConfig = {
  mapPropsToValues() {
    return {
      password: '',
      agreement: true
    }
  },
  handleSubmit: (values, {props}) => {

    let from = props.location.state && props.location.state.from || {pathname: '/'}
    if (from.pathname.includes('forgot-password')) {
      forgotPasswordReset(values, props)
    } else {
      bindMobileSetPassword(values, props)
    }

  },
  validateOnChange: false,
  validate: values => {
    let errors = {}
    const re = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/
    if (!re.test(values.password)) {
      errors.password = '密码需要包含6-16位字母及数字'
      Toast.info(errors.password, 2, null, false)
    }
    if (!values.agreement) {
      errors.agreement = '您须同意《七月在线用户使用协议》'
      Toast.info(errors.agreement, 2, null, false)
    }
    return errors
  }
}


function forgotPasswordReset(values, props) {
  let key = sessionStorage.getItem('r_type') === 'email' ? 'email' : 'tel'

  let requestKey = key === 'email' ? 'email' : 'phone'
  http.post(`${API['passport-api']}/account/up_pass_by_${requestKey}`, {
    [requestKey]: sessionStorage.getItem(key),
    password: encrypt(values.password)
  })
    .then(res => {
      if (res.data.errno == 200) {
        Toast.info('密码设置成功')
        setTimeout(function () {
          props.history.replace('/passport/account-login')
        }, 1000)
      } else {
        Toast.info(res.data.msg, 2, null, false)
      }
    })
}

function bindMobileSetPassword(values, props) {

  http.post(`${API['passport-api']}/bind_mobile/set_pwd_new`, {
    uid: props.user.data.uid,
    password: encrypt(values.password)
  })
    .then(res => {
      if (res.data.errno == 200) {
        const {location, history} = props
        Toast.info('密码设置成功')
        let from = location.state && location.state.from || {pathname: '/'}
        let local_redirect_url = JSON.parse(window.localStorage.getItem('binding_redirect'))
        setTimeout(function () {
          if (local_redirect_url) {
            const {pathname, search, hash} = local_redirect_url
            history.replace(pathname + search + hash)
          } else {
            history.replace(from.pathname)
          }
        }, 1000)
      } else {
        Toast.info(res.data.msg, 2, null, false)
      }
    })
}

export default compose(
  connect(
    state => ({user: state.user}),
    {setCurrentUser}
  ),
  withFormik(formikConfig)
)(SetPassword)
