<template>
  <div>
    <loading v-if="isLoading"
             :show="isLoading"
             text="正在加载"></loading>
    <div>
      <div class="p-base p-header">
        <img class="p-avatar"
             :src="imageURL">
        <span>{{user.Username}}</span>
      </div>
      <div class="p-base p-info">
        <table cellspacing="0">
          <tr>
            <td class="cell1">
              <span class="s1">名称</span>
              <span class="s2">{{user.Realname}}</span>
            </td>
            <td class="cell2">
              <span class="s1">手机</span>
              <span class="s2">{{user.Telephone}}</span>
            </td>
          </tr>
          <tr>
            <td class="cell3">
              <span class="s1">电话</span>
              <span class="s2">{{user.Mobile ? user.Mobile : '无'}}</span>
            </td>
            <td>
              <span class="s1">邮箱</span>
              <span class="s2">{{user.Email ? user.Email : '无'}}</span>
            </td>
          </tr>
        </table>
      </div>
      <box gap="20px 10px">
        <x-button type="primary"
                  @click.native="generateaction">生成报警动作</x-button>
        <x-button type="warn"
                  @click.native="logout">重新绑定</x-button>
        <!-- <x-button v-if="lockflag == 1"
                  type="warn"
                  @click.native="opendoor">开锁</x-button> -->
      </box>
      <actionsheet v-model="asShow"
                   :menus="asMenu"
                   @on-click-menu="doLogout"
                   show-cancel
                   cancel-text="取消"></actionsheet>
      <toast v-model="showInfo"
             :type="showtype"
             :time="2000">{{info}}</toast>
    </div>
  </div>
</template>

<script>
import {
  XButton,
  Box,
  Actionsheet,
  Loading,
  Toast
} from 'vux'
import {
  mapGetters
} from 'vuex'
import store from 'store'
import wx from 'weixin-jsapi'
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.wx = wx
// import wx from "weixin-jsapi"

export default {
  name: 'profile',
  components: {
    XButton,
    Box,
    Actionsheet,
    Loading,
    Toast
  },
  data () {
    return {
      isLoading: false,
      asShow: false,
      lockflag: 0,
      openid: '',
      user: {},
      username: '',
      imageURL: '',
      baseURL: 'http://1.117.158.212:8081',
      asMenu: {
        confirm: '去绑定账号'
      },
      currentPage: 1,
      size: 6,
      currentItemCount: 0,
      keyword: '',
      showInfo: false,
      info: '',
      showtype: ''
    }
  },
  computed: mapGetters({
    session: 'session'
  }),
  created () {
    this.openid = store.get('ygopenid')
    this.getuserinfo()
    // 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 => {
          for (var i = 0; i < res.data.items.length; i++) {
            if (res.data.items[i].DataItem === 31) {
              this.lockflag = 1
            }
          }
        }).catch(() => { })
    },
    logout () {
      this.asShow = true;
    },
    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 () {
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1 则直接返回扫描结果，
        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          // console.log('------res.resultStr----', res.resultStr)
          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')
          }).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('版本过低请升级')
          }
        }
      });
    },
    doLogout (key) {
      if (key === 'confirm') {
        this.$store.dispatch('deleteToken')
        this.$router.replace({ path: '/login' })
      }
    },
    getuserinfo () {
      const params = { openid: store.get('ygopenid') }
      this.$services.user.get('me', { params })
        .then(res => {
          this.user = res.data.Profile;
          this.imageURL = this.baseURL + this.user.Photo;
          if (this.user.Photo === '') {
            this.imageURL = this.imageURL + '/static/equipmentimg/avatar-default.jpg'
          }
        }).catch(() => {

        })
    },
    generateaction () {
      let _this = this
      let params = { openid: store.get('ygopenid'), nick: store.get('ygnick') }
      return _this.$services.channel.put('generateaction', params)
        .then(res => {
          if (res.data.code === 0) {
            this.showInfo = true;
            this.info = res.data.message;
            this.showtype = 'success';
          } else {
            this.showInfo = true;
            this.info = res.data.message;
            this.showtype = 'cancel';
          }
        })
    }
  }
}
</script>

<style>
html,
body {
  background-color: #eeeeee;
  color: #424242;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
}

.p-base {
  border-top: 1px solid #e0e0e0;
  border-bottom: 1px solid #e0e0e0;
  background-color: white;
  margin-top: 20px;
}

.p-info {
  display: block;
  width: 100%;
}

.p-info table {
  width: 100%;
}

.p-info table td {
  padding: 10px;
  width: 50%;
}

.cell1 {
  border-bottom: 1px solid #eeeeee;
  border-right: 1px solid #eeeeee;
}

.cell2 {
  border-bottom: 1px solid #eeeeee;
}

.cell3 {
  border-right: 1px solid #eeeeee;
}

.s1 {
  display: block;
  color: #9e9e9e;
  font-size: 14px;
}

.s2 {
  display: block;
}

.p-header {
  text-align: center;
  padding: 20px;
}

.p-header span {
  display: block;
  font-size: 20px;
}

.p-avatar {
  width: 100px;
  height: 100px;
}
</style>
