const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
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: {
    navigationBarHeight,
    bannerUrl: imgurl.banner.url,
    wmhome: imgurl.wmhome.url,
    wmhelp: imgurl.wmhelp.url,
    chenggong: imgurl.chenggong.url,
    fail: imgurl.fail.url,
    data: null,
    from: null,
    day: null,
    hour: null,
    min: null,
    sec: null,
    showPage: false,
    discountStatus: null,
    disabled: false,
    display: "block!important",
    showButton1: false,
    goHomeUrl: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      goHomeUrl: app.globalData.goHomeUrl
    })
    if(app.globalData.token) {
      Http.get({
        url: config.api.checkUserStatus,
        data: {
          token: app.globalData.token
        }
      }).then(res => {
        Http.get({
          url: config.api.checkPhoneStatus,
          data: {}
        }).then(res => {
          let that = this;
          if (options.orderId || options.orderId && options.from == 'discount') {
            console.log(options, "options")
            if (options.from) {

              that.setData({
                orderId: options.orderId,
                composeOrderType: options.composeOrderType,
                from: "discount"
              })
            } else {
              that.setData({
                orderId: options.orderId,
                composeOrderType: options.composeOrderType,
              })
            }
            app.globalData.wmorder = options.orderId
            that.pressOrderDetail(options.orderId);
          }
          this.getUserInfo()
        }).catch(res => {
          wx.redirectTo({
            url: `/pages/getphoneInfo/index`
          });
        })
      }).catch(res => {
        wx.redirectTo({
          url: `/pages/getuserinfo/index`
        })
      })
    }else{
      app.tokenCallback = token =>{
        Http.get({
          url: config.api.checkUserStatus,
          data: {
            token: app.globalData.token
          }
        }).then(res => {
          Http.get({
            url: config.api.checkPhoneStatus,
            data: {}
          }).then(res => {
            let that = this;
            if (options.orderId || options.orderId && options.from == 'discount') {
              console.log(options, "options")
              if (options.from) {

                that.setData({
                  orderId: options.orderId,
                  composeOrderType: options.composeOrderType,
                  from: "discount"
                })
              } else {
                that.setData({
                  orderId: options.orderId,
                  composeOrderType: options.composeOrderType,
                })
              }
              app.globalData.wmorder = options.orderId
              that.pressOrderDetail(options.orderId);
            }
            this.getUserInfo()
          }).catch(res => {

            app.globalData.type = "bg"
            wx.redirectTo({
              url: `/pages/getuserinfo/index?orderId=${options.orderId}&composeOrderType=${options.composeOrderType}`
            });
          })
        }).catch(res => {

          app.globalData.type = "bg"
          wx.redirectTo({
            url: `/pages/getuserinfo/index?orderId=${options.orderId}&composeOrderType=${options.composeOrderType}`
          })
        })
      }
    }
    

  },
  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
        })
      })
  },
  onShow: function() {
    let that = this;
    var todayDate = new Date().getTime();
    that.setData({
      todayDate: todayDate,
      showButton1: false
    })
    if (that.data.pressEndDate) {
      that.countdown(that.data.pressEndDate)
    }
  },
  goback: function() {
    let this_ = this
    wx.switchTab({
      url: this_.data.goHomeUrl,
    })
  },
  /**
   * 更多砍价商品
   */
  gotomore: function() {
    wx.navigateTo({
      url: '/pages/bargain/bargain',
    })
  },
  /**
   * @param {砍价状态(1：我发起的砍价，2：未参与的砍价, 3:已参与的砍价)} orderId 
   */
  getPressOrderStatus: function(orderId) {
    let that = this;
    Http.get({
        url: config.api.getPressOrderStatus,
        data: {
          orderId: orderId
        }
      })
      .then(res => {
        if (res.data.status == 1) {
          that.setData({
            discountStatus: 1
          })
        } else if (res.data.status == 2) {
          that.setData({
            discountStatus: 2
          })
        } else if (res.data.status == 3) {
          that.setData({
            discountStatus: 3
          })
        }
        wx.stopPullDownRefresh();
      })
      .catch(err => {
        console.log(err)
        wx.stopPullDownRefresh();
        wx.showToast({
          title: err.errMsg,
          icon: "none"
        })
      })
  },
  helpDiscount: function() {
      let that = this;
      that.pressOrderJoin(that.data.orderId);
  },
  //参与砍价
  pressOrderJoin: function(orderId) {
    let that = this;
    Http.post({
        url: config.api.pressOrderJoin,
        data: {
          orderId: orderId
        }
      })
      .then(res => {
        console.log(res);
        // id 是订单号
        that.pressOrderDetail(orderId);
      })
      .catch(err => {
        console.log(err)
        wx.showToast({
          title: err.message,
          icon: "none"
        })
      })
  },
  // 订单详情
  pressOrderDetail: function(orderId) {
    let that = this;
    Http.get({
        url: config.api.pressOrderDetail,
        data: {
          orderId: orderId
        }
      })
      .then(res => {
        console.log(res);
        res.data.orderPressList.map(file => {
          file.createDate = diffTime(file.createDate)
        })
        that.countdown(res.data.pressEndDate);
        that.setData({
          pressEndDate: res.data.pressEndDate
        })
        res.data.orderPressList.map(file => {
          compare(file.first);
        })
        console.log(res.data.orderPressList.sort(compare('first')))
        that.setData({
          data: res.data,
          already: (res.data.price / 100 - res.data.salePrice / 100 - res.data.pressCurrentValue / 100).toFixed(2),
          remain: (res.data.pressCurrentValue / 100).toFixed(2),
          showPage: true
        })
        that.getPressOrderStatus(orderId);
      })
      .catch(err => {
        wx.showToast({
          title: err.message,
          icon: "none"
        })
        wx.stopPullDownRefresh();
      })
  },

  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一个标识 
    }
    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
    }
  },
  payOrderUpdate: (orderId, payOrderId, status, reason, type, _this) => {
    let that = this;
    console.log(that)
    console.log(_this)
    // 支付成功
    Http.post({
        url: config.api.payOrderUpdate,
        data: {
          payOrderId: payOrderId,
          composeOrderId: orderId,
          status: status,
          reason: reason
        }
      })
      .then(res => {
        wx.hideLoading();
        _this.setData({
          display: "none!important",
        })
        // 有价券
        if (!type && type != 'free') {
          wx.navigateTo({
            url: `/pages/order/detail/index?orderId=${
              orderId
              }`
          });
        } 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)
        }
      })
  },
  /**
   * 按原价付款
   */
  // orderFunc1(e) {
  //   var that = this;
  //   let formId = e.detail.formId;
  //   that.setData({
  //     showButton: true
  //   })
  //   Http.get({
  //       url: config.api.checkPhoneStatus,
  //       data: {}
  //     })
  //     .then(res => {
  //       that.setData({
  //         showButton: false
  //       })
  //       /**
  //        * orderSave 下单
  //        */
  //       var data = {
  //         couponChannelId:e.currentTarget.dataset.couponchannelid,
  //         couponId:e.currentTarget.dataset.couponid,
  //         formId:formId
  //       }
  //       return Http.post({
  //         url: config.api.orderSave,
  //         data: data
  //       });
  //     })
  //     .catch(err => {
  //       that.setData({
  //         showButton: 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: "您有未支付订单进行支付",
  //           showCancel: false,
  //           success: function (res) {
  //             console.log(res.confirm)
  //             if (res.confirm) {
  //             }
  //           }
  //         })
  //       }else if (err.code == 11005) {
  //         /**
  //          * 将值传到用户手机号授权的页面
  //          *
  //          */
  //         wx.redirectTo({
  //           url: "/pages/getphoneInfo/index?couponChannelId=" +
  //             that.data.couponChannelId +
  //             "&couponId=" +
  //             that.data.couponId
  //         });
  //       } else if (err.code == 11006) {
  //         // 用户手机已加密
  //         wx.redirectTo({
  //           url: "/pages/phoneinput/phoneinput?couponChannelId=" +
  //             that.data.couponChannelId +
  //             "&couponId=" +
  //             that.data.couponId
  //         });
  //       } 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.id;
  //         that.setData({
  //           orderId: orderId
  //         });
  //         if (e.currentTarget.dataset.saleprice / 100 > 0 || e.currentTarget.dataset.price / 100 > 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 {
  //                       wx.setStorage({
  //                         key: 'couponNum',
  //                         data: "couponNum"
  //                       })
  //                     }
  //                   }
  //                 },
  //                 fail: res => {
  //                   /**
  //                    * 支付失败，需要更新订单的状态
  //                    */
  //                   that.payOrderUpdate(that.data.orderId, payOrderId, 2, '', 'fail', that);
  //                   that.setData({
  //                     showbutton: false
  //                   })
  //                   return;
  //                 },
  //                 complete: res => {}
  //               });
  //               /// End payment  --------
  //             })
  //             .catch(err => {
  //               console.log(err);
  //               wx.showToast({
  //                 title: err.message,
  //                 icon: 'none',
  //                 duration: 2000,
  //                 mask: false
  //               });
  //             })
  //         } else {
  //           // 免费券
  //           that.payOrderUpdate(orderId, "0", 1, '', 'free', that);
  //           if (that.data.cardType == 100) {
  //             wx.setStorage({
  //               key: 'couponNum2',
  //               data: "couponNum2"
  //             })
  //           } else {
  //             wx.setStorage({
  //               key: 'couponNum',
  //               data: "couponNum"
  //             })
  //           }
  //         }
  //       }
  //     })
  // },
  /**
   * 发起支付
   */
  orderFunc(e) {
    var that = this;
    that.setData({
      showButton1: true
    })
    Http.get({
        url: config.api.checkPhoneStatus,
        data: {}
      })
      .then(res => {
        that.setData({
          showButton1: false
        })
        if (typeof(res) != "undefined") {
          let orderId = "" + e.currentTarget.dataset.orderid;
          that.setData({
            orderId: orderId
          });
          if (e.currentTarget.dataset.saleprice / 100 > 0 || e.currentTarget.dataset.price / 100 > 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: '订单正在处理中...',
                    })
                    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 {
                        wx.setStorage({
                          key: 'couponNum',
                          data: "couponNum"
                        })
                      }
                    }
                  },
                  fail: res => {
                    /**
                     * 支付失败，需要更新订单的状态
                     */
                    that.payOrderUpdate(that.data.orderId, payOrderId, 2, '', 'fail', that);
                    that.setData({
                      showbutton1: false
                    })
                    return;
                  },
                  complete: res => {}
                });
                /// End payment  --------
              })
              .catch(err => {
                console.log(err);
                wx.showToast({
                  title: err.message,
                  icon: 'none',
                  duration: 2000,
                  mask: false
                });
              })
          } else {
            // 免费券
            that.payOrderUpdate(orderId, "0", 1, '', 'free', that);
            if (that.data.cardType == 100) {
              wx.setStorage({
                key: 'couponNum2',
                data: "couponNum2"
              })
            } else {
              wx.setStorage({
                key: 'couponNum',
                data: "couponNum"
              })
            }
          }
        }
      })
      .catch(err => {
        that.setData({
          showButton1: 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.couponChannelId +
              "&couponId=" +
              that.data.couponId
          });
        } else if (err.code == 11006) {
          // 用户手机已加密
          wx.redirectTo({
            url: "/pages/phoneinput/phoneinput?couponChannelId=" +
              that.data.couponChannelId +
              "&couponId=" +
              that.data.couponId
          });
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })
  },
  onUnload: function() {
    let that = this;
    clearInterval(that.data.setInterval)
  },
  onHide: function() {
    let that = this;
    clearInterval(that.data.setInterval)
  },
  /**
   * 
   * @param {朋友邀请砍价} e 
   */
  barginAgain: function(e) {
    let that = this;
    let couponChannelId = e.currentTarget.dataset.couponchannelid;
    let couponId = e.currentTarget.dataset.couponid;
    wx.navigateTo({
      url: `/pages/coupon/detail/index?couponChannelId=${couponChannelId}&couponId=${couponId}`,
    })
  },
  /**
   * 刷新
   */
  onPullDownRefresh: function(e) {
    let that = this;
    console.log(app.globalData.wmorder);
    if (app.globalData.wmorder) {
      that.pressOrderDetail(app.globalData.wmorder);
    }
  },
  onShareAppMessage: function(options) { 
    app.globalData.previewFlag = true
    var that = this;
    console.log(`/pages/index/index?orderId=${that.data.orderId}&from=${"discount"}&composeOrderType=${that.data.composeOrderType}`)
    var shareObj = { 
      title: that.data.nickName + '邀请您帮砍' + that.data.data.title,
      path: `/pages/index/index?orderId=${that.data.orderId}&from=${"discount"}&composeOrderType=${that.data.composeOrderType}`,
      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 orderId = options.target.dataset.orderid;
      shareObj.path = `/pages/index/index?orderId=${that.data.orderId}&from=${"discount"}&composeOrderType=${that.data.composeOrderType}`;
    }
    
    console.log(shareObj)
    // 返回shareObj
    // return shareObj;
  },
})

function diffTime(startDate) {
  var diff = new Date().getTime() - startDate;
  var days = Math.floor(diff / (24 * 3600 * 1000));
  var leave1 = diff % (24 * 3600 * 1000);
  var hours = Math.floor(leave1 / (3600 * 1000));
  var leave2 = leave1 % (3600 * 1000);
  var minutes = Math.floor(leave2 / (60 * 1000));
  var leave3 = leave2 % (60 * 1000);
  var seconds = Math.round(leave3 / 1000);

  var returnStr = seconds + "秒";
  if (minutes > 0) {
    returnStr = minutes + "分" + returnStr;
  }
  if (hours > 0) {
    returnStr = hours + "小时" + returnStr;
  }
  if (days > 0) {
    returnStr = days + "天" + returnStr;
  }

  if (returnStr.indexOf('-1') == -1) {
    return returnStr;
  } else {
    return '1秒'
  }
}

function compare(property) {
  return function(a, b) {
    var value1 = a[property];
    var value2 = b[property];
    return value2 - value1;
  }
}