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

  /**
   * 页面的初始数据
   */
  data: {
    mouldType: 0,
    mouldConfig: {},
    navigationBarHeight,
    teljpgUrl: imgurl.teljpg.url,
    wmhome: imgurl.wmhome.url,
    orderGroupFail: imgurl.orderGroupFail.url,
    homeSelectedO: imgurl.homeSelectedO.url,
    couponChannelId: '',
    couponId: '',
    data: [],
    spellData: null,
    canSpell: true,
    canBuyIf: true,
    clock: "00",
    day: "0",
    hour: "00",
    min: "00",
    sec: "00",
    paramData: null,
    showErr: false,
    showTime: true,
    merchantVoList: [],
    mallList: [],
    nickName: '微信用户'
  },

  /** 
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 'options');
    this.setData({
      mouldType: app.globalData.mouldType,
      mouldConfig: app.globalData.mouldConfig,
    })
    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,
          couponChannelId: options.couponChannelId,
          couponId: options.couponId,
          orderGroupId: options.orderGroupId,
          orderId: options.orderId,
          avatarUrl: options.avatarUrl,
          nickName: options.nickName || '微信用户',
        })
        if (options.orderGroupId) {
          this.checkUser(options);
        }

      }).catch(res => {
        wx.redirectTo({
          url: `/pages/getphoneInfo/index`
        });
      })
    }).catch(res => {
      wx.redirectTo({
        url: `/pages/getuserinfo/index`
      })
    })
  },
  gotoIndex() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  /**
   * 判断用户是否已经在团中
   */
  checkUser(options) {
    let that = this;
    Http.get({
      url: config.api.queryAttendStatus,
      data: {
        id: options.orderGroupId,
      }
    }).then(res => {
      wx.stopPullDownRefresh();
      if (res.data.attend == true || res.data.status != 10) {
        wx.redirectTo({
          url: `/pages/spellDetail/index?orderId=${options.orderId}&couponId=${options.couponId}&orderGroupId=${options.orderGroupId}&couponChannelId=${options.couponChannelId}`,
        })
      } else {
        that.getDetail(that.data.couponChannelId);
        that.getOneSpell(that.data.couponId)
      }
    });
  },
  /**
   * 拨打电话
   */
  phone: function (e) {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: e.target.dataset.merchantlinkphone
    });
  },
  /**
   * 直接购买
   */
  gotoBuy(e) {
    let formId = e.detail.formId;
    let that = this;
    that.setData({
      formId: formId
    })
    this.setData({
      canBuyIf: false
    })
    this.orderFunc()
  },
  // 时间格式化输出，如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
    }
  },
  countdown(time) {
    let that = this;
    var EndTime = time;
    if (that.data.spellData != null) {
      EndTime = that.data.spellData.expiredDate;
    }
    var NowTime = new Date().getTime();
    var total_micro_second = EndTime - NowTime || [];
    // 渲染倒计时时钟
    let obj = that.dateformat(total_micro_second);
    console.log(obj)
    if (total_micro_second > 0) {
      that.setData({
        clock: obj,
        day: obj.a1,
        hour: obj.b1,
        min: obj.c1,
        sec: obj.d1,
      })
    } else {
      that.setData({
        // spellData:null,
        clock: "00",
        day: "00",
        hour: "00",
        min: "00",
        sec: "00",
      })
      // that.getOneSpell(that.data.couponId)
    }
    if (that.data.showTime) {
      setTimeout(function () {
        total_micro_second -= 1000;
        that.countdown();
      }, 1000)
    }
  },
  /**
   * 发起拼团
   */
  gotoSpell() {
    this.setData({
      canSpell: false
    })
    this.orderFunc(this.data.orderGroupId)
  },
  /**
   * 获取一个拼团信息
   */
  getOneSpell(couponId) {
    let that = this;
    Http.get({
      url: config.api.queryOrderGroupStatus,
      data: {
        couponId: couponId,
        id: that.data.orderGroupId,
        orderId: that.data.orderId
      }
    }).then(res => {
      if (res.data) {
        that.countdown(res.data.expiredDate);
        that.setData({
          spellData: res.data
        });
      }
    });
  },
  /**
   * 获取券详情信息
   */
  getDetail(couponChannelId) {
    let that = this;
    Http.get({
      url: config.api.couponDetail,
      data: {
        couponChannelId: couponChannelId
      }
    }).then(res => {
      let data = res.data;
      data.price = (data.price / 100).toFixed(2)
      data.salePrice = (data.salePrice / 100).toFixed(2)
      data.validStartDate = utils.formatTime(data.validStartDate, 'yyyy-MM-dd')
      data.validEndDate = utils.formatTime(data.validEndDate, 'yyyy-MM-dd')
      that.setData({
        data,
        // merchantVoList: data.merchantVoList
      });
      Http.get({
        url: config.api.couponMerchant,
        data: {
          couponChannelId: couponChannelId
        }
      }).then(res => {
        const keys = Object.keys(res.data)
        const mallList = []
        keys.forEach(item => {
          const arr = item.split('|')
          const obj = {
            tenantId: arr[0],
            mallName: arr[1],
            merchantVoList: res.data[item],
            expand: true
          }
          mallList.push(obj)
        })
        this.setData({
          mallList: mallList
        })
        console.log(this.data.mallList, 'mallList');
      })
    });
  },
  /**
   * 去拼团
   */
  goToOrderGroup(orderId, orderGroupId, _this) {
    let that = this;
    // 支付成功
    Http.post({
      url: config.api.toOrderGroup,
      data: {
        id: orderGroupId,
        orderId,
        couponId: _this.data.data.couponId
      }
    })
      .then(res => {
        wx.reLaunch({
          url: `/pages/spellDetail/index?orderId=${orderId}&couponId=${_this.data.data.couponId}&orderGroupId=${res.data.orderGroupId}&couponChannelId=${_this.data.couponChannelId}`
        });
      })
      .catch(err => {
        console.log(err);
      })
    // return;
  },
  /**
   * 支付订单更新
   */
  payOrderUpdate: (orderId, payOrderId, status, reason, _this, orderGroupId) => {
    // 支付成功
    Http.post({
      url: config.api.payOrderUpdate,
      data: {
        payOrderId: payOrderId,
        composeOrderId: orderId,
        status: status,
        reason: reason
      }
    })
      .then(res => {
        wx.hideLoading()
        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.singleOrder.orderGroupId, _this)
        }
      })
      .catch(err => {
        console.log(err);
        if (err.code != 12002) {
          setTimeout(function () {
            _this.payOrderUpdate(orderId, payOrderId, status, reason, _this, orderGroupId);
          }, 2000)
        }
      })
  },
  /**
   * 发起支付
   */
  orderFunc(orderGroupId) {
    let data = {
      couponChannelId: this.data.data.id,
      couponId: this.data.data.couponId,
      orderId: this.data.formId
    }
    /**
     * 拼团订单
     */
    data.orderGroupId = orderGroupId

    var that = this;
    Http.get({
      url: config.api.checkPhoneStatus,
      data: {}
    })
      .then(res => {
        /**
         * orderSave 下单
         */
        return Http.post({
          url: config.api.orderSave,
          data: data
        });
      })
      .catch(err => {
        that.setData({
          showbutton: false,
          showbutton1: false,
          canSpell: true,
          canBuyIf: 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.showToast({
            title: err.message,
            icon: "none"
          })
        } else if (err.code == 11005) {
          /**
           * 将值传到用户手机号授权的页面
           *
           */
          console.log(that.data, 444)
          wx.redirectTo({
            url: "/pages/getphoneInfo/index?path=spell&couponChannelId=" +
              that.data.couponChannelId + '&orderGroupId=' + that.data.orderGroupId + '&couponId=' + that.data.couponId + '&orderId=' + that.data.orderId + '&avatarUrl=' + that.data.avatarUrl + '&nickName=' + that.data.nickName
          });
        } else if (err.code == 11006) {
          // 用户手机已加密
          wx.redirectTo({
            url: "/pages/phoneinput/phoneinput?path=spell&couponChannelId=" +
              that.data.couponChannelId + '&orderGroupId=' + that.data.orderGroupId + '&couponId=' + that.data.couponId + '&orderId=' + that.data.orderId + '&avatarUrl=' + that.data.avatarUrl + '&nickName=' + that.data.nickName
          });
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })
      .then(res => {
        console.log(res)
        that.setData({ aa: res })

        if (typeof (res) != "undefined") {
          let orderId = "" + res.data.mainOrderId;
          that.setData({
            orderId: orderId,
            composeOrderType: res.data.composeOrderType,
            canSpell: false,
            canBuyIf: true
          });
          // 支付金额不为0
          /**
           * 支付订单创建
           */
          Http.post({
            url: config.api.payOrderCreate,
            data: {
              orderId: orderId,
              composeOrderType: that.data.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: '订单正在处理中...',
                  })
                  that.setData({
                    canSpell: false
                  })
                  setTimeout(function () {
                    wx.hideLoading()
                  }, 5000)
                  that.payOrderUpdate(that.data.orderId, payOrderId, 1, '', that, orderGroupId);
                  if (res.errMsg == "requestPayment:ok") {
                    setTimeout(function () {
                      wx.hideLoading();
                    }, 2000);
                  }
                },
                fail: res => {
                  /**
                   * 支付失败，需要更新订单的状态
                   */
                  that.payOrderUpdate(that.data.orderId, payOrderId, 2, '', that, orderGroupId);
                  that.setData({
                    showbutton: false,
                    canSpell: true,
                    canBuyIf: true
                  })
                  return;
                },
                complete: res => { }
              });
              /// End payment  --------
            })
            .catch(err => {
              that.setData({
                canSpell: true,
                canBuyIf: true
              })
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000,
                mask: false
              });
            })
        }

      })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      mouldType: app.globalData.mouldType,
      canSpell: true,
      canBuyIf: true,
      showTime: true
    })
    if (this.data.spellData != null) {
      this.countdown()
    }
  },

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

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

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