<template>
  <div id="app"
       style="height:100%;">
    <view-box ref="viewBox">
      <router-view></router-view>
      <!--bottom slot-->
      <tabbar slot="bottom"
              v-show="showTab">
        <tabbar-item :link="{path:'/'}"
                     :selected="$route.path === '/'">
          <img slot="icon"
               src="./assets/images/list1.png"
               v-if="($route.path === '/' || $route.path.indexOf('/detail/') !== -1)">
          <img slot="icon"
               src="./assets/images/list0.png"
               v-else>
          <span slot="label">设备列表</span>
        </tabbar-item>
        <tabbar-item v-if="lockflag == 1">
          <img slot="icon"
               @click="opendoor"
               src="./assets/images/sm.png">
          <span slot="label">扫码</span>
        </tabbar-item>
        <tabbar-item :link="{path:'/profile'}">
          <img slot="icon"
               src="./assets/images/user1.png"
               v-if="$route.path === '/profile'">
          <img slot="icon"
               src="./assets/images/user0.png"
               v-else>
          <span slot="label">我</span>
        </tabbar-item>
      </tabbar>
    </view-box>
  </div>
</template>

<script>
import {
  Tabbar,
  TabbarItem,
  Loading,
  ViewBox,
  XHeader
} from 'vux'
import wx from 'weixin-jsapi'
import Vue from 'vue'
Vue.prototype.wx = wx
import axios from 'axios'
import store from 'store'
import dataManager from 'SERVICES/dataManager'
export default {
  name: 'app',
  components: {
    Tabbar,
    TabbarItem,
    Loading,
    ViewBox,
    XHeader
  },
  data () {
    return {
      // userService, // 实现 userService 挂载 data 的可追踪
      userData: null, // 须与 userService.data【手动】同步
      isLoading: false,
      lockflag: 0,  // 是否显示扫码
      seriallist: ''
    }
  },
  created () {
    this.openid = store.get('ygopenid')
    // this.wxInitialization()
    // this.getChannels()
  },
  methods: {
    getChannels () {
      const params = { _currentPage: this.currentPage, _size: 100, keyword: this.keyword, openid: this.openid }
      this.$services.channel.get('list', { params })
        .then(res => {
          this.lockflag = 0
          this.seriallist = ''
          for (var i = 0; i < res.data.items.length; i++) {
            if (res.data.items[i].DataItem === 31) {
              this.lockflag = 1
              this.seriallist = this.seriallist + res.data.items[i].Serial + ','
              // console.log('----this.seriallist----', this.seriallist)
            }
          }
        }).catch(() => { })
    },
    wxInitialization () {
      // const params = { openid: 'wx.labsop.cn/ui/index.html#/profile' }
      const params = { openid: location.href.split('#')[0] }
      this.$services.channel.get('getwxconfig', { params })
        .then(res => {
          wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: res.data.items.app_id, // 必填，公众号的唯一标识
            timestamp: res.data.items.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.data.items.nonce_str, // 必填，生成签名的随机串
            signature: res.data.items.signature, // 必填，签名，见附录1
            jsApiList: [
              'checkJsApi',
              'startRecord',
              'stopRecord',
              'translateVoice',
              'scanQRCode', // 微信扫一扫接口
              'openCard'
            ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
          });
          wx.error(function (res) {
            alert('出错了：' + res.errMsg);// 这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
          });
          wx.ready(function () {
            wx.checkJsApi({
              jsApiList: ['scanQRCode'],
              success: function (res) {
              }
            });
          });
        })

      // this.$router.replace({ path: '/open' })

      // axios.request({
      //   method: 'get',
      //   url: 'http://39.98.34.197:12001/api/remote_control/rtuseedcmd?code=63000105&instruction=DO1=1'
      // }).then(resp => {
      //   console.log('start --->', resp.data);
      //   this.showInfo = true;
      //   this.info = '开锁成功';
      //   this.showtype = 'success';
      // }).catch(error => {
      //   console.log(error);
      // });
    },
    opendoor () {
      const params = { _currentPage: this.currentPage, _size: 100, keyword: this.keyword, openid: this.openid }
      this.$services.channel.get('list', { params })
        .then(res => {
          var seriallist = ''
          for (var i = 0; i < res.data.items.length; i++) {
            if (res.data.items[i].DataItem === 31) {
              seriallist = seriallist + res.data.items[i].Serial + ','
              // console.log('----this.seriallist----', seriallist)
            }
          }
          wx.scanQRCode({
            needResult: 1, // 默认为0，扫描结果由微信处理，1 则直接返回扫描结果，
            scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
            success: function (res) {
              var result = res.resultStr;
              axios.request({
                method: 'get',
                url: 'http://iot.labsop.cn:12001/api/remote_control/rtuseedcmd?instruction=DO1=1&code=' + result + '&ygnick=' + store.get('ygnick') + '&ygopenid=' + store.get('ygopenid') + '&seriallist=' + seriallist
              }).then(resp => {
                // console.log('start -123-->', resp.data);
                if (resp.data.code !== 0) {
                  alert('操作失败')
                } else {
                  alert('操作成功')
                }
                // this.showInfo = true;
                // this.info = '开锁成功';
                // this.showtype = 'success';
              }).catch(error => {
                console.log(error);
              });
            },
            error: function (res) {
              alert(res, 2);
              if (res.errMsg.indexOf('function_not_exist') > 0) {
                alert('版本过低请升级')
              }
            }
          });
        }).catch(() => { })
    },
    scrollTop () {
      this.$refs.viewBox.$els.viewBoxBody.scrollTop = 0
    },
    print () {
      console.info('[Print] ' + this.$route.path.substring(8));
      // if (dataManager.deviceType() === 'iOS') {
      //   WebViewJavascriptBridge.printChannelData(this.$route.path.substring(8));
      // }
    }
  },
  computed: {
    leftOptions () {
      return {
        showBack: this.$route.path.indexOf('/detail/') !== -1
      }
    },
    getTitle () {
      return dataManager.getNavTitle()
    },
    showPrint () {
      return false
    },
    showTab () {
      return this.$route.path !== '/login'
    },
    title () {
      if (this.$route.path === '/') return '设备列表'
      if (this.$route.path === '/about') return '关于'
      if (this.$route.path === '/profile') return '我'
      if (this.$route.path === '/login') return '账号绑定'
      if (this.$route.path === '/setting') return '设置'
      if (this.$route.path.indexOf('/detail/') !== -1) return '详细信息'
      return this.$route.name
    }
  }
}
</script>

<style lang="less">
@import "~vux/src/styles/reset.less";

@font-face {
  font-family: "Oswald";
  src: url("assets/font/Oswald-Light.ttf");
}

body,
html {
  height: 100%;
  width: 100%;
  overflow-x: hidden;
}
body {
  background-color: #fbf9fe;
}
.vux-demo-header-box {
  z-index: 100;
  position: absolute;
  width: 100%;
  left: 0;
  top: 0;
}
.weui_tab_bd {
  padding-top: 46px;
}
</style>
