|  | var config = require("../../../config/config.js");
var app = getApp();
const Http = require("../../../utils/HttpBasics");
const util = require("../../../utils/util");
const imgurl = require("../../../utils/imgurl");
Page({
  data: {
    fenxiangUrl: imgurl.fenxiang.url,
    clockUrl: imgurl.clock.url,
    teljpgUrl: imgurl.teljpg.url,
    closedUrl: imgurl.closed.url,
    quesGouUrl: imgurl.ques_gou.url,
    headbgUrl: imgurl.headbg.url,
    quesBgUrl: imgurl.ques_bg.url,
    close02: imgurl.close02.url,
    share01: imgurl.share01.url,
    fail: imgurl.fail.url,
    wmhome: imgurl.wmhome.url,
    swiperCurrent: 0,
    hidden: "hidden",
    height: "",
    detailPicture:[],
    coverPicture:[],
    more: "点击查看更多",
    showMore: true,
    data: {
      title: null
    },
    showPage: false,
    questions1: null,
    questions2: null,
    carList: [],
    couponChannelId: null,
    orderId: "",
    hour: null,
    day: null,
    month: null,
    year: null,
    minute: "",
    tempFilePaths: null,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    id: null,
    result: [],
    end_time: null,
    checked: false,
    questionnaire: {},
    questionId: null,
    widthScreen: null,
    moveData: null,
    rotateData: null,
    alphaData: null,
    scaleData: null,
    skewData: null,
    matrixData: null,
    opacity: 0,
    queueData: null,
    zIndex: 11,
    display: "none",
    showbutton: false,
    cardData: null,
    showCardOffer: false,
    isSamePeople: true,
    statusText: '',
    isReceived: false,
    receivedDisabled: false,
    clock: "结束",
    day: "00",
    hour: "00",
    min: "00",
    sec: "00",
    clock02: "00",
    day02: "00",
    hour02: "00",
    min02: "00",
    sec02: "00",
    countdown: "",
    showbutton1: false
  },
  /**
   * 跳转到门店列表的详情页面
   */
  gotoDetail(e) {
    wx.navigateTo({
      url: `/pages/index/detail/index?id=${e.currentTarget.dataset.id}`
    })
  },
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    });
  },
  phone: function(e) {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: e.target.dataset.merchantlinkphone
    });
  },
  // 点击查看更多
  more: function() {
    let that = this;
    if (that.data.more == '点击查看更多') {
      this.setData({
        hidden: "",
        height: that.data.data.merchantVoList.length * 140 + 'rpx',
        more: "点击收起",
        showMore: true
      })
    } else {
      this.setData({
        hidden: "hidden",
        height: 4 * 140 + 'rpx',
        more: "点击查看更多",
        showMore: true
      })
    }
  },
  //获取当前登录用户信息
  getUserInfo: function() {
    let that = this;
    // 获取用户信息
    Http.get({
        url: config.api.getScore,
        data: {}
      })
      .then(res => {
        console.log(res)
        that.getQueryCardStatus()
        if (that.data.cardData.cuserId != res.data.id) {
          console.log(2222, 6666)
          that.setData({
            isSamePeople: false
          })
        }
      })
  },
  //获取卡转赠状态
  getQueryCardStatus() {
    let that = this;
    let param = {
      id: this.data.cardData.couponOrderId,
      cUserId: this.data.cardData.cuserId,
      updateDate: util.formatTime(Number(that.data.cardData.updateDate), "yyyy-MM-dd hh:mm:ss")
    }
    Http.get({
        url: config.api.queryCardStatus,
        data: param
      })
      .then(res => {
        console.log(res, 333333333333)
      })
      .catch(err => {
        that.setData({
          isReceived: true,
          statusText: err.message
        })
      })
  },
  receiveCard() {
    let that = this;
    let param = {
      id: this.data.cardData.couponOrderId,
      cUserId: this.data.cardData.cuserId,
      updateDate: util.formatTime(Number(this.data.cardData.updateDate), "yyyy-MM-dd hh:mm:ss")
    }
    this.setData({
      receivedDisabled: true
    })
    Http.post({
        url: config.api.cardAccept,
        data: param
      })
      .then(res => {
        wx.showToast({
          title: '领取成功!',
          icon: 'none',
          duration: 2000,
          mask: false
        });
        wx.reLaunch({
          url: '/pages/complete/index?couponOrderId=' + this.data.cardData.couponOrderId,
        })
      })
      .catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
        that.setData({
          receivedDisabled: false
        })
      })
  },
  closeAlert() {
    this.setData({
      showCardOffer: false
    })
  },
  goback: function() {
    wx.switchTab({
      url: '/pages/main/index',
    })
  },
  /**
   * 点击提交问题单选
   */
  formSubmit: function(e) {
    console.log(e);
    let that = this;
    /**
     * 多选
     */
    if (e.currentTarget.dataset.flags == 'multi') {
      if (that.data.anwserId.length == 0) {
        var answserIs = null
      } else {
        var answserIs = that.data.anwserId.join(",");
      }
    } else if (e.currentTarget.dataset.flags == 'single') {
      var answserIs = e.detail.value;
    }
    console.log(answserIs)
    console.log(e.currentTarget.dataset.questionid)
    Http.post({
        url: config.api.answerQuestion,
        data: {
          answer: answserIs,
          questionId: e.currentTarget.dataset.questionid
        }
      })
      .then(res => {
        that.closeQuestion();
      })
      .catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },
  /**
   * 多选
   */
  checkboxChange: function(e) {
    console.log(e)
    this.setData({
      anwserId: e.detail.value
    })
  },
  closeQuestion: function() {
    let that = this;
    that.setData({
      display: "none",
      zIndex: 11,
      opacity: 0
    })
    setTimeout(function() {
      that.orderFunc();
    }, 500)
  },
  gotopay: function(e) {
    let that = this;
    wx.showLoading({
      title: '',
    })
    if (e.currentTarget.dataset.type == 51 || e.currentTarget.dataset.type == 50){
      wx.navigateTo({
        url: '/pages/integralmall/payIntegcoupondetail/index?couponChannelId=' + that.data.couponChannelId + '&couponId=' + that.data.couponId,
      })
    }else{
      let formId = e.detail.formId;
      var discount = e.currentTarget.dataset.discount;
      that.setData({
        queueData: null,
        showbutton: true,
        formId: formId
      })
      Http.get({
        url: config.api.getQuestion,
        data: {
          couponType: JSON.stringify(that.data.data.type)
        }
      })
      .then(res => {
        wx.hideLoading();
        if (res.data == undefined) {
          that.orderFunc(discount);
          that.setData({
            flag: false
          })
        } else if (res.data) {
          var animation = wx.createAnimation({});
          animation.translate((that.data.widthScreen - that.data.widthScreen), 0).scale(1).opacity(1).step({
            duration: 500
          })
          that.setData({
            queueData: animation.export(),
            zIndex: 9,
            opacity: 1,
            display: "block",
            questionnaire: JSON.parse(res.data.content),
            questionId: res.data.id
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
    }
  },
  setIntervalTime(end_time) {
    let that = this;
    var EndTime = end_time;
    var NowTime = new Date().getTime();
    var total_micro_second = EndTime - NowTime || [];
    // 渲染倒计时时钟
    let obj = that.dateformat(total_micro_second);
    if (total_micro_second > 0) {
      that.setData({
        clock: obj,
        day: obj.a1,
        hour: obj.b1,
        min: obj.c1,
        sec: obj.d1,
      })
    } else {
      that.setData({
        clock: "00",
        day: "00",
        hour: "00",
        min: "00",
        sec: "00",
      })
      //如果倒计时结束,需要重新查询一下券的状态
      // 给getDetail一个标识 
      that.getDetail(that.data.couponChannelId, 'endclock');
    }
    total_micro_second -= 1000;
  },
  countdown: function(end_time) {
    let that = this;
    that.setIntervalTime(end_time);
    that.data.setInterval = setInterval(function() {
      that.setIntervalTime(end_time);
    }, 1000)
  },
  // 时间格式化输出,如11:03 25:19 每1s都会调用一次
  dateformat(micro_second) {
    // 总秒数
    var second = Math.floor(micro_second / 1000);
    // 天数
    var day = Math.floor(second / 3600 / 24) < 10 ? "0" + Math.floor(second / 3600 / 24) : Math.floor(second / 3600 / 24);
    // 小时
    var hr = Math.floor(second / 3600 % 24) < 10 ? "0" + Math.floor(second / 3600 % 24) : Math.floor(second / 3600 % 24);
    // 分钟
    var min = Math.floor(second / 60 % 60) < 10 ? "0" + Math.floor(second / 60 % 60) : Math.floor(second / 60 % 60);
    // 秒
    var sec = Math.floor(second % 60) < 10 ? "0" + Math.floor(second % 60) : Math.floor(second % 60);
    // return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
    return {
      a1: day,
      b1: hr,
      c1: min,
      d1: sec
    }
  },
  /**
   * 获取用户信息
   */
  onLoad(options) {
    let that = this;
    wx.showLoading({
      title: "加载中..."
    });
    that.setData({
      onshow: false
    })
    if (options && options.couponChannelId){
      that.getDetail(options.couponChannelId, 'notendclock');
    }
    /**
     * 转赠判断
     */
    if (options.cuserId) {
      this.setData({
        showCardOffer: true,
        cardData: options
      })
      this.getUserInfo()
    }
    that.setData({
      couponChannelId: options.couponChannelId,
      title: that.data.data.title ? that.data.data.title : '',
    });
    if (options.cardType) {
      that.setData({
        cardType: options.cardType
      })
    }
  },
  getDetail: function(couponChannelId, flag) {
    let that = this;
    var parmer = {
      url: config.api.couponDetail,
      data: {
        couponChannelId: couponChannelId
      }
    };
    Http.get(parmer)
      .then(res => {
        that.setData({
          couponId: res.data.couponId
        })
        that.setData({
          showPage: true
        })
        if (res && res.data && res.data.detailPicture) {
          that.setData({
            detailPicture: JSON.parse(res.data.detailPicture)
          })
        }
        if (res && res.data && res.data.coverPicture) {
          that.setData({
            coverPicture: JSON.parse(res.data.coverPicture)
          })
        }
        /**
         * 将优惠券优惠卡的详情的BarTitle
         * 设置成券的名称
         */
        wx.setNavigationBarTitle({
          title: res.data.title
        })
        var EndTime = res.data.validStartDate;
        var NowTime = new Date().getTime();
        /**
         * activityStatus==0 活动未开始
         * activityStatus==1 活动已开始
         * flag == endclock 说明倒计时已经结束
         */
        if (res.data.endTime && res.data.beginTime) {
          that.setData({
            begin_time: res.data.beginTime,
            end_time: res.data.endTime,
          })
          if (res.data.activityStatus == 0 && flag != 'endclock') {
            that.countdown(res.data.beginTime);
          } else if (res.data.activityStatus != 0 && flag != 'endclock') {
            that.countdown(res.data.endTime);
          } else {
            clearInterval(that.data.setInterval)
          }
          if (res.data.activityStatus == 0) {
            var beginTime = util.formatTime(res.data.beginTime, "yyyy-MM-dd hh:mm:ss");
            if (util.timechuo(beginTime).indexOf('-') == 0) {
              that.setData({
                beginTime: "活动已结束",
              });
            } else {
              that.setData({
                beginTime: util.timechuo(beginTime)
              });
            }
          } else {
            var endTime = util.formatTime(res.data.endTime, "yyyy-MM-dd hh:mm:ss");
            if (util.timechuo(endTime).indexOf('-') == 0) {
              that.setData({
                endtime: "活动已结束",
              });
            } else {
              that.setData({
                endtime: util.timechuo(endTime)
              });
            }
          }
        }
        wx.hideLoading();
        that.setData({
          data: res.data
        });
        if (that.data.data.merchantVoList && that.data.data.merchantVoList.length <= 4) {
          that.setData({
            height: that.data.data.merchantVoList.length * 140 + 'rpx',
            showMore: false
          })
        } else if (that.data.data.merchantVoList && that.data.data.merchantVoList.length > 4) {
          that.setData({
            height: 4 * 140 + 'rpx'
          })
        }
        if (res.data.validType == 1) {
          that.setData({
            validStartDate: util.formatTime(res.data.validStartDate, "yyyy-MM-dd"),
            validEndDate: util.formatTime(res.data.validEndDate, "yyyy-MM-dd"),
          });
        } else {
          if (res.data.validDays) {
            that.setData({
              validDays: res.data.validDays
            });
          }
        }
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },
  /**
   * 邀请好友继续砍价
   */
  inviteFriend: function() {
    let that = this;
    that.orderFunc("discount");
    that.setData({
      showbutton1: true
    })
  },
  /**
   * 支付订单更新
   */
  payOrderUpdate: (orderId, payOrderId, status, reason, type, _this) => {
    let that = this;
    // 支付成功
    Http.post({
        url: config.api.payOrderUpdate,
        data: {
          payOrderId: payOrderId,
          orderId: orderId,
          status: status,
          reason: reason
        }
      })
      .then(res => {
        wx.hideLoading()
        // 有价券
        if (!type && type != 'free') {
          wx.navigateTo({
            url: `/pages/order/detail/index?orderId=${
              orderId
              }&cardIf=true`
          });
        } else if (type == 'free') {
          wx.navigateTo({
            url: `/pages/order/detail/index?orderId=${
              orderId
              }`
          });
        }
      })
      .catch(err => {
        console.log(err);
        if (!type) {
          setTimeout(function() {
            _this.payOrderUpdate(orderId, payOrderId, status, reason, type, _this);
          }, 2000)
        }
      })
  },
  checkPhoneStatus: function() {
    let that = this;
    Http.get({
        url: config.api.checkPhoneStatus,
        data: {}
      })
      .then(res => {
        console.log(666, '授权成功!')
        that.receiveCard()
      })
      .catch(err => {
        if (err.code == 11005) {
          /**
           * 手机号没有授权,将值传到用户手机号授权的页面
           *
           */
          wx.redirectTo({
            url: "/pages/getphoneInfo/index?path=index&cuserId=" + that.data.cardData.cuserId + "&couponChannelId=" + that.data.cardData.couponChannelId + "&userName=" + that.data.cardData.userName + "&coverImg=" + that.data.cardData.coverImg + "&avatarUrl=" + that.data.cardData.avatarUrl + "&couponOrderId=" + that.data.cardData.couponOrderId + "&updateDate=" + that.data.cardData.updateDate,
          });
        } else if (err.code == 11006) {
          // 用户手机已加密
          wx.redirectTo({
            url: "/pages/phoneinput/phoneinput?path=index&cuserId=" + that.data.cardData.cuserId + "&couponChannelId=" + that.data.cardData.couponChannelId + "&userName=" + that.data.cardData.userName + "&coverImg=" + that.data.cardData.coverImg + "&avatarUrl=" + that.data.cardData.avatarUrl + "&couponOrderId=" + that.data.cardData.couponOrderId + "&updateDate=" + that.data.cardData.updateDate,
          });
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })
  },
  /**
   * 发起支付
   */
  orderFunc(discount) {
    let that = this;
    Http.get({
        url: config.api.checkPhoneStatus,
        data: {}
      })
      .then(res => {
        if (discount == 'discount') {
          var data = {
            couponChannelId: "" + that.data.couponChannelId,
            couponId: "" + that.data.couponId,
            formId: "" + that.data.formId,
            press: true
          }
        } else if (discount == 'discount1') {
          var data = {
            couponChannelId: "" + that.data.couponChannelId,
            couponId: "" + that.data.couponId,
            formId: "" + that.data.formId,
            press: false
          }
        } else if (that.data.couponChannelId == null) {
          var data = {
            couponId: "" + that.data.couponId,
            formId: "" + that.data.formId,
          };
        } else {
          var data = {
            couponChannelId: "" + that.data.couponChannelId,
            couponId: "" + that.data.couponId,
            formId: "" + that.data.formId,
          }
        }
        /**
         * orderSave 下单
         */
        return Http.post({
          url: config.api.orderSave,
          data: data
        });
      })
      .catch(err => {
        wx.hideLoading()
        that.setData({
          showbutton: false,
          showbutton1: false
        })
        if (err.code == 2011) {
          wx.showToast({
            title: "商户信息没找到",
            image: './../../../assets/images/fail.png',
            duration: 2000,
            mask: false
          });
        } else if (err.code == 2013) {
          wx.showToast({
            title: "商户信息禁用",
            image: './../../../assets/images/fail.png',
            duration: 2000,
            mask: false
          });
        } else if (err.code == 3000) {
          wx.showToast({
            title: "库存不足",
            image: './../../../assets/images/fail.png',
            duration: 2000,
            mask: false
          });
        } else if (err.code == 3001) {
          wx.showToast({
            title: "您已超过限购",
            image: './../../../assets/images/fail.png',
            duration: 2000,
            mask: false
          });
        } else if (err.code == 3002) {
          wx.showToast({
            title: "订单失败",
            image: './../../../assets/images/fail.png',
            duration: 2000,
            mask: false
          });
        } else if (err.code == 3003) {
          wx.showToast({
            title: "订单不存在",
            image: './../../../assets/images/fail.png',
            duration: 2000,
            mask: false
          });
        } else if (err.code == 3004) {
          wx.showToast({
            title: "订单不存在",
            image: './../../../assets/images/fail.png',
            duration: 2000,
            mask: false
          });
        } else if (err.code == 4003) {
          wx.showToast({
            title: "卡券已作废",
            image: './../../../assets/images/fail.png',
            duration: 2000,
            mask: false
          });
        } else if (err.code == 3012) {
          wx.showModal({
            title: '提示',
            content: '您有未支付订单,请先进行支付',
            confirmText:"去支付",
            success: function (res) {
              console.log(res.confirm)
              if(res.confirm){
                wx.navigateTo({
                  url: '/pages/order/index/index?id=all',
                })
              }
            }
          })
        } else if (err.code == 11005) {
          /**
           * 将值传到用户手机号授权的页面
           *
           */
          wx.redirectTo({
            url: "/pages/getphoneInfo/index?couponChannelId=" +
              that.data.couponChannelId
          });
        } else if (err.code == 11006) {
          // 用户手机已加密
          wx.redirectTo({
            url: "/pages/phoneinput/phoneinput?couponChannelId=" +
              that.data.couponChannelId
          });
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })
      .then(res => {
        if (discount != 'discount') {
          if (typeof(res) != "undefined") {
            let orderId = "" + res.data.id;
            that.setData({
              orderId: orderId
            });
            if (res.data.payment > 0) {
              // 支付金额不为0
              /**
               * 支付订单创建
               */
              Http.post({
                  url: config.api.payOrderCreate,
                  data: {
                    orderId: orderId
                  }
                })
                .then(res => {
                  var payOrderId = "" + res.data.payOrderId;
                  wx.hideLoading();
                  wx.requestPayment({
                    timeStamp: res.data.timeStamp,
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    signType: (res.data.signType) ? res.data.signType : "MD5",
                    paySign: res.data.paySign,
                    success: res => {
                      wx.showLoading({
                        title: '订单正在处理中...',
                      })
                      setTimeout(function() {
                        wx.hideLoading()
                      }, 5000)
                      that.payOrderUpdate(that.data.orderId, payOrderId, 1, '', '', that);
                      if (res.errMsg == "requestPayment:ok") {
                        setTimeout(function() {
                          wx.hideLoading();
                        }, 2000);
                        /**
                         * 用户支付成功以后跳转到券包列表
                         */
                        if (that.data.cardType == 100) {
                          wx.setStorage({
                            key: 'couponNum2',
                            data: "couponNum2"
                          })
                        } else if (that.data.data.type != 5 && that.data.cardType != 100) {
                          wx.setStorage({
                            key: 'couponNum',
                            data: "couponNum"
                          })
                        }
                      }
                    },
                    fail: res => {
                      wx.hideLoading();
                      /**
                       * 支付失败,需要更新订单的状态
                       */
                      that.payOrderUpdate(that.data.orderId, payOrderId, 2, '', 'fail', that);
                      that.setData({
                        showbutton: false
                      })
                      return;
                    },
                    complete: res => {}
                  });
                  /// End payment  --------
                })
                .catch(err => {
                  wx.hideLoading();
                  wx.showToast({
                    title: err.message,
                    icon: 'none',
                    duration: 2000,
                    mask: false
                  });
                })
            } else {
              // 免费券
              that.payOrderUpdate(orderId, "0", 1, '', 'free');
              if (that.data.cardType == 100) {
                wx.setStorage({
                  key: 'couponNum2',
                  data: "couponNum2"
                })
              } else if (that.data.data.type != "5" && that.data.cardType != 100) {
                wx.setStorage({
                  key: 'couponNum',
                  data: "couponNum"
                })
              }
            }
          }
        } else {
          if (res) {
            wx.navigateTo({
              url: `/pages/bargain/bargainDatail/bargainDatail?orderId=${res.data.id}`,
            })
          }
        }
      })
  },
  onShow() {
    this.setData({
      showbutton: false,
      showbutton1: false
    })
    if (this.data.end_time) {
      this.countdown(this.data.end_time)
    }
  },
  onUnload: function() {
    let that = this;
    clearInterval(that.data.setInterval)
  },
  onHide: function() {
    let that = this;
    clearInterval(that.data.setInterval)
  },
  onShareAppMessage: function(options) {
    var that = this;
    console.log(options)
    var shareObj = {
      title: that.data.data.title,
      path: `/pages/index/index?couponChannelId=${that.data.couponChannelId}`,
      success: function(res) {
        if (res.errMsg == 'shareAppMessage:ok') {}
      },
      fail: function(error) {
        if (res.errMsg == 'shareAppMessage:fail cancel') {} else if (res.errMsg == 'shareAppMessage:fail') {}
      }
    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset.id;
      shareObj.path = `/pages/index/index?couponChannelId=${eData}`;
    }
    // 返回shareObj
    return shareObj;
  },
  // 下拉刷新
  onPullDownRefresh: function() {
    this.getDetail(this.data.couponChannelId);
    wx.stopPullDownRefresh()
  }
});
 |