// pages/pointDetail/pointDetail.js
const app = getApp()
const wxService = require('../../utils/wxService')
const utils = require('../../utils/util')
// import * as watch from "../../utils/watch.js";
import { Integer } from '../../utils/integerDigitalConvertion'

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    imgHeight: 450,
    dialog: {
      show: false,
      image: '../../assets/imgs/point/bgc.png',
      content: '优惠券和积分流水',
      tip: '立即查看'
    },
    desc: [],
    activityId: '',
    type: 0, // 0 不显示 1 显示
    popupType: 0, // 默认不跳转  1 优惠券 2 积分
    goal: 0,
    iconImage: '',
    iconImageFinsh: '',
    detailImage: '',
    countObj: {
      surplusPoints: 0,
      exchangeCount: 0,
      totalPoints: 0,
      surplusExchangeCount: 0
    },
    currentPercent: 0, // 当前进度
    isDisabled: false,
    hideGetBtn: true, // 默认隐藏 可领取按钮
    showGetBtn: true, // 默认展示 未达成按钮
    currentStatus: 2, // 活动状态  1 未生效 2 生效中 3 已失效 0 已删除
    currentTimeStatus: 1, // 1 进行中 2 已结束 3 未开始
    isAuthorization: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
  },
  watch: {
    experAccessible(newVal, oldVal) {
      // 登录接口返回err
      const reLoginErrFlag = wx.getStorageSync('reLoginErr')
      const baseUserInfo = wx.getStorageSync('_baseUserInfo')
      let id
      if (baseUserInfo && !reLoginErrFlag) {
        this.setData({
          isAuthorization: false
        }, () => {
          const option = this.options || {}
          const { scene } = option
          if (scene) {
            let idParam = decodeURIComponent(scene).split('&')[0]
            let shareId = idParam && idParam.split('=')[1] || 0
            if(shareId.length < 12){
              id = Integer.digit(shareId, 64, 10)
            }else{
              id = shareId
            }
          } else {
            id = option.id
          }

          if (id) {
            this.setData({
              id
            }, () => {
              if(newVal) {
                this.getPointDetail(id)
              } else {
                // 去别的页面 
                wxService.router(`/subPackage/page/pages/goToHome/goToHome`).replace()
              }
              // this.getPointDetail(id)
            })
          }
          // 隐藏 dialog
          this.isShowDialog(false)
        })
      }
      else if (!baseUserInfo && reLoginErrFlag) {
        this.setData({
          isAuthorization: true
        })
      }
      else {
        this.setData({
          isAuthorization: true
        })
      }
    }
  },
  //  集点详情
  getPointDetail(id) {
    wx.showLoading({
      title: '加载中'
    })
    wxService.get(`/sale/touchpoints/pointConsumptionActivity/findById/${id}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          let dialog = this.data.dialog
          dialog.show = false
          // 弹框背景
          dialog.image = data.popupImage
          // 是否在有效期
          let timeFlag = 1
          let endT = data.endTime
          let startT = data.startTime
          let currentEndTime = (new Date(endT.replace(/-/g, '/'))).getTime();
          let currentstartTime = (new Date(startT.replace(/-/g, '/'))).getTime();
          let currentTime = (new Date()).getTime();
          // 开始时间 小于 现在  && 小于 结束时间 进行中
          if (currentstartTime < currentTime && currentTime < currentEndTime) {
            timeFlag = 1
          } else if (currentEndTime < currentTime) {
            // 结束时间 小于 现在时间 已结束
            timeFlag = 2
          } else if (currentTime < currentstartTime) {
            // 未开始
            timeFlag = 3
          }
          this.setData({
            activityId: data.id,
            type: data.showActivitys,
            currentStatus: data.status,
            popupType: data.popupType,
            goal: data.goal,
            iconImage: data.iconImage,
            iconImageFinsh: data.iconImageFinsh,
            desc: JSON.parse(data.content),
            detailImage: data.detailImage,
            dialog,
            currentTimeStatus: timeFlag
          }, () => {
            // 1 进行中 2 已结束
            if (timeFlag == 2) {
              this.showTimeStatus('活动已经结束啦')
            } else if (data.status == 3) {
              // 活动状态  1 未生效 2 生效中 3 已失效 0 已删除
              this.showTimeStatus('活动已经失效啦，看看其他的')
            } else {
              // 会员集点活动统计信息 进行中且有效
              this.getPointConsumptionCount(id)
            }
          })
        }
      }
    })
  },
  showTimeStatus(status) {
    wx.showToast({
      title: `${status}`,
      icon: 'none'
    })
  },
  // 会员集点活动统计信息
  getPointConsumptionCount(activityId) {
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    wx.showLoading({
      title: '加载中'
    })
    wxService.post(`/sale/touchpoints/pointConsumptionCount/getPointConsumptionCount?activityId=${activityId}&memberId=${memberId}`).then(res => {
      if (res) {
        const { result, data } = res.data
        // percent
        let newPercent = 0
        let hasNum = data.surplusExchangeCount
        let totalPoints = data.totalPoints
        let goal = this.data.goal
        if (hasNum) {
          if (parseInt(totalPoints % goal) == 0) {
            newPercent = goal
          } else {
            if (totalPoints) {
              newPercent = totalPoints % goal
            } else {
              newPercent = 0
            }
          }
        } else {
          if (totalPoints) {
            newPercent = totalPoints % goal
          } else {
            newPercent = 0
          }
        }

        if (result == 0) {
          this.setData({
            countObj: data,
            currentPercent: 100 / (this.data.goal / newPercent),
            surplusExchangeCount: data.surplusExchangeCount,
            hideGetBtn: hasNum ? false : true,
            showGetBtn: hasNum ? true : false,
          }, () => {
            wx.hideLoading()
          })
        }
      }
    })
  },
  handleCheckGoods() {
    const { activityId } = this.data
    wxService.router(`/subPackage/page/pages/pointGoodsList/pointGoodsList`).search({ activityId })
  },
  _closeDialog() {
    const { id } = this.data
    if (id) this.getPointDetail(id)
  },
  handleGo() {
    // 跳转  popupType: 0  默认不跳转  1 优惠券 2 积分
    const { popupType, id } = this.data
    if (popupType == 1) {
      wxService.router(`/pages/coupons/coupons`)
    } else if (popupType == 2) {
      wxService.router(`/pages/integralWater/integralWater`)
    } else {
      // 隐藏 dialog
      this.isShowDialog(false)
      // 获取最新数据
      this.getPointDetail(id)
    }
  },
  //  触点有礼-消费集点兑换
  getPointExchange() {
    const { activityId } = this.data
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    wx.showLoading({
      title: '加载中'
    })
    wxService.get(`/sale/touchpoints/pointConsumptionExchange/exchange?activityId=${activityId}&memberId=${memberId}`).then(res => {
      if (res) {
        const { result, data } = res.data
        const { popupType, id } = this.data
        if (result == 0) {
          wx.hideLoading()
          // 显示 dialog
          this.isShowDialog(true)
          // popupType == 0 3s 关闭
          if (popupType == 0) {
            setTimeout(() => {
              this.isShowDialog(false)
              this.getPointDetail(id)
            }, 3000)
          }
        }
      }
    })
  },
  isShowDialog(flag) {
    let dialog = this.data.dialog
    dialog.show = flag
    this.setData({
      dialog
    })
  },
  handleToGet() {
    // 按钮防止短时间多次点击
    const { countObj } = this.data
    if (countObj.surplusExchangeCount) {
      this.getPointExchange()
    }
    this.setData({
      isDisabled: true
    })
    setTimeout(() => {
      this.setData({
        isDisabled: false
      })
    }, 3000)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

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

  },

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

  },

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

  },

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

  },

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

  }
})