<template>
    <div :class="bem()">
        <div :class="bem('title')">绑定手机号</div>
        <div :class="bem('skip')" @click="skip">跳过</div>
        <div :class="bem('item')">
            <PhoneNumber
                v-model="vm.form.phone"
                :countries="vm.countries"
                :loading="checkingPhone"
                @blur="checkIsBinded"
            />
        </div>
        <div :class="bem('item')">
            <Input v-model="vm.form.verifyCode" maxlength="4" autocomplete="off" placeholder="输入短信中的验证码"/>
            <Button
                rect
                nativeType="button"
                :class="bem('sms-btn')"
                @click="sendVerifyCode"
                :disabled="!!codePendingRemain"
            >
                {{codePendingRemain ? `${codePendingRemain}秒后获取` : '获取验证码'}}
            </Button>
        </div>

        <div :class="bem('item')" v-show="needRegister">
            <Input
                id="password"
                type="password"
                label="密码"
                @enter="onBindPhone"
                v-model="vm.form.password"
                name="new-password"
                autocomplete="off"
                placeholder="输入6-30位新密码"
                maxlength="30"/>
        </div>

        <Button
            type="primary"
            size="large"
            :class="bem('submit')"
            @click="onBindPhone"
            nativeType="submit"
            :disabled="loading">{{ needRegister ? '注册' : '绑定手机号' }}</Button>
    </div>
</template>
<script>
import Button from '../Button';
import Tips from '../Tips';
import PhoneNumber from './PhoneNumber';
import Input from '../Input';
import { componentMixin, createComponentName } from '../_utils/component';

export default {
    name: createComponentName('auth-bindphone'),
    components: { Button, PhoneNumber, Input },
    mixins: [componentMixin],
    inject: ['vm'],
    data() {
        return {
            phoneNumberIsUsed: null,
            needRegister: false,
            codePendingRemain: null,
            phoneCheckStatus: 0,
            checkingPhone: false,
            loading: false,
        };
    },
    mounted() {
        this.checkIsBinded();
    },
    methods: {

        // TODO: 向商目前只支持校验注册状态，无法区别QQ， Wechat 所以暂时关闭已注册的情况的错误处理
        async checkIsBinded() {
            if (!this.vm.form.phone.number) return;

            this.checkingPhone = true;
            try {
                const { result } = await this.vm.requestUms('checkPhoneNumberStatus', this.vm.form);
                this.phoneCheckStatus = result;
                if (result === 1) {
                    Tips('手机号码未注册，填写密码注册');
                    this.phoneNumberIsUsed = false;
                    this.needRegister = true;
                    return;
                }
                else if (result === 3) {
                    this.phoneNumberIsUsed = true;
                }
                else if (result === 2) {
                    this.phoneNumberIsUsed = false;
                }
                else {
                    throw new Error('未知错误');
                }
                this.needRegister = false;
            }
            catch (error) {
                Tips(error);
            }
            finally {
                this.checkingPhone = false;
            }
        },
        beforeDestroy() {
            clearTimeout(this.codePendingTimer);
        },
        async sendVerifyCode() {
            try {
                if (this.phoneCheckStatus === 0) {
                    await this.checkIsBinded();
                }

                await this.vm.requestUms('sendVerifyCode', { ...this.vm.form, type: this.needRegister ? 'register' : 'login' });
                this.startCheckCodePending();
            }
            catch (error) {
                Tips(error);
            }
        },
        startCheckCodePending() {
            const check = () => {
                this.codePendingRemain -= 1;

                if (this.codePendingRemain <= 0) {
                    this.codePendingRemain = null;

                    return;
                }

                this.codePendingTimer = setTimeout(check, 1000);
            };

            clearTimeout(this.codePendingTimer);

            this.codePendingTimer = setTimeout(check, 1000);
            this.codePendingRemain = 60;
        },
        async skip() {
            try {
                let res;
                if (this.vm.bindphoneType === 'qq') {
                    res = await this.vm.requestUms('skipBindQQ');
                }
                else if (this.vm.bindphoneType === 'wechat') {
                    res = await this.vm.requestUms('skipBindWechat');
                }
                else {
                    throw new Error('尚未通过第三方登录');
                }
                this.vm.$emit('success', {
                    action: 'register',
                    type: this.vm.bindphoneType
                });

                this.vm.onLogin(res.authorization_code, this.vm.bindphoneType);
                this.loading = false;
            }
            catch (error) {
                Tips(error);
                this.loading = false;
                this.vm.$emit('error', {
                    action: 'bindphone',
                    type: this.vm.bindphoneType,
                    error: error
                });
            }
        },
        async onBindPhone() {
            if (this.loading) return;

            this.loading = true;

            try {
                if (this.phoneCheckStatus === 0) {
                    throw new Error('请检查手机号或等待手机号检查完成');
                }

                let res;
                if (this.needRegister) {
                    if (this.vm.bindphoneType === 'qq') {
                        res = await this.vm.requestUms('registerByQQ', this.vm.form);
                    }
                    else if (this.vm.bindphoneType === 'wechat') {
                        res = await this.vm.requestUms('registerByWechat', this.vm.form);
                    }
                    else {
                        throw new Error('尚未通过第三方登录');
                    }
                    this.vm.$emit('success', {
                        action: 'register',
                        type: this.vm.bindphoneType
                    });
                }
                else {
                    if (this.vm.bindphoneType === 'qq') {
                        res = await this.vm.requestUms('bindQQ', { ...this.vm.form });
                    }
                    else if (this.vm.bindphoneType === 'wechat') {
                        res = await this.vm.requestUms('bindWechat', { ...this.vm.form });
                    }
                    else {
                        throw new Error('尚未通过第三方登录');
                    }
                    this.vm.$emit('success', {
                        action: 'bindphone',
                        type: this.vm.bindphoneType
                    });
                }

                this.vm.onLogin(res.authorization_code, this.vm.bindphoneType);
                this.loading = false;
            }
            catch (error) {
                Tips(error);
                this.loading = false;
                this.vm.$emit('error', {
                    action: 'bindphone',
                    type: this.vm.bindphoneType,
                    error: error
                });
            }
        },
    }
};
</script>

<style lang="less">
@import '../_styles/base.less';

@auth-bindphone: ~'@{prefix}-auth-bindphone';

.@{auth-bindphone} {
    line-height: 1.2;

    & &__title {
        color: #000;
        font-size: 24px;
        font-weight: 500;
        margin-bottom: 24px;
    }

    & &__item {
        display: flex;
    }

    & &__item + &__item {
        margin-top: @margin-sm;
    }

    & &__sms-btn {
        width: 100px;
        height: 45px;
        background: #ececec;
        color: #424242;
        flex: 0 0 auto;
        font-weight: 400;
        border: none;
        padding: 0;
        font-size: 14px;
        margin-left: 15px;

        &[disabled] {
            background: #FAFAFA;
            border: 1px solid #CFD8DC;
        }
    }

    & &__sms-btn:hover {
        color: #111;
        &:not([disabled]):hover {
            background: #ccc;
        }
    }

    &__skip {
        font-size: 13px;
        color: #000000;
        position: absolute;
        cursor: pointer;
        right: 20px;
        top: 16px;
    }

    &__submit {
        margin-top: 24px;
        width: 100%;
        height: 45px;
    }

    & &__links {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 24px;
        color: #A9A9A9;
    }
}
</style>
