<template>
    <div class="app-container">
        <van-nav-bar title="绑定设备" left-text="返回" left-arrow @click-left="$router.go(-1)" />

        <div style="padding-top: 100px;"></div>

        <van-form @submit="onSubmit">
            <van-field
                v-model="device_name"
                name="device_name"
                label="设备名称"
                placeholder="请输入设备名称"
                clearable
            />
            <van-field
                v-model="imei"
                name="imei"
                label="设备编号"
                placeholder="请输入设备编号"
                clearable
                required
                :rules="rules.imei"
            >
                <template #right-icon>
                    <van-icon name="scan" color="#03a9f4" size="30" @click="scanCode" />
                </template>
            </van-field>

            <template v-if="userType == 'group' && deviceType == 'badge'">
                <van-field
                    v-model="username"
                    name="username"
                    label="用户姓名"
                    placeholder="请输入用户姓名"
                    clearable
                    required
                />

                <van-field
                    v-model="user_no"
                    name="user_no"
                    label="用户编号"
                    placeholder="请输入用户编号"
                    clearable
                    required
                />
            </template>

            <div style="margin: 36px;">
                <van-button round block type="info" size="small" native-type="submit">绑定</van-button>
            </div>

        </van-form>
    </div>
</template>

<script>
import Vue from 'vue';
import wx from 'weixin-js-sdk'
import { Form,Field,Icon,NavBar,Dialog,Button } from 'vant';

Vue.use(Form);
Vue.use(Field);
Vue.use(Icon);
Vue.use(NavBar);
Vue.use(Dialog);
Vue.use(Button);

export default {
    data() {
        return {
            userid: '',
            openid: '',
            device_name: '',
            imei: '',
            username: '',
            user_no: '',
            userType: '',
            deviceType: '',
            rules: {
                imei: [
                    { required: true, message: '请输入设备号' },
                ]
            }
        }
    },
    created() {
        this.userType = localStorage.getItem('userType');
        this.deviceType = localStorage.getItem('deviceType');
        this.userid = localStorage.getItem('userid');
        this.openid = localStorage.getItem('openid');
    },
    methods: {
        /**
         * 提交
         */
        onSubmit(values) {
            let postData = {
                device_name: values.device_name,
                imei: values.imei,
                userType: this.userType,
                deviceType: this.deviceType,
            }

            if (values.username) {
                postData.username = values.username;
            }
            if (values.user_no) {
                postData.user_no = values.user_no;
            }
            // console.log('onsubmit', values);
            this.$http.post('userBindDevice&userid=' + this.userid + '&openid=' + this.openid, JSON.stringify(postData))
                .then(resp => {
                    if (!resp.data.success) {
                        this.$notify(resp.data.message || '绑定失败');
                        return;
                    }
                    this.$notify({
                        type: 'success',
                        message: resp.data.message || '绑定成功',
                    })
                    // 刷新列表
                    this.$router.replace('devices');
                })
        },
        /**
         * 扫码
         */
        scanCode() {
            let that = this;
            let url = encodeURIComponent(location.href.split('#')[0]);
            // ios 设备只认从公众号菜单首次进入页面的URL
            if (localStorage.getItem('userAgent') == 'ios') {
                let mainUrl = localStorage.getItem('mainUrl');
                url = encodeURIComponent(mainUrl);
            }

            this.$http.get("/getSignaturEtc", { params: { url: url } })
            .then(res => {
                if(!res.data.success){
                    this.$notify( res.data.message);
                    return;
                }
          
                let data = res.data.data;
                    // console.log('resp data',data)
                wx.config({
                    // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    debug: false,
                    // 必填，公众号的唯一标识
                    appId: data.appId,
                    // 必填，生成签名的时间戳
                    timestamp: data.timeStamp,
                    // 必填，生成签名的随机串
                    nonceStr: data.nonceStr,
                    // 必填，签名
                    signature: data.signature,
                    // 必填，需要使用的JS接口列表，所有JS接口列表
                    jsApiList: ['scanQRCode']
                });

                wx.error(function (res) {
                    console.log("出错了：" + res.errMsg);//这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
                });

            })
            .catch(res => {
                console.log(res);
            });


            // 成功时
            wx.ready(function () {

                wx.scanQRCode({
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success: function(res) {
                        var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                        console.log("扫描结果："+result);
                        // window.location.href = result;//因为我这边是扫描后有个链接，然后跳转到该页面

                        that.imei = result;
                    },
                    fail: function(e){
                        console.log('scan fail',e)
                    }
                });

            }); 
        }
    }
}
</script>

<style lang="scss" scoped>

</style>