// pages/spellDetail/index.js
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px';
var config = require("../../../config/config.js");
const Http = require("../../../utils/HttpBasics");
const imgurl = require("../../../utils/imgurl");
const { spellStatus } = require("../../../utils/spell");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navigationBarHeight,
    tuanzhang: imgurl.tuanzhang.url,
    spellBg: imgurl.spellBg.url,
    position: imgurl.position.url,
    close03: imgurl.close03.url,
    home: imgurl.wmhome.url,
    paramData: null,
    data: null,
    showErr: false,
    showAlert: false,
    remainingPoints:0,
    submitAble:true,
    couponChannelDetail:null
  },
  getUserInfo: function () {
    let that = this;
    // 获取用户信息
    Http.get({
      url: config.api.getScore,
      data: {}
    })
      .then(res => {
        console.log(res)
        that.setData({
          remainingPoints: Number(res.data.credit) - Number(that.data.data.creditPrice),
          userInfo:res.data
        })
      })
  },
  cannotPay(){
    wx.showToast({
      title: "您的积分不足",
      image: './../../../assets/images/fail.png',
      duration: 2000,
      mask: false
    });
  },
  gotoIndex() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  gotoSearch() {
    wx.navigateTo({
      url: `/pages/spellGroup/spellGroup`,
    })
  },
  onShow:function(){
    this.setData({
      submitAble: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      paramData: options
    })
    this.getDetail(options.couponChannelId);

    // 关闭来自于左上角的分享
    wx.hideShareMenu()
  },
  /**
  * 发起支付
  */
  gotoPay() {
    var that = this;
    that.setData({
      submitAble: false
    })
    Http.get({
      url: config.api.checkPhoneStatus,
      data: {}
    })
      .then(res => {
        var data = {
          couponChannelId: "" + that.data.paramData.couponChannelId,
          couponId: "" + that.data.paramData.couponId
        }
        /**
         * orderSave 下单
         */
        return Http.post({
          url: config.api.orderSave,
          data: data
        });
      })
      .catch(err => {
        console.log(err);
        that.setData({
          submitAble: true
        })
        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.paramData.couponChannelId + "&couponId=" + that.data.paramData.couponId +"&path=jifen"
          });
        } else if (err.code == 11006) {
          // 用户手机已加密
          wx.redirectTo({
            url: "/pages/phoneinput/phoneinput?couponChannelId=" +
              that.data.paramData.couponChannelId + "&couponId=" + that.data.paramData.couponId + "&path=jifen"
          });
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })
      .then(res => {
        console.log(res)
        if (typeof (res) != "undefined") {
          let orderId = "" + res.data.mainOrderId;
          that.setData({
            orderId: orderId
          });
          console.log(that.data.type)
          // 免费券
          that.payOrderUpdate(orderId, "0", 1, '',that);
          // that.payOrderUpdate(that.data.orderId, '', 1, '', that);
          if (that.data.cardType == 100) {
            wx.setStorage({
              key: 'couponNum2',
              data: "couponNum2"
            })
          } else if (that.data.data.type != "5") {
            wx.setStorage({
              key: 'couponNum',
              data: "couponNum"
            })
          }
        }
      })
      
  },
  /**
   * 支付订单更新
   */
  payOrderUpdate: (orderId, payOrderId, status, reason, _this) => {
    let that = this;
    // 支付成功
    Http.post({
      url: config.api.payOrderUpdate,
      data: {
        payOrderId: payOrderId,
        composeOrderId: orderId,
        status: status,
        reason: reason
      }
    })
      .then(res => {
        wx.hideLoading()
        // 如果是停车券直接跳往停车页
        if (_this.couponChannelDetail.type == 51 ||_this.couponChannelDetail.type== 5) {
          wx.showModal({
            title: '兑换成功',
            cancelText: '我知道了',
            confirmText: '去使用',
            content: '即将前往停车页面',
            success(res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '/index/passCar'
                });
              }
            }
          })
        } else {
          wx.navigateTo({
            url: '/pages/integralmall/payIntegcouponStatus/index?title=' + _this.data.data.title + '&coverImg=' + _this.data.data.coverImg + '&remainingPoints=' + _this.data.remainingPoints + '&type=' + _this.data.data.type,
          })
        }
      })
      .catch(err => {
        if (err.code != 12002) {
          setTimeout(function () {
            _this.payOrderUpdate(orderId, payOrderId, status, reason, _this);
          }, 2000)
        }
      })
  },
  /**
   * 获取券详情信息
   */
  getDetail(couponChannelId) {
    let that = this;
    Http.get({
      url: config.api.couponDetail,
      data: {
        couponChannelId: couponChannelId
      }
    }).then(res => {
      that.couponChannelDetail=res.data
      console.log(that.couponChannelDetail.merchantVoList[0].merchantName,'that.couponChannelDetail');
      wx.stopPullDownRefresh();
      that.getUserInfo()
      let data = res.data;
      that.setData({
        data
      });
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getDetail(this.data.paramData.couponChannelId);
    this.setData({
      submitAble: true
    })
  },
})