// component/userinfo/userinfo.js
let common = require('../../utils/util.js');
var that
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    mytitle: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    isshow: "none",
    info: {},
    imgurl: common.imgurl,
    isfh: false

  },
  ready: function() {
    that = this
    wx.setNavigationBarTitle({
      title: "授权登录" //页面标题为路由参数
    })
    this.initshow();

  },
  /**
   * 组件的方法列表
   */
  methods: {

    //初始判断是否已有用户信息
    initshow(e) {

      var ui = wx.getStorageSync("userinfo");
      if (ui == "") {
        this.setData({
          isshow: ""
        });
        this.initopenid()
      } else if (ui.openId == undefined && ui.nickName != undefined) {
        this.setData({
          info: ui
        })
        this.initopenid()
        this.infoback(ui);
      } else if (ui.nickName == undefined && ui.openId != undefined) {
        this.setData({
          isshow: "",
          info: ui
        });
      } else {
        this.setData({
          isshow: "none"
        });
        this.infoback(ui);
      }

    },
    initopenid() {
      common.initopenid(function(op) {
        var io = that.data.info
        io.openId = op
        that.setData({
          info: io
        })
        that.callback()
      })
    },
    onGotUserInfo: function(e) {
      var io = Object.assign(e.detail.userInfo, this.data.info)
      var ino = that.data.info
      if (ino.openId != undefined) {
        io.openId = ino.openId
      }
      that.setData({
        info: io
      })

      this.callback()
    },
    callback() {
      if (this.data.info.openId == undefined) {
        return
      }
      if (this.data.info.nickName == undefined) {
        return
      }
      wx.setStorageSync("userinfo", this.data.info)
      this.setData({
        isshow: "none"
      })

      this.infoback(this.data.info)
    },
    saveuser(info) {
      common.query("cuser/wxcheckcuser?openId=" + info.openId, {}, function(res) {
        if (res.code != 10000) {
          common.query("cuser/wxcreatecuser", info, function(d) {

          }, 'POST')
        } else {
          // if (!res.data.actvied) {
          //   that.setData({
          //     isfh: true
          //   })
          // }
        }
      })
    },
    infoback(info) {
      this.saveuser(info)
      wx.setNavigationBarTitle({
        title: this.properties.mytitle
      })
      let myEventOption = {
        bubbles: false, //事件是否冒泡
        composed: false, //事件是否可以穿越组件边界
        capturePhase: false //事件是否拥有捕获阶段
      } // 触发事件的选项
      this.triggerEvent('info', info, myEventOption)
    }
  }
})