// pages/pandaBonus/pandaBonus.js
const app = getApp();
const getReq = require('../../config.js').getReq;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openAnimation: true, // 点击开红包
    activityType: '',  // 1 活动未开始
    renderCount: [],
    bonus_state: '',
    mine_bonus: '',
    reveive_info: '',
    binded_info: [], // 领取列表
    msg: '',
    mineid: '',
    type_sn: '',
    message_flag: false,
    input_msg: '',
    result_msg: '留言',
    summarys: false,
    userInfo: app.globalData.userInfo,
    options: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    this.setData({
      options
    })
    if (app.globalData.userInfo) {
      self.init(options)
      self.setData({
        userInfo: app.globalData.userInfo
      })
    }
  },
  getAuth(e) {
    let { userInfo } = e.detail
    if (userInfo) {
      this.init(this.data.options)
      this.setData({
        userInfo
      })
    }
  },
  init(options) {
    let self = this
    let { type_sn, relay_id = '' } = options
    let params = {
      act: 'bonusex',
      op: 'open',
      type_sn
    }
    self.getDatas(params)
    self.setData({
      type_sn,
      relay_id
    })
  },
  detail() {
    let params = {
      act: 'bonusex',
      op: 'detail',
      type_sn: this.data.type_sn
    }
    this.getDatas(params)
  },
  grab() {
    let params = {
      act: 'bonusex',
      op: 'grab',
      type_sn: this.data.type_sn
    }
    this.getDatas(params)
  },
  getDatas(params) {
    let self = this
    getReq(app,params, function (res) {
      if (res.code == 200) {
        let { type_info, bonus_state } = res.datas
        if (bonus_state == 'unstart') {
          // bonus_state: unstart 活动未开始
          let { send_start_date } = type_info
          self.countTime(params, send_start_date)
          self.setData({
            bonus_state
          })
          return
        }
        else if (bonus_state == 'open') {
          // open 活动开始， 可以点击， 红包金额有 固定， 随机
          self.setData({
            type_info,
            bonus_state
          })
          return
        }
        else if (bonus_state == 'detail') {
          // 已点开状态， 详情
          let { avatars, mine_bonus, mineid, summarys } = res.datas
          let { sender_id, relayer_id } = type_info

          let sender_head_src = self.senderHead(relayer_id, sender_id, avatars)
          let reveive_info = self.receiveInfo(type_info) // 展示领取信息
          if (summarys) {
            summarys = summarys.map(item => {
              item['goods_lowest_price'] = parseFloat(item['goods_lowest_price'])
              item['goods_price'] = parseFloat(item['goods_price'])
              return item
            })
          }
          //领取列表
          let binded_info = []
          if (res.datas['binded_info']) {
            binded_info = self.getBindedInfo(res.datas['binded_info'], avatars, type_info)
          }
          if (mine_bonus) {
            mine_bonus['bonus_value'] = parseInt(mine_bonus['bonus_value'] * 100 + 0.5) / 100
          }
          self.setData({
            sender_head_src,
            type_info,
            bonus_state,
            mine_bonus,
            reveive_info,
            binded_info,
            mineid: mineid.toString(),
            summarys
          })
          return
        }
        else if (bonus_state == 'over') {
          let { msg } = res.datas
          self.setData({
            msg,
            bonus_state
          })
          return
        }
        else if (bonus_state == 'end') {
          self.setData({
            type_info,
            bonus_state
          })
          return
        }
        else {
          wx.showModal({
            confirmText: '重试',
            content: '网络错误',
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: "/pages/index/index"
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    });
  },
  getBindedInfo(binded_info, avatars, type_info) {
    let self = this
    return binded_info.map(item => {
      if (avatars[item['user_id']]) {
        let avatarItem = avatars[item['user_id']]
        item['avatar'] = avatarItem['avatar']
        let discount = parseInt(avatarItem['discount'] * 100 + 0.5)
        if (discount != 0) {
          discount = discount / 100
        }
        item['discount'] = discount
      }
      else {
        item['avatar'] = '../../image/bonus/female.png'
        item['discount'] = 0
      }
      item['is_king'] = self.isKing(type_info, item['bonus_value'])
      item['format_time'] = self.formatTime(item['get_time'])
      item['bonus_value'] = parseInt(item['bonus_value'] * 100 + 0.5) / 100
      return item
    })
  },
  // 判断手气最佳
  isKing(type_info, bonus_value) {
    let { total_num, binded_num, send_type, max_amount } = type_info
    if (send_type != 1) return false;
    if (parseInt(total_num) != parseInt(binded_num)) return false;
    if (parseInt(max_amount * 100) != parseInt(bonus_value * 100)) return false;
    return true
  },


  formatTime(time) {
    let d = new Date(time * 1000)
    let month = this.zero(d.getMonth() + 1)
    let date = this.zero(d.getDate())
    let h = this.zero(d.getHours())
    let m = this.zero(d.getMinutes())
    return `${month}-${date}  ${h}:${m}`
  },

  senderHead(relayer_id, sender_id, avatars) {
    let sender_head_src = '../../image/bonus/female.png'
    if (relayer_id > 0) {
      sender_head_src = avatars[relayer_id]['avatar']
    }
    else if (sender_id > 0) {
      sender_head_src = avatars[sender_id]['avatar']
    }

    return sender_head_src
  },
  receiveInfo(type_info) {
    let { total_num, binded_num } = type_info
    if (total_num == binded_num) {
      // 红包领完了
      let timestr = `${total_num}个红包,${this.bindedTime(type_info['binded_period'])}`
      return timestr
    }
    else {
      let timestr = `领取 ${binded_num}/${total_num}`
      let isEndTime = this.isEnd(type_info['send_end_date'])
      if (isEndTime == false) {
        timestr += '，点击右上角继续分享此红包'
      }
      return timestr
    }
  },
  isEnd(send_end_date) {
    let sendDate = parseInt(send_end_date)
    if (sendDate === 0) {
      return false
    }
    else {
      return new Date().getTime >= sendDate * 1000
    }
  },
  bindedTime(period) {
    let min = 60
    let hour = 3600
    let day = 24 * 3600

    let days = parseInt(period / day)
    period = period % day

    let hours = parseInt(period / hour)
    period = period % hour

    let mins = parseInt(period / min)
    period = period % min

    if (period > 0) {
      mins += 1
    }

    let timestr = ''
    if (days > 0) {
      timestr += `${days}天`
    }
    if (hours > 0) {
      timestr += `${hours}小时`
    }
    if (mins > 0) {
      timestr += `${mins}分钟`
    }
    timestr += '，领完'
    return timestr

  },


  countTime(params, send_start_date) {
    let times = parseInt(send_start_date - new Date().getTime() / 1000)
    if (times <= 0) {
      this.getDatas(params) // 活动时间到了，重新请求
      return
    }
    let h = Math.floor(times / 3600)
    h = this.zero(h)
    let m = Math.floor((times / 60) % 60)
    m = this.zero(m)
    let s = times % 60
    s = this.zero(s)
    let renderCount = [h.split(''), m.split(''), s.split('')]
    this.setData({
      renderCount
    })
    setTimeout(() => {
      this.countTime(params, send_start_date)
    }, 1000);

  },
  zero(n) {
    n = n >= 10 ? n.toString() : '0' + n
    return n
  },
  open() {
    this.setData({
      openAnimation: false
    })
    this.grab()
  },
  bindKeyInput(e) {
    let value = e.detail.value
    this.setData({
      input_msg: value
    })
  },
  message_tap(e) {
    let { flag } = e.currentTarget.dataset
    this.setData({
      message_flag: flag
    })
  },
  send_msg() {
    let self = this
    let result_msg = this.trim(this.data.input_msg)
    if (!result_msg) return;

    let params = {
      act: 'bonusex',
      op: 'comment',
      comment: result_msg,
      bonus_sn: this.data.mine_bonus['bonus_sn']
    }
    getReq(app,params, function (res) {
      if (res.code == 200) {
        self.setData({
          message_flag: false,
          result_msg
        })
      }
      else {
        wx.showToast({
          icon: 'none',
          title: 'error',
          duration: 2000
        })
        self.setData({
          message_flag: false,
          input_msg: ''
        })
      }
    }, 'POST')
  },
  trim(str) {
    str = str.replace(/\s+/g, "")
    return str
  },
  backHome: function () {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

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

  },

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

  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let imageUrl = '../../image/share_bonus.png'
    let { type_sn, relay_id } = this.data
    return {
      title: `点一下，你和TA都有红包！`,
      path: `/pages/shareBonus/shareBonus?type_sn=${type_sn}&relay_id=${relay_id}`,
      imageUrl: imageUrl
    }
  }
})