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

  /**
   * 页面的初始数据
   */
  data: {
    navigationBarHeight,
    blueImg: imgurl.blue.url,
    tuanzhang: imgurl.tuanzhang.url,
    spellBg: imgurl.spellBg.url,
    position: imgurl.position.url,
    close03: imgurl.close03.url,
    home: imgurl.wmhome.url,
    orderGroupFail: imgurl.orderGroupFail.url,
    paramData: null,
    data: null,
    clock: "00",
    day: "0",
    hour: "00",
    min: "00",
    sec: "00",
    spellStatusList: spellStatus,
    isMyself: false,
    showErr: false,
    showAlert: false,
    disabled: false
  },
  gotoAgain() {
    let data = this.data.data;
    wx.navigateTo({
      url: `/pages/spellGroup/mySpellGroup/index?couponId=${data.couponId}&couponChannelId=${data.couponChannelId}`,
    })
  },
  getUserInfo: function() {
    let that = this;
    // 获取用户信息
    Http.get({
        url: config.api.getScore,
        data: {}
      })
      .then(res => {
        console.log(res)
        that.setData({
          nickName: res.data.nickName,
          avatarUrl: res.data.avatarUrl
        })
      })
  },
  gotoIndex() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  gotoSearch() {
    wx.navigateTo({
      url: `/pages/spellGroup/spellGroup`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    Http.get({
      url: config.api.checkUserStatus,
      data: {
        token: app.globalData.token
      }
    }).then(res => {
      Http.get({
        url: config.api.checkPhoneStatus,
        data: {}
      }).then(res => {
        this.setData({
          paramData: options
        })
        this.getUserInfo();
        if (options.orderGroupId) {
          if (options.orderId && options.couponId) {
            this.getDetail(options);
          }
        }
        // 关闭来自于左上角的分享
        wx.hideShareMenu()
      }).catch(res => {
        wx.redirectTo({
          url: `/pages/getphoneInfo/index`
        });
      })
    }).catch(res => {
      wx.redirectTo({
        url: `/pages/getuserinfo/index`
      })
    })
  },
  /**
   * 去拼团
   */
  goToOrderGroup(orderId, orderGroupId, _this) {
    console.log(22222222)
    let that = this;
    // 支付成功
    Http.post({
        url: config.api.toOrderGroup,
        data: {
          id: orderGroupId,
          orderId,
          couponId: _this.data.data.couponId
        }
      })
      .then(res => {
        wx.redirectTo({
          url: `/pages/spellDetail/index?orderId=${orderId}&couponId=${_this.data.paramData.couponId}&orderGroupId=${res.data.orderGroupId}&couponChannelId=${_this.data.paramData.couponChannelId}`
        });
      })
      .catch(err => {
        console.log(err);
      })
    // return;
  },
  /**
   * 支付订单更新
   */
  payOrderUpdate: (orderId, payOrderId, status, reason, _this, orderGroupId) => {
    console.log(orderGroupId, 7777)
    let that = _this;
    // 支付成功
    Http.post({
        url: config.api.payOrderUpdate,
        data: {
          payOrderId: payOrderId,
          composeOrderId: orderId,
          status: status,
          reason: reason
        }
      })
      .then(res => {
        wx.hideLoading()
        that.setData({
          disabled: false
        })
        if (res.data.orderStatus == 14) {
          _this.setData({
            showErr: true
          })
          return;
        }
        if (orderGroupId == undefined) {
          wx.navigateTo({
            url: '/pages/order/detail/index?orderId=' + res.data.id,
          })
        } else {
          _this.goToOrderGroup(res.data.singleOrder.id, res.data.mainOrderId, _this)
        }
      })
      .catch(err => {
        console.log(err);
        that.setData({
          disabled: false
        })
        if (err.code != 12002) {
          setTimeout(function() {
            _this.payOrderUpdate(orderId, payOrderId, status, reason, _this, orderGroupId);
          }, 2000)
        }
      })
  },
  gotoPay() {
    let that = this;
    wx.showLoading({
      title: '支付创建中...',
    })
    that.setData({
      disabled: true
    })
    Http.post({
        url: config.api.payOrderCreate,
        data: {
          orderId: that.data.paramData.orderId,
          composeOrderType: that.data.paramData.composeOrderType,
        }
      })
      .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.paramData.orderId, payOrderId, 1, '', that, 0);
            if (res.errMsg == "requestPayment:ok") {
              setTimeout(function() {
                wx.hideLoading();
              }, 2000);
            }
          },
          fail: res => {
            /**
             * 支付失败，需要更新订单的状态
             */
            that.payOrderUpdate(that.data.paramData.orderId, payOrderId, 2, '', that, 0);
            that.setData({
              showbutton: false,
              canSpell: true,
              canBuyIf: true,
              disabled: false
            })
            return;
          },
          complete: res => {}
        });
        /// End payment  --------
      })
      .catch(err => {
        that.setData({
          canSpell: true,
          canBuyIf: true,
          disabled: false
        })
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },
  /**
   * 去使用
   */
  gotoUse() {
    wx.navigateTo({
      url: `/pages/couponorder/index/index`
    });
  },
  /**
   * 拼团状态字段转换
   */
  changeSatus(status) {
    console.log(spellStatus, 8888888)
    return spellStatus.filter(item => item.value == status)[0].name;
  },
  //跳转拼团列表
  gotoSpellList() {
    wx.navigateTo({
      url: '/pages/spellGroup/spellGroup',
    })
  },
  /**
   * 获取券详情信息
   */
  getDetail() {
    let that = this;
    Http.get({
      url: config.api.couponDetail,
      data: {
        couponChannelId: this.data.paramData.couponChannelId
      }
    }).then(res => {
      wx.stopPullDownRefresh();
      let data = res.data;
      that.setData({
        data
      });
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      showTime: true
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      showTime: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    this.setData({
      showTime: false
    })
  },

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