//index.js
var util = require('../../utils/util.js');
var status = require('../../utils/index.js');
var wcache = require('../../utils/wcache.js');

var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tablebar: 4,
    canIUse: wx.canIUse("button.open-type.getUserInfo"),
    theme_type: '',
    add_mo: 0,
    is_show_on: 0,
    level_name: '',
    member_level_is_open: 0,
    is_yue_open: 0,
    is_login: true,
    opencommiss: 0,
    inputValue: 0,
    getfocus: false,
    showguess: true,
    items: [],
    auditStatus: 5,
    isShowCoder: false,
    myCoderList: [],
    qrcodebase64: "",
    setInter: null,
    copyright: '',
    common_header_backgroundimage: '',
    enabled_front_supply: 0,
    cartNum: 0,
    is_show_about_us: 0,
    groupInfo: {
      group_name: '社区',
      owner_name: '团长'
    },
    is_show_score: 0,
    showGetPhone: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideTabBar();
    let that = this;
    status.setNavBgColor();
    status.setGroupInfo().then((groupInfo) => { that.setData({ groupInfo }) });
    wx.showLoading();
    this.getCopyright();
  },

  getMemberInfo: function(){
    var token = wx.getStorageSync('token');
    let that = this;
    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'user.get_user_info',
        token: token
      },
      dataType: 'json',
      success: function (res) {
        wx.hideLoading();
        if (res.data.code == 0) {
          let showGetPhone = false;
          if (res.data.is_show_auth_mobile == 1 && !res.data.data.telephone) showGetPhone = true;
          let member_info = res.data.data;

          let params = {};
          //开启分销
          if (res.data.commiss_level > 0) {
            //还差多少人升级
            let commiss_share_member_update = res.data.commiss_share_member_update * 1;
            let share_member_count = res.data.share_member_count * 1;
            let need_num_update = res.data.commiss_share_member_update*1 - res.data.share_member_count*1;

            //判断表单状态状态
            let formStatus = 0; //未填写 1 已填写未审核 2 已审核
            if (member_info.is_writecommiss_form == 1) {
              formStatus = 1;
              //已填写
              if (member_info.comsiss_flag == 1) {
                member_info.comsiss_state == 0 ? formStatus = 1 : formStatus = 2;
              }
            }

            params = {
              formStatus,
              commiss_level: res.data.commiss_level,
              commiss_sharemember_need: res.data.commiss_sharemember_need,
              commiss_share_member_update,
              commiss_biaodan_need: res.data.commiss_biaodan_need,
              share_member_count,
              today_share_member_count: res.data.today_share_member_count,
              yestoday_share_member_count: res.data.yestoday_share_member_count,
              need_num_update
            };
          }

          that.setData({
            ...params,
            member_info,
            enabled_front_supply: res.data.enabled_front_supply,
            is_supply: res.data.is_supply,
            is_open_yue_pay: res.data.is_open_yue_pay,
            is_show_score: res.data.is_show_score,
            showGetPhone: showGetPhone,
            index_top_font_color: res.data.index_top_font_color || '#fff',
            user_order_menu_icons: res.data.user_order_menu_icons || {},
            commiss_diy_name: res.data.commiss_diy_name || '分销',
            close_community_apply_enter: res.data.close_community_apply_enter || 0
          });
        } else {
          //is_login
          that.setData({
            is_login: false
          })
          wx.hideTabBar();
          wx.setStorage({
            key: "member_id",
            data: null
          })
        }
      }
    })
  },

  getCopyright: function (){
    let that = this;
    app.util.request({
      'url': 'entry/wxapp/user',
      'data': {
        controller: 'user.get_copyright'
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.code == 0) {
          that.setData({
            copyright: res.data.data || '',
            common_header_backgroundimage: res.data.common_header_backgroundimage || '',
            is_show_about_us: res.data.is_show_about_us || 0
          })
        }
      }
    })
  },

  /**
   * 授权成功回调
   */
  authSuccess: function() {
    wx.reLaunch({
      url: '/lionfish_comshop/pages/user/me',
    })
  },

  /**
   * 跳转团长中心
   */
  goToGroup: function() {
    5 === this.data.auditStatus ? wx.navigateTo({
      url: "/lionfish_comshop/pages/groupCenter/index"
    }) : wx.navigateTo({
      url: "/lionfish_comshop/pages/groupCenter/apply"
    });
  },

  /**
   * 更新资料
   */
  bindGetUserInfo: function (e) {
    let that = this;
    if ("getUserInfo:ok" === e.detail.errMsg) {
      var userInfo = Object.assign({}, wx.getStorageSync("userInfo"), {
        avatarUrl: e.detail.userInfo.avatarUrl,
        nickName: e.detail.userInfo.nickName
      });
      app.globalData.userInfo = userInfo, wx.setStorage({
        key: "userInfo",
        data: userInfo
      }), this.setData({
        userInfo: userInfo
      }), wx.showToast({
        title: "资料已更新",
        icon: "none",
        duration: 2000
        }),app.util.request({
          'url': 'entry/wxapp/user',
          'data': {
            controller: 'user.update_user_info',
            memberId: wx.getStorageSync("member_id"),
            nickName: e.detail.userInfo.nickName,
            avatarUrl: e.detail.userInfo.avatarUrl
          },
          dataType: 'json',
          success: function (res) {
            let member_info = that.data.member_info;
            let user_info = Object.assign({}, member_info, {
              avatar: e.detail.userInfo.avatarUrl,
              username: e.detail.userInfo.nickName
            });
            that.setData({
              member_info: user_info
            })
          }
        })
    } else {
      wx.showToast({
        title: "资料更新失败。",
        icon: "none"
      });
    }
  },

  /** 
	 * 预览图片
	 */
  previewImage: function (e) {
    var current = e.target.dataset.src;
    current && wx.previewImage({
      current: current,
      urls: [current]
    })
  },

  goLink2: function(event) {
    let link = event.currentTarget.dataset.link;
    var pages_all = getCurrentPages();
    if (pages_all.length > 3) {
      wx.redirectTo({
        url: link
      })
    } else {
      wx.navigateTo({
        url: link
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      tabbarRefresh: true
    })
    var that = this;
    (0, status.cartNum)('', true).then((res) => {
      res.code == 0 && that.setData({ cartNum: res.data })
    });

    util.check_login() ? this.setData({ is_login: true }) : this.setData({ is_login: false });
    this.getMemberInfo()
    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({ tabbarRefresh: false })
  },

  /**
    * 设置手机号
  */
  getReceiveMobile: function (e) {
    var num = e.detail;
    wx.showToast({
      icon: 'none',
      title: '授权成功',
    })
    this.setData({
      showGetPhone: false
    });
  },

  /**
    * 关闭手机授权
  */
  close: function () {
    this.setData({
      showGetPhone: false
    });
  },

  /**
    * 关闭分销
  */
  closeDistribution: function(){
    this.setData({ showDistribution: false })
  },

  /**
    * 分销下一步
  */
  goDistribution: function(){
    let member_info = this.data.member_info;
    //判断是不是分销商
    if (member_info.comsiss_flag==0) {
      this.distributionNext();
    } else {
      if (member_info.comsiss_state==0) {
        //分销商未审核
        this.distributionNext();
      } else {
        //分销商已审核
        wx.navigateTo({
          url: '/lionfish_comshop/pages/distribution/me',
        })
      }
    }
  },

  distributionNext: function(){
    if (this.data.commiss_sharemember_need==1) {
      console.log('需要分享');
      let url = '/lionfish_comshop/pages/distribution/recruit';
      wx.navigateTo({ url })
    } else if (this.data.commiss_biaodan_need==1){
      console.log('需要表单');
      // let url = '/lionfish_comshop/pages/distribution/apply';
      wx.navigateTo({
        url: '/lionfish_comshop/pages/distribution/recruit',
      })
    } else {
      // 跳转表单自动审核
      let status = 0;
      let member_info = this.data.member_info;
      if (member_info.comsiss_flag == 1) {
        member_info.comsiss_state == 0 ? status = 1 : status = 2;
      }
      let url = '/lionfish_comshop/pages/distribution/recruit';
      if(status==2){
        url = '/lionfish_comshop/pages/distribution/me';
      }
      wx.navigateTo({ url })
    }
  },

  goNext: function(e){
    console.log(e)
    let status = 0;
    let member_info = this.data.member_info;
    if (member_info.comsiss_flag == 1) {
      member_info.comsiss_state == 0 ? status = 1 : status = 2;
    }
    let type = e.currentTarget.dataset.type; 
    if (type=='share'){
      wx.navigateTo({
        url: '/lionfish_comshop/pages/distribution/share',
      })
    } else if (type=='commiss'){
      if(status == 2){
        wx.navigateTo({
          url: '/lionfish_comshop/pages/distribution/me',
        })
      } else {
        wx.navigateTo({
          url: '/lionfish_comshop/pages/distribution/recruit',
        })
      }
    } else if (type =='form'){
      if (status == 2) {
        wx.navigateTo({
          url: '/lionfish_comshop/pages/distribution/me',
        })
      } else {
        // let url = '/lionfish_comshop/pages/distribution/apply';
        wx.navigateTo({
          url: '/lionfish_comshop/pages/distribution/recruit',
        })
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})