const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
let config = require("../../../config/config.js");
let util = require("../../../utils/util");
let Http = require("../../../utils/HttpBasics");
let app = getApp();
const imgurl = require("../../../utils/imgurl");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showIdFalg: false,
    showFlag: false,
    navigationBarHeight,
    succUrl: imgurl.succ.url,
    spcodeUrl: imgurl.spcode.url,
    chevronUrl: imgurl.chevron.url,
    teljpgUrl: imgurl.teljpg.url,
    newUrl: imgurl.new1.url,
    weixinTitle: imgurl.weixinTitle.url,
    showModalStatus: false,
    flag: 0,
    order: null,
    orderId: null,
    //存储计时器
    setInter: "",
    mystatus: '',
    staticGamedata: {},
    showIf: false,
    showPage: false,
    showButton: false,
    cardDetail: null,
    supportTransfer: '',
    cardIf: false,
    contentType: 0,
    orderFlag: false, //判断是不是线上配送
    mallList: []
  },
  showId() {
    let this_ = this;
    if (!this_.data.showIdFalg) {
      wx.showModal({
        content: '是否查看完整券码',
        success(res) {
          if (res.confirm) {
            this_.setData({
              showIdFalg: true
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      this.setData({
        showIdFalg: false
      })
    }

  },
  copeCode(e) {
    let code = e.currentTarget.dataset.text
    wx.setClipboardData({
      data: code,
      success: function () {
        wx.showToast({
          title: '复制成功',
          icon: "none"
        })
      }
    })
  },
  gokuaidi(e) {
    let nu = e.currentTarget.dataset.nu
    wx.navigateToMiniProgram({
      appId: 'wx6885acbedba59c14',
      path: `pages/result/result?nu=${nu}&com=&querysource=third_xcx`
    })
  },

  setShow() {
    this.setData({
      showFlag: true
    })
  },
  hieShow() {
    this.setData({
      showFlag: false
    })
  },
  //刷新订单
  updetail() {
    let that = this
    let url = config.api.orderDetail
    // let data = {}

    // if (that.data.orderFlag) {
    //   url = config.api.goodsDetail
    //   data = {
    //     mainOrderId: this.data.orderId
    //   }
    // } else {
    //   data = {
    //     orderId: this.data.orderId
    //   }
    // }

    Http.get({
      url: url,
      data: {
        orderId: this.data.orderId
      }
    }).then(res => {
      wx.hideLoading();
      console.log(res.data.orders[0], "data");
      if (res.data.orders[0].type == 5 || res.data.orders[0].type == 51) {
        wx.showModal({
          title: '领取成功',
          cancelText: '我知道了',
          confirmText: '去使用',
          content: '即将前往停车页面',
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: '/index/passCar'
              });
            }
          }
        })
      }
      // if (res.data.level == 0) { //单券
      //   if (res.code == 200) {
      //     that.getUserInfo()
      //     that.setData({
      //       showPage: true,
      //       composeOrderType: res.data.composeOrderType
      //     })
      //   }
      //   let tempData = res.data
      //   if (tempData.deliveryInfo) tempData.deliveryInfo = JSON.parse(tempData.deliveryInfo)

      //   that.setData({
      //     order: res.data,
      //     supportTransfer: res.data.supportTransfer
      //   });
      //   that.getStaticGame()
      //   //createDate 创建时间
      //   var createDate = util.formatTime(res.data.createDate, "yyyy-MM-dd hh:mm:ss");
      //   that.setData({
      //     createDate: createDate
      //   });
      // } else {

      // if (that.data.orderFlag) {
      that.getStaticGame()
      var createDate = util.formatTime(res.data.orders[0].createDate, "yyyy-MM-dd hh:mm:ss");
      let tempData = res.data.orders[0]
      tempData.deliveryInfo = tempData.deliveryInfo ? JSON.parse(tempData.deliveryInfo) : "";
      tempData.couponOrderIdS = tempData.couponOrderIdS ? tempData.couponOrderId.slice(0, 4) + `******` + tempData.couponOrderId.slice(14) : ''
      that.setData({
        order: tempData,
        showPage: true,
        createDate: createDate,
        composeOrderType: tempData.composeOrderType
      })
      console.log(that.data.order)
      Http.get({
        url: config.api.couponMerchant,
        data: {
          couponChannelId: that.data.order.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');
      })
      // } 
      // }


    })
      .catch(error => {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: error.message ? error.message : error.data,
          showCancel: false
        })
      })
  },
  //确认收货
  verify() {
    Http.post({
      url: config.api.verify,
      data: {
        couponOrderId: this.data.order.couponOrderId
      }
    }).then(res => {
      wx.showToast({
        title: '签收成功',
        icon: "none"
      })
      this.updetail()
    }).catch(err => {
      wx.showModal({
        title: '提示',
        content: err.message ? err.message : err.data,
        showCancel: false
      })
    })
  },
  phone: function (e) {
    let that = this;
    console.log(e);
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.merchantlinkphone
    });
  },
  /**
   * 跳转到门店列表的详情页面
   */
  gotoDetail(e) {
    wx.navigateTo({
      url: `/pages/index/searchbar/detail/index?id=${e.currentTarget.dataset.id}`
    })
  },
  getUserInfo: function () {
    let that = this;
    // 获取用户信息
    Http.get({
      url: config.api.getScore,
      data: {}
    })
      .then(res => {
        console.log(res)
        that.setData({
          userName: res.data.nickName,
          avatarUrl: res.data.avatarUrl
        })
      })
  },
  onShareAppMessage: function (res) {
    app.globalData.previewFlag = true
    if (res.from === 'button') {
      console.log(res, 3333333333333333333333)
      // 来自页面内转发按钮
      let _this = this;
      return {
        title: _this.data.userName + '赠送您一张' + _this.data.order.title,
        path: '/pages/index/index?couponChannelId=' + this.data.order.couponChannelId + '&cuserId=' + this.data.order.cuserId + '&couponId=' + this.data.order.productId + '&coverImg=' + this.data.order.coverImg + '&userName=' + this.data.userName + '&avatarUrl=' + this.data.avatarUrl + '&couponOrderId=' + this.data.order.couponOrderId + '&updateDate=' + this.data.order.updateDate,
        imageUrl: this.data.order.coverImg,
        success: function (res) {
          // 转发成功
        },
        fail: function (res) {
          // 转发失败
        }
      }
    } else {
      console.log(res, 444444444444444444)
    }
  },


  powerDrawer: function (e) {
    let that = this;
    console.log(e)
    // couponOrderStatus
    // 0 未使用
    // 1 已使用
    // 2 已过期
    // 3 已经退款
    if (that.data.mystatus == "" || that.data.mystatus == undefined) {
      wx.navigateTo({
        url: `/pages/orderquanma/index?quancode=${e.currentTarget.dataset.quancode
          }&title=${e.currentTarget.dataset.title}&subtitle=${e.currentTarget.dataset.subtitle
          }&remark=${e.currentTarget.dataset.remark}&couponorderstatus=${e.currentTarget.dataset.couponorderstatus}&validstatus=${e.currentTarget.dataset.validstatus}
          &contentType=${that.data.contentType}`
      });
    } else {
      wx.navigateTo({
        url: `/pages/orderquanma/index?quancode=${e.currentTarget.dataset.quancode
          }&title=${e.currentTarget.dataset.title}&subtitle=${e.currentTarget.dataset.subtitle
          }&remark=${e.currentTarget.dataset.remark}&couponorderstatus=${that.data.mystatus}&validstatus=${e.currentTarget.dataset.validstatus}
          &contentType=${that.data.contentType}`
      });
    }
  },
  gotogame: function () {
    let that = this;
    wx.redirectTo({
      url: '/pages/game/index?url=' + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
    })
  },
  // 买完卡跳转到立即使用页面
  gotoUse: function () {
    wx.navigateTo({
      url: '/pages/cardorder/index/index'
    })
  },
  // 获取游戏
  getStaticGame(token) {
    let _this = this;
    Http.get({
      url: config.api.getGame,
      data: {
        triggleAction: 3 // 购买触发
      }
    }).then(res => {
      if (res.data.id) {
        _this.setData({
          showIf: true
        })
      }
      _this.setData({
        staticGamedata: res.data
      })
    })
      .catch(err => {
        console.log(err);
      })
  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let that = this;
    if (options.dingdan && options.dingdan == "order") {
      that.setData({
        orderFlag: true //判断是不是线上配送
      })
    }
    that.setData({
      orderId: options.orderId,
      contentType: options.contentType,
      composeOrderType: options.composeOrderType
    });
    wx.hideShareMenu()
    if (options.cardIf) {
      that.setData({
        cardIf: true
      })
    }
    wx.showLoading({
      title: "加载中"
    });

    that.updetail()

  },
  onShow: function () {
    let that = this;
    that.setData({
      showButton: false
    })
  },
  /**
   * 去拼团
   */
  goToOrderGroup(orderId, orderGroupId, _this) {
    let that = this;
    // 支付成功
    Http.post({
      url: config.api.toOrderGroup,
      data: {
        id: orderGroupId,
        orderId,
        couponId: _this.data.order.productId
      }
    })
      .then(res => {
        wx.redirectTo({
          url: `/pages/spellDetail/index?orderId=${orderId}&couponId=${_this.data.order.productId}&orderGroupId=${res.data.orderGroupId}`
        });
      })
      .catch(err => {
        console.log(err);
      })
    // return;
  },
  /**
   * 发起支付
   */
  orderFunc(e) {
    var that = this;
    that.setData({
      showButton: true
    })
    wx.showLoading({
      title: "加载中..."
    });

    const orderId = "" + that.data.orderId;
    if (that.data.order.payment > 0) {
      // 支付金额不为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") {
              if (that.data.order.type == 100) {
                wx.setStorage({
                  key: 'couponNum2',
                  data: "couponNum2"
                })
              } else if (that.data.order.type != 5) {
                wx.setStorage({
                  key: 'couponNum',
                  data: "couponNum"
                })
              }
            }
          },
          fail: res => {
            that.setData({
              showButton: false
            })
            that.payOrderUpdate(that.data.orderId, payOrderId, 2, '', 'fail', that);
            return;
          },
        });
      }).catch(err => {
        wx.hideLoading();
        that.setData({
          showButton: false
        })
        wx.showModal({
          title: "抱歉",
          content: err.message,
          showCancel: false
        })
      });
    } else {
      // 免费券
      that.payOrderUpdate(orderId, "0", 1, '', 'free') // 支付成功
      if (that.data.order.type == 100) {
        wx.setStorage({
          key: 'couponNum2',
          data: "couponNum2"
        })
      } else if (that.data.order.type != "5") {
        wx.setStorage({
          key: 'couponNum',
          data: "couponNum"
        })
      }
      wx.showToast({
        title: "支付成功",
        duration: 2000,
        image: imgurl.success.url,
      });
    }
  },
  /**
   * 支付订单更新
   */
  payOrderUpdate: (orderId, payOrderId, status, reason, type, _this) => {
    // 支付成功
    Http.post({
      url: config.api.payOrderUpdate,
      data: {
        payOrderId: payOrderId,
        composeOrderId: orderId,
        status: status,
        reason: reason
      }
    })
      .then(res => {
        wx.hideLoading();
        _this.setData({
          showButton: false
        })
        if (!type && type != 'free') {
          wx.showToast({
            title: "购买成功",
            duration: 2000,
            image: imgurl.success.url,
            mask: false,
            success: function () {
              wx.showLoading({
                title: "加载中..."
              });
              setTimeout(function () {
                wx.hideLoading();
              }, 1600);
              setTimeout(() => {
                let url = ""
                if (_this.data.orderFlag) {
                  wx.redirectTo({
                    url: `/pages/order/detail/index?orderId=${orderId}&dingdan=order`
                  });
                } else {
                  wx.redirectTo({
                    url: `/pages/order/detail/index?orderId=${orderId}`
                  });
                }

              }, 1600);
            }
          });
        } else if (type == 'free') {
          wx.redirectTo({
            url: `/pages/order/detail/index?orderId=${orderId}`
          });
        }
      })
      .catch(err => {
        console.log(err)
        if (!type) {
          setTimeout(function () {
            _this.payOrderUpdate(orderId, payOrderId, status, reason, type, _this);
          }, 1500)
        }
      });
  },
});