import React, {Component} from 'react';
import {InputItem, List} from "antd-mobile";
import './bargain-info.scss'
import {validateTel} from "@/utils";
import {Toast} from 'antd-mobile'
import { http } from "@/utils";
import {Link} from "react-router-dom";


class BargainInfo extends Component {

    state = {
        mobile: '',
        code: '',
        isBargain: true
    }

    handleChange = e => {

        let {name, value} = e.target

        this.setState({
            [name]: value
        })
    }

    sendCode = () => {

        console.log(validateTel(this.state.mobile));

        if (!validateTel(this.state.mobile)) {
            Toast.info('请输入正确的手机号')
            return
        }


        http.post(`${API['base-api']}/sys/bind_send_sms`, {
            phone_num: this.state.mobile
        }).then(res => {
            if (res.data.code == 200) {
                Toast.info('验证码发送成功', 2, null, false)
            } else if (res.data.errno === 410) {
                Toast.info('该手机号已注册，请使用该手机号登录，发起砍价。', 3, null, false)
                this.setState({
                    isBargain: false
                })
            } else {
                Toast.info(res.data.msg)
            }
        })
    }

    handleClick = () => {
        if (!this.state.code) {
            Toast.info('请填写验证码')
            return
        }

        http.post(`${API.home}/m/user/bindMobile`, {
            ...this.state
        }).then(res => {
            if (res.data.code == 200) {
                Toast.info('绑定手机号成功', 2, null, false)
                this.props.iWantBargain()
            } else {
                Toast.info(res.data.msg)
            }
        })

    }


    render() {
        let {mobile, code} = this.state
        return (
            <div className={'bargain-bind-phone'}>
                <div className="title">绑定手机，先砍一刀</div>
                <List className={'list'}>
                    <input type="tel" onChange={this.handleChange} name='mobile' placeholder='手机号' maxLength={11}/>
                    <label htmlFor="code">
                        <input type="tel" id='code' onChange={this.handleChange} name='code' placeholder='验证码'
                               maxLength={6}/>
                        <div className={'send-code'} onClick={this.sendCode}>发送验证码</div>
                    </label>
                </List>
                {
                    this.state.isBargain &&
                    <button onClick={this.handleClick}
                            className={validateTel(mobile) && code ? 'active' : ''}>先砍一刀</button>
                }
                {
                    !this.state.isBargain &&
                    <Link className='button active' to={`/passport/login`}>去登录</Link>
                }
            </div>
        );
    }
}

export default BargainInfo