<template>
    <div class="app-container">
        <van-nav-bar title="三一校验" />

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

        <van-form>
            <van-field
                v-model="licenseCode"
                name="licenseCode"
                label="证件码"
                placeholder="请输入证件码"
                clearable
                size="large"
                required
                :rules="rules.imei"
            >
                <template #right-icon>
                    <van-icon name="scan" color="#03a9f4" size="64" @click="scanCode('license')" />
                </template>
            </van-field>
            <span style="font-size:20px;font-weight:600;margin-left:0.5rem">解码结果:{{ licenseDecode }}</span>
            <van-field
                v-model="plateCode"
                class="margin-top-field"
                name="plateCode"
                label="车牌码"
                size="large"
                placeholder="请输入车牌码"
                clearable
                required
                :rules="rules.imei"
            >
                <template #right-icon>
                    <van-icon name="scan" color="#03a9f4" size="64" @click="scanCode('plate')" />
                </template>
            </van-field>
            <span style="font-size:20px;font-weight:600;margin-left:0.5rem">解码结果:{{ plateDecode }}</span>
            <van-field
                v-model="rfidCode"
                class="margin-top-field"
                name="rfidCode"
                label="标签码"
                size="large"
                placeholder="请输入标签码"
                clearable
                required
                :rules="rules.imei"
            >
                <template #right-icon>
                    <van-icon name="scan" color="#03a9f4" size="64" @click="scanCode('rfid')" />
                </template>
            </van-field>

            <div style="margin: 36px;margin-top:1.5rem">
                <van-button round block type="info" size="large" @click="onSubmit">校验</van-button>
            </div>

            <div class="foot-count-area">
                <span>已完成套件数:</span>
                <span style="font-size:42px;font-weight:600">{{seriCount}}</span>
                <van-icon style="maring-left:0.2rem" name="replay"  color="#03a9f4" size="24" @click="getSeriCount" />
            </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 {
            licenseCode: '',
            plateCode: '',
            rfidCode: '',
            seriCount: 0,
            licenseDecode: '',
            plateDecode: '',
            
            rules: {
                imei: [
                    { required: true, message: '请输入对应的码' },
                ]
            }
        }
    },
    created() {
        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 () {
            
            that.$notify( '初始化成功');

        }); 


        that.getSeriCount();

    },
    methods: {
        /**
         * 提交
         */
        getSeriCount(){
            let that = this;
            that.$http.get('getSeriCount')
                .then(resp => {
                    if (!resp.data.success) {
                        Dialog({ message: resp.data.message });
                        return;
                    }
                    that.seriCount = resp.data.data;
                })
        },
        onSubmit() {
            let that =this;

            let flag = that.licenseCode  && that.plateCode && that.rfidCode;
            if(!flag){
                Dialog({ message: '有码为空！！' });
            }
            if((that.licenseCode.indexOf("http://app.renlianiot.com/?ba") !== 0)) {
                Dialog({ message: '证件码前缀不符合规则' });
                return;
            }
            if((that.plateCode.indexOf("http://app.renlianiot.com/?ba") !== 0)) {
                Dialog({ message: '车牌码前缀不符合规则' });
                return;
            }
            if((that.rfidCode.indexOf("000") !== 0)) {
                Dialog({ message: '标签码前缀不符合规则' });
                return;
            }
            if( that.rfidCode.length != 10) {
                Dialog({ message: '标签码长度不符合规则' });
                return;
            }
            if( !( /^\d+$/.test(that.rfidCode) )  ) {
                Dialog({ message: '标签码不是纯数字' });
                return;
            }


            

            if(that.licenseCode !== that.plateCode){
                Dialog({ message: '证件码和车牌码不一致！！' });
                return;
            }


            let postData = {
                licenseCode: that.licenseCode ,
                rfidCode: that.rfidCode,
                plateCode: that.plateCode
            };
            that.$http({
                    method:'post',
                    url:"/verify_vehicle_code",
                    data:JSON.stringify(postData)
                }).then(resp  => {
                    if (!resp.data.success) {
                        Dialog({ message: resp.data.message });
                        return;
                    }
                    that.$notify({
                        type: 'success',
                        message: '绑定成功',
                    })
                    // 刷新列表
                    that.licenseCode ='';
                    that.plateCode ='';
                    that.rfidCode ='';
                    that.plateDecode = '';
                    that.licenseDecode = '';
                    that.seriCount = resp.data.data;

                });

            // console.log('onsubmit', values);
            // that.$http.get('verify_vehicle_code&licenseCode=' + that.licenseCode + '&rfidCode=' + that.rfidCode)
            //     .then(resp => {
            //         if (!resp.data.success) {
            //             Dialog({ message: resp.data.message });
            //             return;
            //         }
            //         that.$notify({
            //             type: 'success',
            //             message: '绑定成功',
            //         })
            //         // 刷新列表
            //         that.licenseCode ='';
            //         that.plateCode ='';
            //         that.rfidCode ='';
            //         that.seriCount = resp.data.data;
            //     })
        },
        /**
         * 扫码
         */
        scanCode(codeType) {

            let that = this;

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

                    if(codeType === 'license'){
                        that.licenseCode = result;
                        let liRes = that.decodeQrSecret(result, 'license');
                        
                        liRes.then((lres) => {
                            // Dialog({ message: lres });
                            that.licenseDecode = lres
                            console.log(lres)
                        }).catch((err) => {
                            // Dialog({ message: err });
                            that.licenseDecode = '解码失败';
                            console.log(err)
                        });
                    }
                    if(codeType === 'plate'){
                        that.plateCode = result;
                        let plRes = that.decodeQrSecret(result, 'plate');
                        plRes.then((pres) => {
                            // Dialog({ message: lres });
                            that.plateDecode = pres
                            console.log(pres)
                        }).catch((err) => {
                            // Dialog({ message: err });
                            that.plateDecode = '解码失败';
                            console.log(err)
                        });
                    }
                    if(codeType === 'rfid'){
                        that.rfidCode = result;
                        that.onSubmit();
                    }

                    
                },
                fail: function(e){
                    console.log('scan fail',e)
                }
            });

        },
        decodeQrSecret(code, type){
            let that= this;
            let postData = {
                qrCode : code,
                type: type
            }
            console.log(postData, 'post data')
            return new Promise((resolve, reject) => {
                that.$http({
                        method:'post',
                        url:"/decodeQrSecret",
                        data:JSON.stringify(postData)
                    }).then(resp  => {
                        if (!resp.data.success) {
                            console.log(resp.data, 'eeeee --')
                            reject(false)
                        }else{
                            console.log(resp.data, 'ddddd--')
                            resolve(resp.data.data)
                        }
                        

                    });
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.margin-top-field{
    margin-top: 1.1rem;
}
.foot-count-area{
    margin-left: 0.5rem;
    margin-top: 0.5rem;
}
</style>