var config = require("../../../config/config.js");
var app = getApp();
const Http = require("../../../utils/HttpBasics");
const util = require("../../../utils/util");

Page({
  data: {
    data: {},
    carList: [],
    couponChannelId: null,
    couponId: null,
    orderId: "",
    hour: "",
    minute: "",
    tempFilePaths: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    id: '',
    result: [],
    end_time: '',
    clock: "已经截止",
  },

  phone: function () {
    let that = this;
    console.log(that.data);
    if (that.data.data.merchantLinkPhone) {
      wx.makePhoneCall({
        phoneNumber: that.data.data.merchantLinkPhone
      });
    }
  },

  countdown(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",
      })
    }
    setTimeout(function () {
      total_micro_second -= 1000;
      that.countdown(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: "加载中..."
    });
    /**
     * 暂时注销
     * this.orderFunc()
     */
    that.setData({
      couponChannelId: options.couponChannelId,
      couponId: options.couponId
    });
    var parmer = {
      url: config.api.couponDetail,
      data: {
        couponChannelId: options.couponChannelId
      }
    };
    Http.get(parmer).then(res => {
      console.log(res.data);
      if (res.data.endTime){
        that.countdown(res.data.endTime);
        //当前时间与优惠券下架时间做计算
        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 (res.data.validType == 1) {
        that.setData({
          validStartDate: util.formatTime(res.data.validStartDate, "yyyy-MM-dddd"),
          validEndDate: util.formatTime(res.data.validEndDate, "yyyy-MM-dddd"),
        });
      } else {
        that.setData({
          validDays: res.data.validDays
        });
      }
    });
  },
  /**
   * 支付订单更新
   */
  payOrderUpdate: (orderId, payOrderId, status, reason) => {
    // 支付成功
    Http.post({
      url: config.api.payOrderUpdate,
      data: {
        payOrderId: payOrderId,
        orderId: orderId,
        status: status,
        reason: reason
      }
    })
      .then(res => {
        console.log("payOrderUpdate then", res);
      })
      .catch(err => {
        console.log("payOrderUpdate catch", err);
      });
  },
  /**
   * 发起支付
   */
  orderFunc() {
    var that = this;
    wx.showLoading({
      title: "加载中..."
    });
    if (that.data.data.type == 6) { } else {
      Http.post({
        url: config.api.checkPhoneStatus,
        data: {}
      })
        .then(res => {
          console.log(res);
          var data = {
            couponChannelId: "" + that.data.couponChannelId,
            couponId: "" + that.data.couponId
          };
          if (that.data.couponChannelId == null) {
            var data = {
              couponId: "" + that.data.couponId
            };
          }
          /**
           * orderSave 下单
           */
          return Http.post({
            url: config.api.orderSave,
            data: data
          });
        })
        .catch(err => {
          console.log(err);
          if (err.code == "2011") {
            wx.showToast({
              title: "商户信息没找到",
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          } else if (err.code == "2013") {
            wx.showToast({
              title: "商户信息禁用",
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          } else if (err.code == "3000") {
            wx.showToast({
              title: "库存不足",
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          } else if (err.code == "3001") {
            wx.showToast({
              title: "领取达到上限",
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          } else if (err.code == "3002") {
            wx.showToast({
              title: "订单失败",
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          } else if (err.code == "3003") {
            wx.showToast({
              title: "订单不存在",
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          } else if (err.code == "3004") {
            wx.showToast({
              title: "订单不存在",
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          } else if (err.code == "4003") {
            wx.showToast({
              title: "卡券已作废",
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          } 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,
              image: "./../../../assets/img/fail.png",
              duration: 2000,
              mask: false
            });
          }
        })
        .then(res => {
          console.log(res);
          console.log("点击领取卡券一直在loading");
          if (typeof (res) != "undefined") {
            console.log("", res);
            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 => {
                console.log(res);
                /// Begin payment ----
                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 => {
                    that.payOrderUpdate(that.data.orderId, payOrderId, 1); // 支付成功
                    console.log(res);
                    if (res.errMsg == "requestPayment:ok") {
                      setTimeout(function () {
                        wx.hideLoading();
                      }, 2000);
                      setTimeout(() => {
                        wx.navigateTo({
                          url: `/pages/order/detail/index?orderId=${
                            that.data.orderId
                            }`
                        });
                      }, 1000)
                      /**
                       * 用户支付成功以后跳转到券包列表
                       */
                      wx.setStorage({
                        key: 'couponNum',
                        data: "couponNum",
                      })
                      if (that.data.data.type == 5) {
                        setTimeout(() => {
                          wx.switchTab({
                            url: '/pages/passCar/passCar'
                          });
                        }, 1600);
                        // this.initUsrCarList()
                        // 领取 5.停车券
                        // TODO 选取用户下的车牌                  
                      }
                    }
                  },

                  fail: res => {
                    that.payOrderUpdate(that.data.orderId, payOrderId, 2); // 支付失败
                    console.log(res);
                    return;
                  },
                  complete: res => {
                  }
                });
                /// End payment  --------

                ///// virtual pay
                //var payOrderId = "" + res.data.out_trade_no;
                //that.payOrderUpdate(that.data.orderId, payOrderId, 1); // 支付成功
                ///// end virtual pay
              });
            } else {
              // 免费券
              that.payOrderUpdate(orderId, "0", 1);
              wx.setStorage({
                key: 'couponNum',
                data: "couponNum"
              })
              setTimeout(function () {
                wx.navigateTo({
                  url: `/pages/order/detail/index?orderId=${
                    that.data.orderId
                    }`
                });
              }, 1000)
              //////////////////////////停车券
              console.log(that.data.data.type)
              if (that.data.data.type == 5) {
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/passCar/passCar'
                  });
                }, 1600);
              }
            }
          }
        })
        .catch(err => {
          console.log("ERR", err);
        });
    }
  },
  onShareAppMessage: function (options) {
    var that = this;
    var shareObj = {
      title: options.target.dataset.title,
      path: '/pages/index/index',
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res)
        }
      },
      fail: function (error) {
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          console.log(error)
        } else if (res.errMsg == 'shareAppMessage:fail') {
          console.log(error)
        }
      }
    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      console.log(options)
      var eData = options.target.dataset.id;
      var couponId = options.target.dataset.couponid;
      // shareObj.path = `/pages/index/index?couponChannelId=${eData}&couponId=${couponId}`;
      shareObj.path = `/pages/index/index?couponChannelId=${eData}&couponId=${couponId}`;
    }
    // 返回shareObj
    return shareObj;
  }
});