<template>
    <lj-win-common title="绑定手机">
        <div slot="body">
            <van-cell-group>
                <van-field 
                    v-model="phoneNumber"
                    center
                    type="tel"
                    label="手机号" 
                    placeholder="请输入手机号" 
                    :disabled="isBinding"
                    :rules="[{ validator, message: '手机格式不正确' }]"
                >
                </van-field>
                <van-field
                    v-model="code"
                    center
                    clearable
                    label="短信验证码"
                    placeholder="请输入短信验证码"
                >
                    <template #button>
                        <van-button size="small" type="primary" @click="sendSms" :disabled="smsSendCd > 0">{{ smsSendCd == 0 ? "获取验证码" : smsSendCd + "秒后重试" }}</van-button>
                    </template>
                </van-field>
                <van-field label="唯一码" :value="phoneUUID" disabled center>
                    <template #button>
                        <van-switch size="24" v-model="isOnlyUse" @change="handleChancePhoneIsUseUUID"/>
                    </template>
                </van-field>
                <van-notice-bar left-icon="info-o" text="开启唯一码后，该用户只能在该设备登录" />
            </van-cell-group>
        </div>
        <div slot="footer">
            <mu-button large color="primary" @click="handleBingPhone" style="width: 100%" v-if="!isBinding">
                确认绑定
            </mu-button>
            <mu-button large color="error" @click="handleUnBindingPhone" style="width: 100%" v-else>
                解除绑定
            </mu-button>
        </div>
    </lj-win-common>
</template>

<script>
import LjWinCommon from "components/lj-win-common";
import { Input, Button, Alert, Form, FormItem, Switch } from 'element-ui';

export default {
    components: {
        'el-button': Button,
        'el-input': Input,
        'el-alert': Alert,
        'el-form': Form,
        'el-form-item': FormItem,
        'el-switch': Switch,
        LjWinCommon
    },
    data() {
        return {
            phoneNumber: "",
            phoneUUID: "",
            code: "",
            isBinding: true,
            smsSendCd: 0,
            isOnlyUse: false,
            timer: null,
            pattern: /\d{6}/
        }
    },
    mounted() {
        this.refresh();
    },
    methods: {
        validator(val){
            return /1\d{10}/.test(val)
        },
        clearPhone(){
            this.isBinding = false;
            this.phoneNumber = '';
            this.code = '';
        },
        refresh() {
            let userInfo = $lj.getStorage('userInfo');
            this.isBinding = userInfo.phoneNumber != '';
            this.isOnlyUse = userInfo.phoneUUID != '';
            this.phoneNumber = userInfo.phoneNumber;
            this.phoneUUID = userInfo.phoneUUID;
        },
        handleBingPhone() {
            if(this.code == '') {
                $lj.toast("请输入验证码!")
                return false;
            }

            let self = this;
            this.handleBindingPhone(1,() => {
                self.code = '';
                alert("手机号码绑定成功!");
            });
        },
        handleUnBindingPhone() {
            if(this.code == '') {
                $lj.toast("请输入验证码!")
                return false;
            }
            let self = this;
            this.handleBindingPhone(2,() => {
                self.clearPhone();
                alert("手机号码解绑成功!");
            });
        },
        handleBindingPhone(type,callback) {
            let self = this;
            // 1,3: 绑定 2,4: 解绑
            let requestBody = {
                token: $lj.getStorage("token"),
                phoneNumber: this.phoneNumber,
                bigFlag: "L1APP",
                code: this.code,
                phoneUUID: this.phoneUUID,
                type: type
            };
            $lj.postLJRequest("LJAPPBindingPhoneNumber", requestBody, function (ret) {
                callback && callback();
                self.setUserInfo(ret.userInfo);
                self.refresh();
            });
        },
        setUserInfo(user) {
            let userInfo = $lj.getStorage('userInfo');
            userInfo.phoneNumber = user.phoneNumber;
            userInfo.phoneUUID = user.phoneUUID;
            $lj.setStorage('userInfo',userInfo);
        },
        handleChancePhoneIsUseUUID(value) {
            let text = value ? '开启' : '关闭';
            let self = this;
            $lj.selectDialog("操作提示", "确认是否" + text + "设备唯一码", ["取消", "确认"], function (btnIndex) {
                if (btnIndex === 2) {
                    if(value) {
                        $lj.getAppDeviceId().then(() => {
                            self.phoneUUID = $lj.deviceId;
                            self.handleBindingPhone(3,() => {
                                alert("设备唯一码绑定成功!");
                            });
                        })
                    } else {
                        self.phoneUUID = '';
                        self.handleBindingPhone(4,() => {
                            alert("设备唯一码解绑成功!");
                        });
                    }
                } else {
                    self.isOnlyUse = !value;
                }
            })
        },
        sendSms() {
            if(this.phoneNumber == '') {
                $lj.toast("请输入手机号码!");
                return false;
            }
            let self = this;
            $lj.postLJRequest("SendSMS", {
                token: $lj.getStorage("token"),
                phoneNumber: this.phoneNumber,
                bigFlag: "L1APP"
            }, function (ret) {
                // 表示发送成功
                $lj.toast("发送成功!");
                // alert("验证码:" + ret.code);
                self.getCode();
            })
        },
        getCode(){      
            const TIME_COUNT = 60;
            if (!this.timer) {
                this.smsSendCd = TIME_COUNT;
                this.timer = setInterval(() => {
                    if (this.smsSendCd > 0 && this.smsSendCd <= TIME_COUNT) {
                        this.smsSendCd--;         
                    } else {
                        clearInterval(this.timer);
                        this.timer = null;
                    }
                }, 1000)       
            }
        },
    }
}
</script>