<template>
    <div class="signUpAccount">
        <m-header />
        <m-step />

        <div class="title">基本信息</div>
        <!-- <van-form ref="form" :show-error="false" validate-first @submit="onSubmit" @failed="onFailed"> -->
        <van-field v-model="form.phone" required name="phone" label="手机号" placeholder="请输入手机号" />
        <van-field v-model="form.code" required clearable name="code" label="验证码" placeholder="请输入验证码" >
            <template #button>
                <span class="codeText" v-show="countDownStatus" @click="onGetCode">获取验证码</span>
                <span class="code-text" v-show="!countDownStatus">
                    <van-count-down
                        ref="countdown"
                        :auto-start="false"
                        :time="countDownTime"
                        @finish="onCountDownFinished"
                        format="ss秒" />
                </span>
            </template>
        </van-field>


        <m-button class="stepBtn" text="下一步" @click="onSubmit" native-type="submit" />
        <!-- </van-form> -->
    </div>
</template>
<script>
import MHeader from '@/components/MHeader'
import MStep from '@/components/MStep'
import MButton from '@/components/MButton'
// import { browser } from '@/common/common'
import { patternPhone } from '@/utils/validateRules'
import setLoading from '@/utils/loading'
import { sendSms, smsLogin, queryUserByPhone } from './SignUpApi'
export default {
    name: 'signUpAccount',
	components: { MHeader, MStep, MButton },
    data () {
        localStorage.removeItem("Authorization")
        const query = this.$route.query
        return {
            examId: query.examId,
            organId: query.organId,
            patternPhone: patternPhone,
            form: {
                phone: null,
                code: null,
            },
            countDownStatus: true, // 到计时状态
            countDownTime: 1000 * 120 // 倒计时时间
        }
    },
    mounted() {
        // 插入token
        // let params = this.$route.query
        // if(params.Authorization) {
        //     localStorage.setItem('Authorization', decodeURI(params.Authorization))
        //     localStorage.setItem('userInfo', decodeURI(params.Authorization))
        // }
        // window.onbeforeunload = onbeforeunload_handler;
        // window.onunload = onunload_handler;
        // function onbeforeunload_handler(){
        //     var warning="确认退出?";
        //     return warning;
        // }
        // function onunload_handler(){
        //     var warning="谢谢光临";
        //     alert(warning);
        // }
    },
    methods: {
        async onGetCode() { // 获取验证码
            setLoading(true)
            if(!this.checkPhone(this.form.phone)) {
                return
            }
            try {
                const resultSend = await sendSms({ mobile: this.form.phone })
                const result = resultSend.data
                if(result.code === 200) {
                    this.countDownStatus = false
                    this.$refs.countdown.start() // 倒计时开始
                    setLoading(false)
                } else {
                    this.$toast(result.msg)
                }
            } catch (error) {
                //
                setLoading(false)
            }
        },
        onCountDownFinished() { // 倒计时结束
            this.countDownStatus = true
            this.$refs.countdown.reset()
        },
        async onCheckPhone() { // 检查手机号是否存在
            setLoading(true)
            try {
                let form = this.form
                let params = {
                    mobile: form.phone
                }
                const code = await queryUserByPhone(params)
                const result = code.data
                if(result.code === 200) {
                    // 1 为已注册，0为未注册
                    this.onLogin(result.data)
                } else {
                    this.$toast(result.msg)
                }
            } catch(error) {
                setLoading(false)
            }
        },
        async onLogin(status) { // 登录
            const form = this.form
            let params = {
                clientId: 'student',
                clientSecret: 'student',
                phone: form.phone,
                smsCode: form.code,
                organId: this.organId
            }
            if(status === 0) { // 不为空是为注册
                params.registerFlag = 'true'
            }
            const login = await smsLogin(params)
            const result = login.data
            if(result.code === 200) {
                let auth = result.data.authentication
                localStorage.setItem('Authorization', auth.token_type + ' ' + auth.access_token)
                this.$router.push({
                    path: "/signUpBaseInfo",
                    query: {
                        organId: this.organId
                    }
                })
            } else {
                this.$toast(result.msg)
            }
        },
        onSubmit() {
            const form = this.form
            if(!this.checkPhone(form.phone)) { // 手机号验证
                return
            }
            if(!form.code) {
                this.$toast('请输入验证码')
                return
            }
            // 验证码
            this.onCheckPhone()
        },
        checkPhone(phoneNumber) {
            let result = true
            if(!(this.patternPhone.test(phoneNumber))){
                this.$toast('手机号输入有误')
                result = false
            }
            return result
        }
    },
    destroyed() {
        this.$toast.clear()
    }
}
</script>
<style lang="less" scoped>
.signUpAccount {
    height: 100vh;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: var(--main-bg-color);
    .title {
        font-size: .16rem;
        color: var(--font-second-color);
        padding: .12rem .16rem;
    }
    /deep/.van-cell {
        padding: .13rem .16rem;
    }
    /deep/.van-field__label {
        font-size: .17rem;
        color: var(--font-main-color);
        width: 1.15rem;
    }
    /deep/.van-field__body {
        font-size: .16rem
    }

    /deep/.van-count-down {
        font-size: .16rem;
        // color: ;
    }

    .codeText {
        font-size: .16rem;
        color: var(--main-color);
    }
}

</style>