const util = require("../../utils/util.js");
const app = getApp();
Page({
  data: {
    make: false,
    type: "",
    invite: "",
    userInfo: "",
    invitePrice: util.config.invitePrice
  },
  onLoad(options) {
    let userInfo = app.globalData.userInfo;
    userInfo.recomCode = !util.isEmpty(userInfo.recomCode) ? userInfo.recomCode : '';
    this.setData({ type: options.type || '', userInfo });
    if (options.type == 'account' && !util.isEmpty(userInfo.recomCode)){
      this.data.invite = userInfo.recomCode;
      this.setData({ invite: this.data.invite });
      this.getUserInfo(1);
    } else if (!util.isEmpty(wx.getStorageSync("WX-invite"))){
      this.getUserInfo(0);
    }
  },
  inputinvite(e) {
    let val = e.detail.value;
    if (val.length == 6){
      this.setData({ invite: val });
      this.getUserInfo(1);
    }else{
      this.setData({ info: '', invite: val });
    }
  },
  getUserInfo(type) {
    let that = this;
    util.ajax({
      func: "inviter/info",
      data: { "code": type == 1 ? that.data.invite : wx.getStorageSync("WX-invite") }
    }, function (res) {
      if (res.code == 0) {
        res.data.avatar = !util.isEmpty(res.data.avatar) ? res.data.avatar : '/images/default_logo.jpg';
        if (res.data.roleType == 'sharer' || res.data.roleType == 'organ') {
          type == 0 ? that.data.invite = wx.getStorageSync("WX-invite") : '';
          that.setData({ info: res.data, invite: that.data.invite });
        } else if (type == 1){
          that.setData({ info: res.data, invite: that.data.invite });
        }
      } else{
        that.setData({ info: "" });
        type == 1 ?util.showTips(res.reason) : "";
      }
    });
  },
  submit() {
    let that = this;
    if (this.data.invite.length != 6) {
      util.showTips("请输入有效的6位邀请码。");
      return false;
    }
    if (this.data.info.roleType == 'normal') {
      util.showTips("该用户不是分享家/机构。");
      return false;
    }
    if (this.data.info.roleTypeDisable == 1) {
      util.showTips("该分享家/机构未启用。");
      return false;
    }
    util.ajax({
      func: "user/savecode",
      data: { "code": that.data.invite,receiveType:that.data.type?1:0}
    }, function (res) {
      if (res.code == 0) {
        app.globalData.userInfo['recomCode'] = that.data.invite;
        wx.setStorageSync("WXuserInfo", app.globalData.userInfo);
        if (that.data.info.roleType == 'sharer' || that.data.info.roleType == 'organ'){
          that.setData({ make: false, vouchers: res.vouchers,invitePrice:res.invitePrice});
        }else{
          that.back();
        }
      } else
        util.showTips(res.reason);
    });
  },
  back(e) {
    this.setData({
      make: true
    });
    if(this.data.type == "share"){
      wx.reLaunch({
        url: '/pages/home/index',
      });
    }else{
      wx.navigateBack({
        delta: (this.data.type == "account" ? 1 : 2)
      });
    }
  }
})