const navigationBarHeight = (getApp().statusBarHeight + 50) + '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");
const QR = require("../../../utils/memberqrcode.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    curHtml: '',
    showIdFalg: false,
    outOrderNo: '', //支付2.0继续支付id
    payOrderNo: "", //评价订单id
    evaluateFlag: false, //控制评价显隐藏
    serviceUrl: '', //客服外部链接
    dynamicRq: "",
    expiredSeconds: 0,
    couponTenantId: '',
    showhieRq: false,
    mouldType: 0,
    showFlag: false,
    navigationBarHeight,
    upDataRqUrlF: imgurl.upDataRqF.url,
    succUrl: imgurl.succ.url,
    spcodeUrl: imgurl.spcode.url,
    chevronUrl: imgurl.chevron.url,
    teljpgUrl: imgurl.teljpg.url,
    newUrl: imgurl.new1.url,
    weixinTitle: imgurl.weixinTitle.url,
    lineUrl: imgurl.line.url,
    wm01Url: imgurl.wm01.url,
    wm02Url: imgurl.wm02.url,
    wm03Url: imgurl.wm03.url,
    wm04Url: imgurl.wm04.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, //判断是不是线上配送
    tenantId: '',
    mallList: []
  },
  handleRefund(event) {
    const {
      status,
      result
    } = event.detail;
    if (status === 'success') {
      const {
        refundId,
        outRefundNo
      } = result;
      console.log(refundId, outRefundNo);
    } else {
      const {
        errMsg
      } = result;
      console.log(errMsg);
    }
  },
  applyRefund(event) {
    const {
      orderId
    } = event.detail;
    const extra = {
      orderId
    }; // 开发者需要透传的参数，可自定义内容
    return new Promise(resolve => {
      resolve(extra);
    });
  },
  showId() {
    let this_ = this;
    if (!this_.data.showIdFalg) {
      tt.showModal({
        // title: "查看券码",
        content: "是否查看完整券码",
        success(res) {
          if (res.confirm) {
            console.log("confirm, continued");
            this_.setData({
              showIdFalg: true
            })
          } else if (res.cancel) {
            //取消
            console.log("cancel, cold");
          } else {
            // what happend?
          }
        },
        fail(err) {
          console.log(`showModal 调用失败`, err);
        },
      });
    } else {
      this.setData({
        showIdFalg: false
      })
    }

  },

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

  setShow() {
    this.setData({
      showFlag: true
    })
  },
  hieShow() {
    this.setData({
      showFlag: false
    })
  },

  getCouponMerchant() { //获取适用门店
    Http.get({
      url: config.api.orderDetail,
      data: {
        orderId: this.data.orderId,
        mallTenantId: this.data.mallTenantId || ''
      }
    }).then(res => {
      const couponChannelId = res.data.orders[0].couponChannelId
      Http.get({
        url: config.api.couponMerchant,
        data: {
          couponChannelId: couponChannelId,
          mallTenantId: this.data.mallTenantId || ''
        }
      }).then(res => {
        const keys = Object.keys(res.data)
        const mallList = []
        let i = 0
        keys.forEach(item => {
          const arr = item.split('|')
          const obj = {
            tenantId: arr[0],
            mallName: arr[1],
            merchantVoList: res.data[item],
            expand: false
          }
          if (i == 0) {
            obj.expand = true
          }
          mallList.push(obj)
          i++
        })
        this.setData({
          mallList: mallList
        })
      })
    }).catch(err => {

    })
  },

  goDetail() {
    tt.navigateTo({
      url: `/pages/coupon/detail/index?couponChannelId=${this.data.order.couponChannelId}&mallTenantId=${this.data.mallTenantId}`,
      success: (res) => {

      },
      fail: (res) => {

      },
    });
  },
  refund() { //退款
    Http.post({
      url: config.api.refund,
      data: {
        orderId: this.data.order.id,
        mallTenantId: this.data.mallTenantId || ''
      }
    }).then(res => {
      tt.navigateTo({
        url: `/pages/refund/refund?id=${this.data.order.id}&mallTenantId=${this.data.mallTenantId}`,
        success: (res) => {

        },
        fail: (res) => {

        },
      });
    }).catch(err => {
      tt.showToast({
        title: err.message ? err.message : err.data, // 内容
        icon: "none"
      });
    })
  },
  goRefund(e) {
    let this_ = this
    if (this_.data.order.couponOrderStatus == 0) {
      tt.showModal({
        title: "申请退款",
        content: "提交申请退款",
        confirmText: "确定",
        success(res) {
          if (res.confirm) {

            this_.refund()
            console.log("confirm, continued");
          } else if (res.cancel) {
            console.log("cancel, cold");
          } else {
            // what happend?
          }
        },
        fail(res) {
          console.log(`showModal调用失败`);
        },
      });
    } else if (this_.data.order.couponOrderStatus == 3) { //退款中
      tt.navigateTo({
        url: `/pages/refund/refund?id=${this.data.order.id}&mallTenantId=${this.data.mallTenantId}`,
        success: (res) => {

        },
        fail: (res) => {

        },
      });
    }


  },

  //刷新订单
  updetail() {
    let that = this
    let url = config.api.orderDetail

    Http.get({
      url: url,
      data: {
        orderId: this.data.orderId,
        mallTenantId: this.data.mallTenantId || ''
      }
    }).then(res => {
      tt.hideLoading();
      if (res.data.tenantId) {
        that.setData({
          tenantId: res.data.tenantId
        })
      }
      var createDate = util.formatTime(res.data.orders[0].createDate, "yyyy-MM-dd");
      let tempData = res.data.orders[0]
      tempData.deliveryInfo = tempData.deliveryInfo ? JSON.parse(tempData.deliveryInfo) : ""
      tempData.itemGroup = tempData.itemGroup ? JSON.parse(tempData.itemGroup) : ""
      tempData.validStartDate = util.formatTime(tempData.validStartDate, "yyyy-MM-dd")
      tempData.validEndDate = util.formatTime(tempData.validEndDate, "yyyy-MM-dd")
      tempData.couponOrderIdS = tempData.couponOrderId ? tempData.couponOrderId.slice(0, 4) + `******` + tempData.couponOrderId.slice(14) : ''

      if (tempData.productAttrs && tempData.skuAttrs) {
        tempData.productAttrs = JSON.parse(tempData.productAttrs)
        tempData.skuAttrs = JSON.parse(tempData.skuAttrs)
        console.log(tempData.productAttrs);
        console.log(tempData.skuAttrs);
        console.log('****');
        tempData.productAttrs.map(item => {

          if (item.key == "appointment") {
            let tempAppoinObj = JSON.parse(item.data)
            if (tempAppoinObj.need_appointment) {
              let subscribeSing = "";
              if (tempAppoinObj.ahead_time_type == 1) {
                subscribeSing = `需提前${tempAppoinObj.ahead_day_num}天致电商家预约`
              } else if (tempAppoinObj.ahead_time_type == 2) {
                subscribeSing = `需提前${tempAppoinObj.ahead_hour_num}小时致电商家预约`
              } else if (tempAppoinObj.ahead_time_type == 3) {
                subscribeSing = `需提前${tempAppoinObj.ahead_minute_num}分钟致电商家预约`
              }
              tempData.subscribeSing = subscribeSing
            }

          }

          if (item.key == "Notification") {
            if (item.data != '') {
              tempData.curLsit = JSON.parse(item.data)
            }
          }
          if (item.key == "bring_out_meal") {
            tempData.besides = item.data
          }
          if (item.key == "free_pack") {
            tempData.pack = item.data
          }

          if (item.key == "superimposed_discounts") {
            tempData.superimposed_discounts = item.data
          }
          if (item.key == "private_room") {
            tempData.private_room = item.data
          }
          if (item.key == "rec_person_num_max") {
            tempData.rec_person_num_max = item.data
          }


          if (item.key == 'Description') {
            tempData.Description = JSON.parse(item.data)
          }
          if (item.key == "can_no_use_date") {
            tempData.can_no_use_date = JSON.parse(item.data)
          }
        })

        tempData.skuAttrs.map(item => {
          if (item.key == "commodity") {
            if (item.data != '') {
              tempData.itemGroup = JSON.parse(item.data)
            }
          }
        })

      }


      that.setData({
        outOrderNo: res.data.id,
        order: tempData,
        showPage: true,
        createDate: createDate,
        composeOrderType: tempData.composeOrderType,
        contentType: tempData.contentType ? tempData.contentType : 0,
        orderFlag: tempData.type == 11 ? true : false, //判断是不是线上配送
      })
      if (tempData.couponOrderId) { //0未付款 1已支付 2已取消 3退款中 4已退款
        that.setRq()
        // that.upStatus()
        let setInter = setInterval(() => {
          if (tempData.couponOrderStatus == 0) {
            Http.get({
                url: config.api.getStatus,
                data: {
                  couponOrderId: tempData.couponOrderId,
                  mallTenantId: this.data.mallTenantId || ''
                }
              }).then(res => {
                console.log(res);
                that.setData({
                  couponOrderStatus: res.data.CouponOrderStatus
                });
                if (res.data.CouponOrderStatus == 1 || res.data.CouponOrderStatus == 3) {
                  /**
                   * 动态改变上一级页面的核销状态
                   */
                  // that.getStaticGame()
                  //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
                  clearInterval(that.data.setInter);
                  clearInterval(that.data.templTiem);
                  that.updetail()
                  that.setData({
                    mystatus: res.data.CouponOrderStatus
                  });
                }
              })
              .catch(err => {
                tt.showToast({
                  title: err.errMsg,
                  icon: 'none',
                  duration: 2000,
                  mask: false
                });
              })
          }
        }, 2000);
        that.setData({
          setInter: setInter
        })
      }
      if (tempData.couponOrderStatus && tempData.couponOrderStatus == 1) { //核销后
        that.goIfEvaluate() //判断订单是否能评价
      }
    }).catch(error => {
      console.log(error, "error");
      tt.hideLoading();
      tt.showModal({
        title: '提示',
        content: error.errMsg,
        showCancel: false
      })
    })
  },
  //确认收货
  verify() {
    Http.post({
      url: config.api.verify,
      data: {
        couponOrderId: this.data.order.couponOrderId
      }
    }).then(res => {
      tt.showToast({
        title: '签收成功',
        icon: "none"
      })
      this.updetail()
    }).catch(err => {
      tt.showModal({
        title: '提示',
        content: err.message ? err.message : err.data,
        showCancel: false
      })
    })
  },
  phone: function (e) {
    let that = this;
    console.log(e);
    tt.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.merchantlinkphone
    });
  },
  /**
   * 跳转到门店列表的详情页面
   */
  gotoDetail(e) {
    tt.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)
    }
  },

  createQrCode: function (url, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    let that = this;
    QR.api.draw(url, canvasId, cavW, cavH, function (res) {
      that.setData({
        tempFilePath: res
      })
    });
  },

  setRq() {
    let _this = this
    _this.setData({
      showhieRq: false,
    })
    Http.get({ //获取动态二维码
      url: config.api.dynamicId,
      data: {
        couponOrderId: _this.data.order.couponOrderId,
        couponTenantId: _this.data.tenantId || ''
      }
    }).then(res => {
      console.log(res, "res")
      _this.setData({
        dynamicRq: res.data.dynamicId,
        expiredSeconds: res.data.expiredSeconds,
        couponTenantId: res.data.couponTenantId
      })

      let url = JSON.stringify({
        END: "C",
        TYPE: "couponorder",
        ID: _this.data.dynamicRq,
        couponTenantId: _this.data.couponTenantId
      })
      if (res.data.expiredSeconds == 0) {
        //倒计时为零直接显示券码
      } else {
        let inre = setInterval(() => {
          if (_this.data.expiredSeconds > 1) {
            _this.setData({
              expiredSeconds: _this.data.expiredSeconds - 1
            })
            // console.log("有效", _this.data.expiredSeconds)
          } else {
            // console.log("无效", _this.data.expiredSeconds)
            clearInterval(_this.data.templTiem)
            _this.setData({
              showhieRq: true
            })
          }
          _this.setData({
            templTiem: inre
          })
        }, 1000)
      }
      _this.createQrCode(url, "qrcode", 350, 350);
    }).catch(err => {
      tt.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000,
        mask: false
      });
    })
  },

  goPaySnapshoot(e) {
    let id = e.currentTarget.dataset.id;
    tt.navigateTo({
      url: `/pages/paySnapshoot/paySnapshoot?id=${id}`,
      success: (res) => {

      },
      fail: (res) => {

      },
    });
  },
  powerDrawer: function (e) {
    let that = this;
    console.log(e)
    // couponOrderStatus
    // 0 未使用
    // 1 已使用
    // 2 已过期
    // 3 已经退款
    if (that.data.mystatus == "" || that.data.mystatus == undefined) {
      tt.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 {
      tt.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;
    tt.redirectTo({
      url: '/pages/game/index?url=' + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
    })
  },
  // 买完卡跳转到立即使用页面
  gotoUse: function () {
    tt.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);
      })
  },
  goEvaluate() {
    let _this = this
    tt.rateAwemeOrder({
      orderId: _this.data.payOrderNo,
      success({
        result
      }) {
        console.log(result);
        if (result) {
          tt.navigateBack({
            delta: 1,
            success: (res) => {

            },
            fail: (res) => {

            },
          });
          // 用户已经评价的逻辑
        } else {
          // 用户没有评价的逻辑
        }
      },
      fail(err) {
        console.log(err);
      },
    });
  },

  goIfEvaluate() {
    let _this = this
    Http.get({
      url: config.api.getchanId,
      data: {
        id: _this.data.order.couponOrderId,
        mallTenantId: this.data.mallTenantId || ''
      }
    }).then(res => {
      tt.canRateAwemeOrders({
        orderIds: [res.data.payOrderNo],
        success({
          result
        }) {
          console.log("result", result);
          _this.setData({
            evaluateFlag: result[0],
            payOrderNo: res.data.payOrderNo
          })
        },
        fail(err) {
          console.log(err);
        },
      });
    }).catch(err => {
      tt.showToast({
        title: err.message ? err.message : err.data, // 内容
        icon: "none"
      });
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSeUrl()
    if (options.mallTenantId) {
      this.setData({
        mallTenantId: options.mallTenantId,
      })
    }

    this.setData({
      mouldType: app.globalData.mouldType
    })
    let that = this;
    // if (options.dingdan && options.dingdan == "order") {

    // }
    that.setData({
      orderId: options.orderId,
    });
    tt.hideShareMenu()
    if (options.cardIf) { //转赠 展示不需
      that.setData({
        cardIf: true
      })
    }
    tt.showLoading({
      title: "加载中"
    });

    this.getCouponMerchant() //获取可用商户
  },
  onShow: function () {
    let that = this;
    that.setData({
      showButton: false
    })
    that.updetail()
  },
  getSeUrl() { //获取客服链接 
    const openId = tt.getStorageSync('openId');
    Http.post({
      url: config.api.getServiceUrl,
      data: {
        appid: app.globalData.appId,
        openid: openId
      }
    }).then(res => {
      this.setData({
        serviceUrl: res.data ? res.data : ''
      })
      if (res.data) {
        tt.setStorageSync('serviceData', res.data);
      }
    })
  },
  goWebView() {
    let _this = this
    tt.navigateTo({
      url: `/pages/serviceWebView/serviceWebView`,
      success: (res) => {

      },
      fail: (res) => {

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

    // if (true) {//兼容不支持支付2.0 js-api  !tt.canIUse('createOrder')
    if (that.data.order.payment > 0) {

      if (tt.canIUse('createOrder')) { //支付2.0 js-api 
        const outOrderNo = that.data.outOrderNo
        console.log(outOrderNo, "outOrderNo");
        Http.post({
          url: config.api.payOrderCreate_2,
          data: {
            // composeOrderId: outOrderNo
            orderId: outOrderNo,
            composeOrderType: that.data.composeOrderType,
            mallTenantId: this.data.mallTenantId || ''
          }
        }).then(res => {
          if (res.data.createPay) {
            let tempCallbackData = res.data.callbackData
            // tempCallbackData[that.data.data.couponChannel.ttSpuId] = that.data.data.couponChannel.id
            let options = {
              callbackData: tempCallbackData,
              goodsList: res.data.goodsList,
              payment: res.data.payment,
              success: res => {
                tt.hideLoading();
                that.setData({
                  showbutton: false,
                })
                const {
                  orderId,
                  outOrderNo
                } = res;
                // that.setData({
                //   orderId,
                //   outOrderNo
                // });
                that.payOrderUpdate(outOrderNo, outOrderNo, 1, '', '', that, '');
              },
              fail: res => {
                const {
                  orderId,
                  outOrderNo,
                  errNo,
                  errMsg,
                  errLogId
                } = res;
                if (errLogId) {
                  tt.hideLoading();
                  that.setData({
                    showbutton: false,
                  })
                  console.log('预下单失败', errNo, errMsg, errLogId);
                  let tempErrmsg = errMsg.split('开发者拒绝交易:');
                  tt.showToast({
                    title: tempErrmsg[tempErrmsg.length - 1],
                    icon: 'none',
                    duration: 2000,
                    mask: false
                  });
                }
                if (orderId || outOrderNo) {
                  tt.hideLoading();
                  that.setData({
                    showbutton: false,
                  })
                  console.log('支付失败', errNo, errMsg, orderId, outOrderNo);
                  console.log(that.payOrderUpdate, "payOrderUpdate");
                  tt.showToast({
                    title: "取消支付",
                    icon: 'none',
                    duration: 2000,
                    mask: false
                  });
                  that.payOrderUpdate(outOrderNo, outOrderNo, 2, '', 'fail')
                }
              },
            }
            console.log(options, "options");
            tt.createOrder(options)
          } else {
            tt.continueToPay({
              outOrderNo: res.data.outOrderNo, // 外部订单号 2个订单号必填一个
              success: res => {
                // const { orderId, outOrderNo } = res;
                // console.log('success res', res);
                // console.log('orderId', orderId, 'outOrderNo', outOrderNo);
                that.setData({
                  showButton: false
                })
                tt.hideLoading();
                that.payOrderUpdate(outOrderNo, outOrderNo, 1, '', '', that); // 支付成功
              },
              fail: res => {
                const {
                  orderId,
                  outOrderNo,
                  errNo,
                  errMsg,
                  errLogId
                } = res;
                if (errLogId) {
                  console.log('查询订单信息失败', errNo, errMsg, errLogId);
                  that.setData({
                    showButton: false
                  })
                  tt.showToast({
                    title: errMsg,
                    icon: 'none',
                    duration: 2000,
                    mask: false
                  });
                  tt.hideLoading();
                }
                if (orderId || outOrderNo) {
                  console.log('支付失败', errNo, errMsg, orderId, outOrderNo);
                  tt.showToast({
                    title: errMsg,
                    icon: 'none',
                    duration: 2000,
                    mask: false
                  });
                  that.payOrderUpdate(outOrderNo, outOrderNo, 2, '', 'fail', that);
                  that.setData({
                    showButton: false
                  })
                  tt.hideLoading();
                }
              },
            });
          }

        }).catch(err => {
          tt.showToast({
            title: err.message ? err.message : err.data, // 内容
            icon: "none"
          });
        })
      } else { //不支持支付2.0 js-api
        tt.showToast({
          title: '请升级抖音', // 内容
          icon: "none"
        });
        return
        // 支付金额不为0
        Http.post({
          url: config.api.payOrderCreate,
          data: {
            orderId: orderId,
            composeOrderType: that.data.composeOrderType
          }
        }).then(res => {
          var payOrderId = "" + res.data.outOrderNo;
          tt.hideLoading();
          tt.pay({
            service: 5,
            orderInfo: {
              order_id: res.data.payOrderId,
              order_token: res.data.payOrderToken,
            },
            success: res => {
              tt.showLoading({
                title: '订单正在处理中...',
              })
              if (res.code == 0) {
                setTimeout(function () {
                  tt.hideLoading()
                }, 5000)
                that.payOrderUpdate(that.data.orderId, payOrderId, 1, '', '', that); // 支付成功
                if (res.errMsg == "requestPayment:ok") {
                  if (that.data.order.type == 100) {
                    tt.setStorage({
                      key: 'couponNum2',
                      data: "couponNum2"
                    })
                  } else if (that.data.order.type != 5) {
                    tt.setStorage({
                      key: 'couponNum',
                      data: "couponNum"
                    })
                  }
                }
              } else if (res.code === 1) {
                that.setData({
                  showButton: false
                })
                tt.hideLoading();
                tt.showToast({
                  title: '支付超时', // 内容
                  icon: "none"
                });

              } else if (res.code === 2) {
                that.setData({
                  showButton: false
                })
                tt.hideLoading();
                tt.showToast({
                  title: '支付失败', // 内容
                  icon: "none"
                });

              } else if (res.code === 3) {
                that.setData({
                  showButton: false
                })
                tt.hideLoading();
                tt.showToast({
                  title: '支付关闭', // 内容
                  icon: "none"
                });
              } else if (res.code === 4) {
                that.setData({
                  showButton: false
                })
                tt.hideLoading();
                tt.showToast({
                  title: '支付取消', // 内容
                  icon: "none"
                });
              } else if (res.code === 9) {
                that.setData({
                  showButton: false
                })
                tt.hideLoading();
                tt.showToast({
                  title: '订单状态开发者自行获取', // 内容
                  icon: "none"
                });
              }
            },
            fail: res => {
              that.setData({
                showButton: false
              })
              that.payOrderUpdate(that.data.orderId, payOrderId, 2, '', 'fail', that);
              return;
            },
          });
        }).catch(err => {
          tt.hideLoading();
          that.setData({
            showButton: false
          })
          tt.showModal({
            title: "抱歉",
            content: err.message,
            showCancel: false
          })
        });
      }

    } else {
      // 免费券
      that.payOrderUpdate(orderId, "0", 1, '', 'free') // 支付成功
      if (that.data.order.type == 100) {
        tt.setStorage({
          key: 'couponNum2',
          data: "couponNum2"
        })
      } else if (that.data.order.type != "5") {
        tt.setStorage({
          key: 'couponNum',
          data: "couponNum"
        })
      }
      tt.showToast({
        title: "支付成功",
        duration: 2000,
        image: imgurl.success.url,
      });
    }
    // } else {//支持 支付2.0 js-api


    // }

  },
  /**
   * 支付订单更新
   */
  payOrderUpdate(orderId, payOrderId, status, reason, type, _this) {
    // 支付成功
    Http.post({
        url: config.api.payOrderUpdate,
        data: {
          payOrderId: payOrderId,
          composeOrderId: orderId,
          status: status,
          reason: reason,
          mallTenantId: this.data.mallTenantId || ''
        }
      })
      .then(res => {
        tt.hideLoading();
        _this.setData({
          showButton: false
        })
        if (!type && type != 'free') {
          tt.showToast({
            title: "购买成功",
            duration: 2000,
            image: imgurl.success.url,
            mask: false,
            success: function () {
              tt.showLoading({
                title: "加载中..."
              });
              setTimeout(function () {
                tt.hideLoading();
              }, 1600);
              setTimeout(() => {
                console.log('Here1');
                let url = ""
                if (_this.data.orderFlag) {
                  tt.redirectTo({
                    url: `/pages/order/detail/index?orderId=${orderId}&dingdan=order}&mallTenantId=${that.data.mallTenantId}`
                  });
                } else {
                  tt.redirectTo({
                    url: `/pages/order/detail/index?orderId=${orderId}}&mallTenantId=${that.data.mallTenantId}`
                  });
                }

              }, 1600);
            }
          });
        } else if (type == 'free') {
          console.log('Here2');
          tt.redirectTo({
            url: `/pages/order/detail/index?orderId=${orderId}}&mallTenantId=${that.data.mallTenantId}`
          });
        }
      })
      .catch(err => {
        console.log(err)
        if (!type) {
          setTimeout(function () {
            _this.payOrderUpdate(orderId, payOrderId, status, reason, type, _this);
          }, 1500)
        }
      });
  },
  onUnload: function () {
    let that = this;
    clearInterval(that.data.setInter);
    clearInterval(that.data.templTiem);
  },
  onHide: function () {
    let that = this;
    clearInterval(that.data.setInter);
    clearInterval(that.data.templTiem);
  },
});