<template>
    <div>
        <van-nav-bar :title='appTitle'>
            <template #left>
                <van-icon name='wap-home-o' size='1.5em' color='#000' @click='backApp' />
            </template>
            <template #right>
                <van-icon name='search' size='1.5em' color='#000' @click='query' />
                <van-icon name='scan' size='1.5em' color='#000' style='margin-left:0.5em' @click='scan' />
            </template>
        </van-nav-bar>
    </div>
</template>
<script>
import Vue from 'vue'
import { NavBar, Icon, Tabbar, TabbarItem, Toast } from 'vant'
Vue.use(NavBar).use(Icon)
import { mapGetters, mapMutations } from 'vuex'
import store from '@/store'
import { debounce } from 'lodash'
// 扫一扫回到函数
window.__scanCallback = function (data) {
    console.log('__scanCallback')
    console.log(data)
    switch (data.code) {
        // 扫描的⾮设备⼆维码
        case 0:
        case '0':
            // Toast('扫描的⾮设备⼆维码')
            store.commit('SCANASSETID', null)
            break
        // 扫码的是设备二维码
        case 1:
        case '1':
            // 设置时间,防止两次扫描同一个设备,assetid不改变,watch监听不触发
            let time = new Date().getTime()
            store.commit('SCANASSETID', `${data.text}__${time}`)
            break
        // 扫码失败
        case -1:
        case '-1':
            store.commit('SCANASSETID', null)
            Toast('扫码出错')
            break

        default:
            break
    }
}
export default {
    name: 'navbar',
    props: {},
    components: {},
    data() {
        return {}
    },
    computed: {
        ...mapGetters(['appTitle', 'scanAssetid']),
    },
    watch: {
        // 扫到二维码,跳转设备详情页
        scanAssetid(newV, oldV) {
            if (newV) {
                let assetid = newV.split('__')[0]
                this.$router.push({ name: 'AssetDetail', query: { assetid } })
            }
        },
    },
    beforeMount() {},
    mounted() {},
    methods: {
        ...mapMutations(['SCANASSETID']),
        // 返回工程信息化主菜单
        backApp() {
            console.log('backApp')
            window.webkit &&
                webkit.messageHandlers.cordova_iab.postMessage(
                    JSON.stringify({
                        method: 'close',
                    })
                )
        },
        // 扫码,300ms触发一次
        scan: debounce(function () {
            console.log('扫码')
            window.webkit &&
                webkit.messageHandlers.cordova_iab.postMessage(
                    JSON.stringify({
                        method: 'scan',
                    })
                )
        }, 300),

        // 全局搜索
        query() {
            this.$router.push({ name: 'GlobalSearch' })
        },
    },
}
</script>
<style lang='less' scoped>
</style>