import Taro, { Component } from '@tarojs/taro'
import { isChineseMobilePhoneNumber } from '@utils/tools'
import { applyCard } from '@services/card'
import { connect } from '@tarojs/redux'
import { ROLE_CODE } from '@constants/user'
import './index.scss'

@connect(state => state.user)
export default class Cards extends Component {
  config = {
    navigationBarTitleText: '置业顾问绑定'
  }
  state = {
    phone: '',
    pass: '1234'
  }
  componentDidMount() {
    const { userInfo: { person: { personType, personId } } } = this.props

    if (personType && personType === ROLE_CODE.CONSULTANT) {
      // this.toCardPage(personId)
    }
  }
  toCardPage(id) {
    this.props.dispatchUpdateUserInfoNew(id)
    Taro.navigateTo({ url: `/pages/card/index?id=${id}` })
  }
  doSubmit(payload) {
    applyCard(payload).then(res => {
      this.toCardPage(res)
    })
  }
  validate({ phone, pass }) {
    if (!phone) {
      Taro.showToast({
        title: '电话不能为空',
        image: require('@assets/icons/warn.png')
      })
      return false
    }

    if (!isChineseMobilePhoneNumber(phone)) {
      Taro.showToast({
        title: '电话格式不正确',
        image: require('@assets/icons/warn.png')
      })
      return false
    }

    if (!pass) {
      Taro.showToast({
        title: '密码不能为空',
        image: require('@assets/icons/warn.png')
      })
      return false
    }

    return true
  }
  submitHandler(e) {
    let payload = e.detail.value

    if (!this.validate(payload)) return

    this.doSubmit(payload)
  }
  bindphoneInput(e) {
    this.setState({
      phone: e.detail.value
    })
  }
  bindPassInput(e) {
    this.setState({
      pass: e.detail.value
    })
  }
  render() {
    return (
      <View className="login">
        <Form className="form" onSubmit={this.submitHandler.bind(this)}>
          <View className="form__row">
            <Input className="form__row-input" name="phone" type="number" value={phone} onInput={this.bindphoneInput.bind(this)} placeholder="请输入手机号码" />
          </View>
          <View className="form__row">
            <Input className="form__row-input" name="pass" value={pass} password onInput={this.bindPassInput.bind(this)} placeholder="请输入密码" />
          </View>
          <View className="form__btn">
            <Button type="primary" form-type="submit">登录</Button>
          </View>
        </Form>
      </View>
    )
  }
}
