// downline.js
const app = getApp(),
  { hostname } = app.globalData,
  userInfo = wx.getStorageSync('userInfo')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    firstActive: false,
    secondActive: false,
    downline: {
      one: [],
      two: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { share_id = '' } = options,
      that = this;
    wx.showLoading({
      title: '加载中',
    })
    // if (share_id) {
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({ userInfo })
      setTimeout(() => {
        that.getUserBanlance()
        that.getDownline()
        that.getServerUserInfo()
      }, 500)
    }, share_id)
    // }else{
    //   app.getUserInfo(function (userInfo) {
    //     //更新数据
    //     that.setData({ userInfo })
    //   }, share_id)
    // }
    // if (userInfo){
    //   this.setData({ userInfo })
    // }

    // options.withdraw && this.setData({ withdrawFlag: true})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showLoading({
      title: '加载中...',
    })
    this.getUserBanlance()
    this.getDownline()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },
  // 分享
  shareApp() {
    wx.showShareMenu({
      withShareTicket: false,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return {
      title: '邀请好友成为您的伙伴',
      path: '/pages/more/downLine/downLine?share_id=' + wx.getStorageSync('openid'),
      success: function (res) {
        // 转发成功
        wx.showToast({
          title: '分享成功',
        })
      },
      fail: function (res) {
        // 转发失败
        wx.showToast({
          title: '分享失败',
          image: '/images/warning.png'
        })
      }
    }
  },
  showQRCode() {
    wx.request({
      url: hostname + 'userCode',
      data: {
        user_id: wx.getStorageSync('openid')
      },
      success: res => {
        let img = res.data
        wx.previewImage({
          urls: [img],
        })
      }
    })
  },
  getServerUserInfo() {
    wx.request({
      url: hostname + 'getUser',
      data: {
        user_id: wx.getStorageSync('openid')
      },
      success: res => {
        console.log(res)
        let tempDate = new Date()
        tempDate.setTime(Number(res.data.create_time) * 1000)
        res.data.create_time = `${tempDate.getFullYear()}年${(tempDate.getMonth() + 1).toString().length > 1 ? tempDate.getMonth() + 1 : '0' + (tempDate.getMonth() + 1)}月${(tempDate.getDate()).toString().length > 1 ? tempDate.getDate() : '0' + tempDate.getDate()}日 ${(tempDate.getHours()).toString().length > 1 ? tempDate.getHours() : '0' + tempDate.getHours()}:${(tempDate.getMinutes()).toString().length > 1 ? tempDate.getMinutes() : '0' + tempDate.getMinutes()}`
        this.setData({
          userData: res.data
        })
      },
      complete: () => {
        setTimeout(() => wx.hideLoading(), 1000)
      }
    })
  },
  getDownline() {
    let that = this
    wx.request({
      url: hostname + 'share_friend',
      data: {
        // user_id: 100445
        user_id: wx.getStorageSync('openid')

      },
      success: (res) => {
        let downline = res.data.data
        if (res.data.code == 200) {
          let downline = res.data.data
          let two = []
          downline.two.forEach(item => {
            item.forEach(person =>
              two.push(person)
            )
          })
          downline.two = two
          let downlineCount = downline.one.length + downline.two.length
          that.setData({ downline, downlineCount })
        }
        // 获取订单数量
        wx.request({
          url: hostname + 'share_order',
          data: {
            user_id: wx.getStorageSync('openid')
          },
          success: res => {
            if (res.data.code == 200) {
              let orderList = res.data.data
              that.setData({
                orderCount: orderList.length
              })
            }
          },
          fail: function (res) { },
          complete: function (res) {
            setTimeout(() => wx.hideLoading(), 1000)
          },
        })
        // 获取佣金数量
        wx.request({
          url: hostname + 'share_money',
          data: {
            user_id: wx.getStorageSync('openid')
          },
          success: res => {
            console.log(res)
            this.setData({
              userMoney: res.data.data
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      }
    })
  },

  getUserBanlance() {
    let warnTips = setTimeout(() => {
      wx.showToast({
        title: '请求超时',
        image: '/images/warning.png'
      })
    }, 10000),
      that = this
    wx.request({
      url: hostname + 'userinfo',
      data: {
        user_id: wx.getStorageSync('openid')
      },
      success: function (res) {
        if (res.data.code == 200) {
          that.setData({ money: res.data.data.share_money })
        }
      },
      fail: function (res) { },
      complete: function (res) {
        clearTimeout(warnTips)
        setTimeout(() => wx.hideLoading(), 1000)
      },
    })
    //获取用户余额
  },
  // 显示一级下线 
  showFirstDownline() {
    let firstActive = this.data.firstActive
    this.setData({ firstActive: !firstActive })
  },
  // 显示二级下线
  showSecondDownline() {
    let secondActive = this.data.secondActive
    this.setData({ secondActive: !secondActive })
  },
  // 显示提现窗口
  // showWithdraw(e) {
  //   let { attr } = e.target.dataset
  //   console.log(attr, e)
  //   if (attr) {
  //     if (this.data.money > 0) {
  //       this.setData({ withdrawFlag: true })
  //     }
  //   } else {
  //     this.setData({ withdrawFlag: false })
  //   }
  // },
  // 提现
  getWithdraw() {
    let { withdrawMoney, withdrawName, withdrawCard, withdrawBank } = this.data,
      that = this
    if (!withdrawMoney) {
      wx.showModal({
        title: '提示',
        content: '请输入要提现的金额',
        showCancel: false
      })
    } else {
      wx.showLoading({
        title: '请稍后..',
      })
      wx.request({
        url: hostname + 'cash_apply',
        data: {
          user_id: wx.getStorageSync('openid'),
          money: withdrawMoney,
          card_number: withdrawCard,
          name: withdrawName,
          bank: withdrawBank
        },
        success: function (res) {
          if (res.data == 10000) {
            wx.showToast({
              title: '提现成功',
              duration: 2500,
              success: () => {
                that.setData({
                  withdrawName: '',
                  withdrawBank: '',
                  withdrawCard: '',
                  withdrawMoney: '',
                  withdrawFlag: false
                })
              }
            })
          }
        },
        fail: function (res) { },
        complete: function (res) {
          setTimeout(() => {
            setTimeout(() => wx.hideLoading(), 1000)
          }, 1500)
        },
      })
    }
  },
  // 同步输入
  syncInfo(e) {
    let value = e.detail.value,
      { info } = e.currentTarget.dataset
    switch (info) {
      case 'name':
        this.setData({ withdrawName: value })
        break;
      case 'card_num':
        this.setData({ withdrawCard: value })
        break;
      case 'bank':
        this.setData({ withdrawBank: value })
        break;
      case 'money':
        this.setData({ withdrawMoney: value })
        break;
    }
  }
})