// 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,
    donate : false,
    donateImgUrl : '',
    showDonateImgUrl : false,
    showTempalteModal : false,
    userHasBaseInfo : false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.id = options.id;
    if(!this.data.id){
      wx.showToast({
        title: '进入页面参数不对',
        icon : 'none'
      });
      return ;
    }
  },

  //弹出订阅莫泰关闭
  onTapCloseModalTemplate(){
    this.setData({
      showTempalteModal : false
    });
  },

  //确认弹出订阅消息框
  onTapSureSubTemplate(e){
    //
    this.setData({
      showTempalteModal : false
    });
    let activityId = this.data.id;
    //查询订阅模板
    let baseUserInfo = wx.getStorageSync('_baseUserInfo');
    wxService.post(`${'/merchant/message/wxSubMsgMapping/getListByParams'}`, {
      scenarioIds: ['pcstart', 'pccomplete'],
      sourceFrom: 2,
      switchType: 3
    }).then(res => {
      let tempArr = res.data.data ? res.data.data : [];
      let tempids = [];
      if(tempArr.length == 0){
        return ;
      }

      tempArr.map(item => {
        tempids.push(item.templateId);
      });
      let promiseArr = []
      wx.requestSubscribeMessage({
        tmplIds: tempids,
        success: (res) => {
          for (let i = 0; i < tempArr.length; i++) {
            let tempPromise = wxService.post(`${'/merchant/message/wxSubMsgSubscride/member/subscribe'}`, {
              businessId: activityId,
              memberId: baseUserInfo.memberId,
              scenarioId: tempArr[i].scenarioId,
              templateId: tempArr[i].templateId
            });

            promiseArr.push(tempPromise);
          }
        }
      });

      Promise.all(promiseArr).then(promiseArr => {
        wx.showToast({
          title: '订阅成功',
        });
      })
    });
  },

  //  集点详情
  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();
          const baseUserInfo = wx.getStorageSync('_baseUserInfo');
          if(baseUserInfo){
            let isUat = data.isUat;
            if(isUat == 'y'){
              let isTrial = baseUserInfo.member.trial ? baseUserInfo.member.trial : false;
              if(!isTrial){
                wx.redirectTo({
                  url: '/subPackage/page/pages/goToHome/goToHome',
                });
              }
            }
          }

          let dialog = data.dialog ? data.dialog : {};
          dialog.show = false
          // 弹框背景
          dialog.image = data.popupImage
          this.data.donateImgUrl = data.donateImgUrl ? data.donateImgUrl : 'https://img3.bigaka.com/test/1001/202005/20200517/10010c6f71af-479e-4663-adde-00f64c1fb941.png';
          // 是否在有效期
          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.data.donate = data.donate == 1  ? true : false;

          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,
            donateImgUrl : this.data.donateImgUrl,
          }, () => {
            // 1 进行中 2 已结束
            if (timeFlag == 2) {
              this.showTimeStatus('活动已经结束啦')
            } else if (data.status == 3) {
              // 活动状态  1 未生效 2 生效中 3 已失效 0 已删除
              this.showTimeStatus('活动已经失效啦，看看其他的')
            } else {
              // 会员集点活动统计信息 进行中且有效
              this.getPointConsumptionCount(id);
              //限制必须是扫码进来的才调用
              if(this.data.donate){
                this.getUserShowRewardCollectionPoint(id);
              }
            }
          })
        }
      }
    });

    this.showOrHideTemplateModal(id);
  },
  //获取用户扫码进来是否需要弹出领取集点的
  getUserShowRewardCollectionPoint(id){
    wxService.post(`/sale/touchpoints/pointConsumptionActivity/verifyWhetherReward?id=${id}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          //如果需要 弹出提示框
          if(data == 1){
            this.showConfirmModal(id);
          }
        }
      }
    })
  },
  //弹出原生提示框让用户去点击
  showConfirmModal(id){
    //先判断是否已经弹出服务通知了
    let self = this;
    if(this.showModal){
      return ;
    }

    this.showModal = true;
    this.setData({
      showDonateImgUrl : true,
    })
  },

  //图片的点击事件
  onDialogTap(e){
    //这里先去判断用户是否开卡
    const { member } = wx.getStorageSync('_baseUserInfo');
    if(!member){
      wx.showToast({
        title: '请先去登录',
        icon : 'none'
      })
      return ;
    }

    //判断是否开卡
    if(!member.cardNoWeixin){
      wx.showToast({
        title: '请先开卡后购买',
        icon : 'none'
      });

      wxService.openCard()
      return ;
    }

    this.setData({
      showDonateImgUrl :false
    });

    this.userConfirmGetCollectionPoint(this.data.id);
  },

  //调用领取接口
  userConfirmGetCollectionPoint(id){
    wxService.post(`/sale/touchpoints/pointConsumptionActivity/award?id=${id}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          //如果需要 弹出提示框
          wx.showToast({
            title: '领取成功~',
          });
          
          this.getPointDetail(this.data.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 () {

  },

  ////授权订阅消息的弹出框一天弹出一次
  showOrHideTemplateModal(activityId){
    if(this.todayHasGot(activityId)){
      return ;
    }
    else{
      this.setData({
        showTempalteModal : true
      });
      this.setLocalStorageByKey(activityId); 
    }
  },

  //设置每天只能领取一次限制
  setLocalStorageByKey(activityId){
    let getCouponData = wx.getStorageSync('userHasSubActivity');
    let key = `${activityId}_d_${this.getCurrentYearMonDay()}`;
    if(!getCouponData){
      getCouponData = {};
      getCouponData[key] = true;
      wx.setStorageSync('userHasSubActivity',getCouponData);
    }
    else{
      //先设置进去
      getCouponData[key] = true;
      
      //获取今天的当前也的key
      let expiredAllKey = [];
      for(let k in getCouponData){
        let expiredKey = k.split('_d_')[1];
        if(parseInt(expiredKey) < parseInt(this.getCurrentYearMonDay())){
          expiredAllKey.push(k);
        }
      }
      //移除今天一起的过期key
      expiredAllKey.forEach(item => {
        delete getCouponData[item];
      });

      wx.setStorageSync('userHasSubActivity',getCouponData);
    }
  },

  //是否已经领取了
  todayHasGot(activityId){
    let getCouponData = wx.getStorageSync('userHasSubActivity');
    let key = `${activityId}_d_${this.getCurrentYearMonDay()}`;
    if(!getCouponData){
      return false;
    }

    if(getCouponData[key]){
      return true
    }

    return false;
  },

  //获取当前年月日
  getCurrentYearMonDay(){
    let da = new Date();
    return `${da.getFullYear()}${da.getMonth()}${da.getDate()}`;
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const baseUserInfo = wx.getStorageSync('_baseUserInfo')
    if(!baseUserInfo){
      this.setData({
        isAuthorization: true
      });
      
      return;
    }

    this.getPointDetail(this.data.id);
  },


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

  }
})