const navigationBarHeight = (getApp().statusBarHeight + 50) + '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: {
    priceAndStockObj:{},//存放价格和库存
    isGetUser: true,//判断是否授权抖音
    mouldType: 0,
    navigationBarHeight,
    homeSelectedO: imgurl.homeSelectedO.url,
    isshowposter: false, //是否显示分享弹框 
    fenxiang: imgurl.fenxiang1.url,
    fenxiangUrl: imgurl.fenxiang.url,
    clockUrl: imgurl.clock.url,
    yushouUrl: imgurl.yushou.url,
    teljpgUrl: imgurl.teljpg.url,
    closedUrl: imgurl.closed.url,
    quesGouUrl: imgurl.ques_gou.url,
    headbgUrl: imgurl.headbg.url,
    quesBgUrl: imgurl.ques_bg.url,
    close02: imgurl.close02.url,
    share01: imgurl.share01.url,
    fail: imgurl.fail.url,
    wmhome: imgurl.wmhome.url,
    swiperCurrent: 0,
    detailPicture: [],
    coverPicture: [],
    couponList: [],
    data: {
      title: null
    },
    showPage: false,
    questions1: null,
    questions2: null,
    carList: [],
    couponChannelId: null,
    orderId: "",
    hour: null,
    day: null,
    month: null,
    year: null,
    minute: "",
    tempFilePaths: null,
    userInfo: {},
    hasUserInfo: false,
    // canIUse: tt.canIUse('button.open-type.getUserInfo'),
    id: null,
    result: [],
    end_time: null,
    checked: false,
    questionnaire: {},
    questionId: null,
    widthScreen: null,
    moveData: null,
    rotateData: null,
    alphaData: null,
    scaleData: null,
    skewData: null,
    matrixData: null,
    opacity: 0,
    queueData: null,
    zIndex: 11,
    display: "none",
    showbutton: false,
    cardData: null,
    showCardOffer: false,
    isSamePeople: true,
    statusText: '',
    isReceived: false,
    receivedDisabled: false,
    clock: "结束",
    day: "00",
    hour: "00",
    min: "00",
    sec: "00",
    clock02: "00",
    day02: "00",
    hour02: "00",
    min02: "00",
    sec02: "00",
    countdown: "",
    showbutton1: false,
    limitCondition: "",
    minLimit: 0,
    maxLimit: 0,
    dispressEndDate: false,
    barTitle: "",
    activityStatus: "",
    //图文混排
    curHtml: '',
    contentType: 0,
    page: 1,//查询商户优惠券page
    idList: [],
    showBox: false,//手机号授权框
    spuIdObj:{}
  },

  /**
   * 显示分享弹框
   */
  showshare: function () {
    this.setData({
      isshowposter: true,
    })
  },
  getCouponList: function (id) { //获取其他活动
    let that = this;
    let data;
    data = {
      status: 0,
      merchantIds: id,
      pageNum: that.data.page,
      pageSize: 5,
    }
    Http.post({
      url: config.api.listByMerchant,
      data: data
    }).then(res => {
      if (res.data.page.list <= 0) {
        return
      }
      let dataLsit = []
      // dataLsit = that.data.couponList
      dataLsit = res.data.page.list
      dataLsit.map((item, index) => {
        if (item.id == that.data.couponChannelId) {
          dataLsit.splice(index, 1)
        }
      })
      if (that.data.page > 1) {
        let tmpeLsit = that.data.couponList
        tmpeLsit.push(...dataLsit)
        that.setData({
          couponList: tmpeLsit,
        })
      } else {
        that.setData({
          couponList: dataLsit,
        })
      }


      // if (res.data && res.data.qrCode){
      //   that.setData({
      //     qrCode: res.data.qrCode,
      //   })
      // }
    })
      .catch(err => {
        tt.showToast({
          title: err.errMsg,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },

  setPhone(paramData) {//子组件调用这个方法说明手机号已经授权成功
    this.setData({
      showBox: paramData.detail,
    })
    tt.showToast({
      title: '授权成功', // 内容
      icon: 'none', // 图标
      success: (res) => {

      },
      fail: (res) => {

      },
    });
  },
  setBox(paramData) {
    this.setData({
      showBox: paramData.detail
    })
    tt.showToast({
      title: '取消授权', // 内容
      icon: 'none', // 图标
      success: (res) => {

      },
      fail: (res) => {

      },
    });
  },
  /**
   * 隐藏分享弹框
   */
  hidemodal: function () {
    this.setData({
      isshowposter: false,
    })
  },
  /**
   * 显示分享海报
   */
  /* showPoster: function() {
    //跳转到海报生成页
    console.log(this.data.canIUse)

    // return;
    tt.navigateTo({
      url: `/pages/canvas/index?couponChannelId=${this.data.data.id}`
    })
  }, */
  showPoster: function () {
    //跳转到海报生成页
    let that = this;
    Http.get({
      url: config.api.checkUserStatus,
      data: {
        token: app.globalData.token
      }
    }).then(res => {
      tt.navigateTo({
        url: `/pages/canvas/index?couponChannelId=${that.data.data.id}`
      })
    }).catch(err => {
      console.log(err)
      if (err.code == 11004) {
        // 用户昵称未授权
        tt.redirectTo({
          url: `/pages/getuserinfo/index?couponChannelId=${that.data.data.id}&fromflag=poster`
        })
      }
    })

  },
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    });
  },
  gohome(e) {
    console.log(e.currentTarget.dataset.id, "123")
    tt.navigateTo({
      url: `/pages/fillIndent/fillIndent?couponChannelId=${e.currentTarget.dataset.couponchannelid}&couponId=${e.currentTarget.dataset.couponid}&shippingtype=${e.currentTarget.dataset.shippingtype}`,
    })
  },

  gochild(e) {
    let id = e.currentTarget.dataset.id
    tt.navigateTo({
      url: `/pages/coupon/childDetail/childDetail?couponIds=${id}`,
    })
  },
  //获取当前登录用户信息
  getUserInfo: function () {
    let that = this;
    // 获取用户信息
    Http.get({
      url: config.api.getScore,
      data: {}
    })
      .then(res => {
        console.log(res)
        that.getQueryCardStatus()
        if (that.data.cardData.cuserId != res.data.id) {
          console.log(2222, 6666)
          that.setData({
            isSamePeople: false
          })
        }
      })
  },
  //获取卡转赠状态
  getQueryCardStatus() {
    let that = this;
    let param = {
      id: this.data.cardData.couponOrderId,
      cUserId: this.data.cardData.cuserId,
      updateDate: util.formatTime(Number(that.data.cardData.updateDate), "yyyy-MM-dd hh:mm:ss")
    }
    Http.get({
      url: config.api.queryCardStatus,
      data: param
    })
      .then(res => {
        console.log(res, 333333333333)
      })
      .catch(err => {
        that.setData({
          isReceived: true,
          statusText: err.message
        })
      })
  },
  receiveCard() {
    let that = this;
    let param = {
      id: this.data.cardData.couponOrderId,
      cUserId: this.data.cardData.cuserId,
      updateDate: util.formatTime(Number(this.data.cardData.updateDate), "yyyy-MM-dd hh:mm:ss")
    }

    this.setData({
      receivedDisabled: true
    })
    Http.post({
      url: config.api.cardAccept,
      data: param
    })
      .then(res => {
        tt.showToast({
          title: '领取成功！',
          icon: 'none',
          duration: 2000,
          mask: false
        });
        tt.reLaunch({
          url: '/pages/complete/index?couponOrderId=' + this.data.cardData.couponOrderId,
        })
      })
      .catch(err => {
        tt.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
        that.setData({
          receivedDisabled: false
        })
      })
  },
  closeAlert() {
    this.setData({
      showCardOffer: false
    })
  },
  goback: function () {
    tt.reLaunch({
      url: '/index/index',
    })
  },
  /**
   * 点击提交问题单选
   */
  formSubmit: function (e) {
    console.log(e);
    let that = this;
    /**
     * 多选
     */
    if (e.currentTarget.dataset.flags == 'multi') {
      if (that.data.anwserId.length == 0) {
        var answserIs = null
      } else {
        var answserIs = that.data.anwserId.join(",");
      }
    } else if (e.currentTarget.dataset.flags == 'single') {
      var answserIs = e.detail.value;
    }
    console.log(answserIs)
    console.log(e.currentTarget.dataset.questionid)
    Http.post({
      url: config.api.answerQuestion,
      data: {
        answer: answserIs,
        questionId: e.currentTarget.dataset.questionid
      }
    })
      .then(res => {
        that.closeQuestion();
      })
      .catch(err => {
        tt.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },
  /**
   * 多选
   */
  checkboxChange: function (e) {
    console.log(e)
    this.setData({
      anwserId: e.detail.value
    })
  },

  closeQuestion: function () {
    let that = this;
    that.setData({
      display: "none",
      zIndex: 11,
      opacity: 0
    })
    setTimeout(function () {
      that.orderFunc();
    }, 500)
  },
  ifGetUser() {
    Http.get({
      url: config.api.checkUserStatus,
      data: {
        token: app.globalData.token
      }
    }).then(res => {
    }).catch(err => {
      if (err.code == 11004) {
        this.setData({
          isGetUser: false
        })
      }
    })
  },

  gotopay: function (e) {
    let that = this;
    app.globalData.previewFlag = true
    /* 判断是否授权*/
    Http.get({
      url: config.api.checkUserStatus,
      data: {
        token: app.globalData.token
      }
    }).then(res => {
      Http.get({
        url: config.api.checkPhoneStatus,
      }).then(res => {
        tt.showLoading();
        if (e.currentTarget.dataset.type == 51 || e.currentTarget.dataset.type == 50) { 
          tt.navigateTo({
            url: '/pages/integralmall/payIntegcoupondetail/index?couponChannelId=' + that.data.couponChannelId + '&couponId=' + that.data.couponId,
          })
        } else {
          let formId = e.detail.formId ? e.detail.formId : "";
          var discount = e.currentTarget.dataset.discount;
          that.setData({
            queueData: null,
            showbutton: true,
            formId: formId
          })
          Http.get({
            url: config.api.getQuestion,
            data: {
              couponType: JSON.stringify(that.data.data.type)
            }
          }).then(res => {
            tt.hideLoading();
            if (res.data == undefined) {
              // 立即购买
              that.orderFunc(discount);
              that.setData({
                flag: false
              })
            } else if (res.data) {
              var animation = tt.createAnimation({});
              animation.translate((that.data.widthScreen - that.data.widthScreen), 0).scale(1).opacity(1).step({
                duration: 500
              })
              that.setData({
                queueData: animation.export(),
                zIndex: 9,
                opacity: 1,
                display: "block",
                questionnaire: JSON.parse(res.data.content),
                questionId: res.data.id
              });
            }
          }).catch(err => {
            tt.hideLoading();
            tt.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000,
              mask: false
            });
          })
        }
      }).catch(err => {
        app.globalData.type = ''
        app.globalData.skipUrl=""
        app.globalData.skip = 'navigateBack'
        if(app.globalData.ifCongPh==1){
          tt.navigateTo({
            url: '/pages/getPhone/getPhone?skipUrl=1',  
          });
        }else{
          this.setData({
            showBox: true
          })
        }
       
      })
    }).catch(err => {
      app.globalData.type = ''
      if (err.code == 11004) {//未授权抖音
        tt.navigateTo({
          url: `/pages/getuserinfo/getuserinfo?fromflag=coupondetail&couponChannelIdflag=${this.data.couponChannelId}`,

        });
      }
    })




  },
  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一个标识 
      that.getDetail(that.data.couponChannelId, 'endclock');
    }
    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
    }
  },
  /**
   * 获取用户信息
   */
  onLoad(options) {
    
    this.setData({
      mouldType: app.globalData.mouldType,
    })
    let that = this;
    if (options.g) {
      app.globalData.havePlayEd1 = true;
    }
    tt.showLoading({
      title: "加载中..."
    });
    that.setData({
      onshow: false
    })
    if (options && (options.couponChannelId || options.couponIds)) {
      if (options.couponIds) {
        this.setData({
          couponIds: options.couponIds
        })
        that.getDetail(options.couponIds, 'notendclock');
      } else {
        that.getDetail(options.couponChannelId, 'notendclock');
        that.getSupId(options.couponChannelId)
      }


    }
    /**
     * 转赠判断
     */
    if (options.cuserId) {
      this.setData({
        showCardOffer: true,
        cardData: options
      })
      this.getUserInfo()
    }
    that.setData({
      couponChannelId: options.couponChannelId,
      title: that.data.data.title ? that.data.data.title : '',
    });
    if (options.cardType) {
      that.setData({
        cardType: options.cardType
      })
    }
  },
  getHtml(couponChannelId) {
    Http.get({
      url: config.api.couponHtmlDetail,
      data: {
        couponChannelId: couponChannelId
      }
    }).then(res => {
      console.log(res)
      if (res.code == 200 && res.data.html) {
        this.setData({
          curHtml: decodeURI(res.data.html)
        })
        app.globalData.curHtml = this.data.curHtml;
        console.log(app.globalData.curHtml)
      }
    })
  },
  getSupId(id){
    Http.get({
      url:config.api.getSpuid,
      data:{id:id}
    }).then(res=>{
      if(res.data){
        this.setData({
          spuIdObj:res.data
        })
      }
    }).catch(err=>{
      // tt.showToast({
      //   title: err.message,
      //   icon: 'none',
      //   duration: 2000,
      //   mask: false
      // });
    })
  },

  getCouponPriceAndStock(couponChannelId){//获取券价格与库存
    Http.get({
      url:config.api.couponPriceAndStock,
      data:{
        couponChannelId
      }
    }).then(res=>{
      let tempBoj = JSON.parse(res.data)
      console.log(tempBoj,"$");
      this.setData({
        priceAndStockObj:tempBoj
      })
    })
  },
  getCouponMerchant(couponChannelId){//获取适用门店
    Http.get({
      url:config.api.couponMerchant,
      data:{
        couponChannelId:couponChannelId
      }
    }).then(res=>{
      if (res.data && res.data.length) {
        let merchantVoList = res.data
        let idList = []
        merchantVoList.map(item => {
          idList.push(item.id)
        })
        this.setData({
          idList: idList
        })
        this.getCouponList(idList) //获取推荐列表
      }
      this.setData({
        merchantVoList: res.data
      })
    })
  },

  getDetail: function (couponChannelId, flag) {
    let that = this;
    let data = {};
    that.getCouponMerchant(couponChannelId);//获取适用门店
    that.getCouponPriceAndStock(couponChannelId);//获取券价格和库存
    if (that.data.couponIds) {
      data.couponId = couponChannelId
    } else {
      data.couponChannelId = couponChannelId
    }
    var parmer = {
      url: config.api.newCouponDetail,
      data: data
    };
    Http.get(parmer)
      .then(res => {
        //aaa
        if (res.data.contentType != undefined && res.data.contentType == 1) {
          //获取图文展示详情html
          this.setData({
            contentType: res.data.contentType
          })
          this.getHtml(couponChannelId);
        }
        that.setData({
          couponId: res.data.couponId
        })
        that.setData({
          showPage: true
        })
        if (res && res.data && res.data.detailPicture) {
          that.setData({
            detailPicture: JSON.parse(res.data.detailPicture)
          })
        }
        if (res && res.data && res.data.coverPicture) {
          that.setData({
            coverPicture: JSON.parse(res.data.coverPicture)
          })
        }
        if (res && res.data && res.data.conditions) {
          that.setData({
            limitCondition: JSON.parse(res.data.conditions).type
          })
          if (JSON.parse(res.data.conditions).type == 2 && (JSON.parse(res.data.conditions).min || JSON.parse(res.data.conditions).min == 0)) {
            that.setData({
              minLimit: JSON.parse(res.data.conditions).min
            })
          }
          if (JSON.parse(res.data.conditions).type == 2 && (JSON.parse(res.data.conditions).max) || JSON.parse(res.data.conditions).max == 0) {
            that.setData({
              maxLimit: JSON.parse(res.data.conditions).max
            })
          }
        }
        /**
         * 将优惠券优惠卡的详情的BarTitle
         * 设置成券的名称
         */
        // tt.setNavigationBarTitle({
        //   title: res.data.title
        // })
        that.setData({
          barTitle: res.data.title
        })
        var EndTime = res.data.validStartDate;
        var NowTime = new Date().getTime();

        /**
         * activityStatus==0 活动未开始
         * activityStatus==1 活动已开始
         * flag == endclock 说明倒计时已经结束
         */
        if (res.data.endTime && res.data.beginTime) {
          that.setData({
            begin_time: res.data.beginTime,
            end_time: res.data.endTime,
            activityStatus: res.data.actStatus ? res.data.actStatus : ''
          })
          if (res.data.actStatus == 0 && flag != 'endclock') {
            that.countdown(res.data.beginTime);
          } else if (res.data.actStatus != 0 && flag != 'endclock') {
            that.countdown(res.data.endTime);
          } else {
            clearInterval(that.data.setInterval)
          }
          if (res.data.actStatus == 0) {
            var beginTime = util.formatTime(res.data.beginTime, "yyyy-MM-dd hh:mm:ss");
            if (util.timechuo(beginTime).indexOf('-') == 0) {
              that.setData({
                beginTime: "活动已结束",
              });
            } else {
              that.setData({
                beginTime: util.timechuo(beginTime)
              });
            }
          } else {
            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)
              });
            }
          }
        }
        tt.hideLoading();
        that.setData({
          data: res.data,
        });
        if (res.data.type == 10) {
          that.setData({
            salePriceStr: res.data.salePriceStr,
            pickEndDate: util.formatTime(res.data.pickEndDate, "yyyy-MM-dd"),
            pickStartDate: util.formatTime(res.data.pickStartDate, "yyyy-MM-dd"),
            priceStr: res.data.priceStr,
            tailPriceStr: res.data.tailPriceStr,
            origPriceStr: res.data.origPriceStr
          })
        }
        if (res.data.validType == 1) {
          that.setData({
            validStartDate: util.formatTime(res.data.validStartDate, "yyyy-MM-dd"),
            validEndDate: util.formatTime(res.data.validEndDate, "yyyy-MM-dd"),
            pickStartDate: util.formatTime(res.data.pickStartDate, "yyyy-MM-dd"),
            pickEndDate: util.formatTime(res.data.pickEndDate, "yyyy-MM-dd"),
          });
        } else {
          if (res.data.validDays) {
            that.setData({
              validDays: res.data.validDays
            });
          }
        }


        if(res.data.itemGroup){
          let tempObj = this.data.data
          tempObj.itemGroup = JSON.parse(tempObj.itemGroup)
          this.setData({
            data:tempObj
          })
          console.log(this.data.data,"data");
        }
      }).catch(err => {
        tt.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },
  /**
   * 邀请好友继续砍价
   */
  inviteFriend: function (e) {
    let that = this;
    let formId = e.detail.formId;
    that.setData({
      formId: formId,
      showbutton1: true
    })
    that.orderFunc("discount");
  },
  /**
   * 支付订单更新
   */
  payOrderUpdate: (orderId, payOrderId, status, reason, type, _this, composeOrderType) => {
    let that = this;
    // 支付成功
    Http.post({
      url: config.api.payOrderUpdate,
      data: {
        payOrderId: payOrderId,
        composeOrderId: orderId,
        status: status,
        reason: reason
      }
    })
      .then(res => {
        tt.hideLoading()
        // 有价券
        if (!type && type != 'free') {
          tt.navigateTo({
            url: `/pages/order/detail/index?orderId=${orderId
              }`
          });
        } else if (type == 'free') {
          tt.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, composeOrderType);
          }, 2000)
        }
      })
  },
  checkPhoneStatus: function () {
    let that = this;
    Http.get({
      url: config.api.checkPhoneStatus,
      data: {}
    })
      .then(res => {
        console.log(666, '授权成功！')
        that.receiveCard()
      })
      .catch(err => {
        if (err.code == 11005) {
          /**
           * 手机号没有授权，将值传到用户手机号授权的页面
           *
           */
          tt.redirectTo({
            url: "/pages/getphoneInfo/index?path=index&cuserId=" + that.data.cardData.cuserId + "&couponChannelId=" + that.data.cardData.couponChannelId + "&userName=" + that.data.cardData.userName + "&coverImg=" + that.data.cardData.coverImg + "&avatarUrl=" + that.data.cardData.avatarUrl + "&couponOrderId=" + that.data.cardData.couponOrderId + "&updateDate=" + that.data.cardData.updateDate,
          });
        } else if (err.code == 11006) {
          // 用户手机已加密
          tt.redirectTo({
            url: "/pages/phoneinput/phoneinput?path=index&cuserId=" + that.data.cardData.cuserId + "&couponChannelId=" + that.data.cardData.couponChannelId + "&userName=" + that.data.cardData.userName + "&coverImg=" + that.data.cardData.coverImg + "&avatarUrl=" + that.data.cardData.avatarUrl + "&couponOrderId=" + that.data.cardData.couponOrderId + "&updateDate=" + that.data.cardData.updateDate,
          });
        } else {
          tt.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })
  }, 
  // 券包支付

  /**
   * 发起支付
   */
  orderFunc(discount) {
    let that = this;
    Http.get({
      url: config.api.checkUserStatus,
      data: {
        token: app.globalData.token
      }
    }).then(res => {
      Http.get({
        url: config.api.checkPhoneStatus,
        data: {}
      }).then(res => {
          // 发起砍价
          if (discount == 'discount') {
            var data = {
              couponChannelId: "" + that.data.couponChannelId,
              couponId: "" + that.data.couponId,
              formId: "" + that.data.formId,
              press: true
            }
          } else if (discount == 'discount1') {
            var data = {
              couponChannelId: "" + that.data.couponChannelId,
              couponId: "" + that.data.couponId,
              formId: "" + that.data.formId,
              press: false
            }
          } else if (that.data.couponChannelId == null) {
            var data = {
              couponId: "" + that.data.couponId,
              formId: "" + that.data.formId,
            };
          } else {
            var data = {
              couponChannelId: "" + that.data.couponChannelId,
              couponId: "" + that.data.couponId,
              formId: "" + that.data.formId,
            }
          }
          console.log(data, "data")
          let url = ""
          let tempObj;
          let tempArr = []
          if (that.data.data.type == 12) {
            url = config.api.couponPackageSave
            tempObj = {
              signleOrder: {
                couponChannelId: "" + that.data.couponChannelId,
                couponId: "" + that.data.couponId,
                formId: "" + that.data.formId,
              },
              count: "1"
            }
            tempArr.push(tempObj)
          } else {
            url = config.api.orderSave
          }
          /**
           * orderSave 下单
           */
          return Http.post({
            url: url,
            data: that.data.data.type == 12 ? JSON.stringify(tempArr) : data
          });
        }).catch(err => {
          tt.hideLoading()
          that.setData({
            showbutton: false,
            showbutton1: false
          })
          if (err.code == 2011) {
            tt.showToast({
              title: "商户信息没找到",
              image: './../../../assets/images/fail.png',
              duration: 2000,
              mask: false
            });
          } else if (err.code == 2013) {
            tt.showToast({
              title: "商户信息禁用",
              image: './../../../assets/images/fail.png',
              duration: 2000,
              mask: false
            });
          } else if (err.code == 3000) {
            tt.showToast({
              title: "库存不足",
              image: './../../../assets/images/fail.png',
              duration: 2000,
              mask: false
            });
          } else if (err.code == 3001) {
            tt.showToast({
              title: "您已超过限购",
              image: './../../../assets/images/fail.png',
              duration: 2000,
              mask: false
            });
          } else if (err.code == 3002) {
            tt.showToast({
              title: "订单失败",
              image: './../../../assets/images/fail.png',
              duration: 2000,
              mask: false
            });
          } else if (err.code == 3003) {
            tt.showToast({
              title: "订单不存在",
              image: './../../../assets/images/fail.png',
              duration: 2000,
              mask: false
            });
          } else if (err.code == 3004) {
            tt.showToast({
              title: "订单不存在",
              image: './../../../assets/images/fail.png',
              duration: 2000,
              mask: false
            });
          } else if (err.code == 4003) {
            tt.showToast({
              title: "卡券已作废",
              image: './../../../assets/images/fail.png',
              duration: 2000,
              mask: false
            });
          } else if (err.code == 3012) {
            that.getUnPaidOrder(that.data.couponId);
          } else if (err.code == 11005) {
            /**
             * 将值传到用户手机号授权的页面
             *
             */
            tt.redirectTo({
              url: "/pages/getphoneInfo/index?couponChannelId=" +
                that.data.couponChannelId
            });
          } else if (err.code == 11006) {
            // 用户手机已加密
            tt.redirectTo({
              url: "/pages/phoneinput/phoneinput?couponChannelId=" +
                that.data.couponChannelId
            });
          } else {
            tt.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000,
              mask: false
            });
          }
        }).then(res => {
          if (discount != 'discount') {
            if (typeof (res) != "undefined") {
              let orderId = "" + res.data.mainOrderId;
              that.setData({
                orderId: orderId,
                composeOrderType: res.data.composeOrderType
              });
              if (res.data.payment > 0) {
                // 支付金额不为0
                /**
                 * 支付订单创建
                 */
                Http.post({
                  url: config.api.payOrderCreate,
                  data: {
                    orderId: orderId,
                    composeOrderType: res.data.composeOrderType
                  }
                }).then(res => {
                  var payOrderId = "" + res.data.outOrderNo;
                  tt.hideLoading();
                  tt.pay({
                    service: 5,
                    orderInfo: {
                      order_id: res.data.orderId,
                      order_token: res.data.token,
                    },
                    success: res => {
                      tt.showLoading({
                        title: '订单正在处理中...',
                      })
                      if (res.code === 0) {
                        that.payOrderUpdate(that.data.orderId, payOrderId, 1, '', '', that, that.data.composeOrderType);
                        if (res.errMsg == "requestPayment:ok") {
                          /**
                           * 用户支付成功以后跳转到券包列表
                           */
                          if (that.data.cardType == 100) {
                            tt.setStorage({
                              key: 'couponNum2',
                              data: "couponNum2"
                            })
                          } else if (that.data.data.type != 5 && that.data.cardType != 100) {
                            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 => {
                      tt.hideLoading();
                      /**
                       * 支付失败，需要更新订单的状态
                       */
                      that.payOrderUpdate(that.data.orderId, payOrderId, 2, '', 'fail', that, that.data.composeOrderType);
                      that.setData({
                        showbutton: false
                      })
                      return;
                    },
                    complete: res => { }
                  });
                  /// End payment  --------
                })
                  .catch(err => {
                    tt.hideLoading();
                    tt.showToast({
                      title: err.message,
                      icon: 'none',
                      duration: 2000,
                      mask: false
                    });
                  })
              } else {
                // 免费券
                that.payOrderUpdate(orderId, "0", 1, '', 'free', that, that.data.composeOrderType);
                if (that.data.cardType == 100) {
                  tt.setStorage({
                    key: 'couponNum2',
                    data: "couponNum2"
                  })
                } else if (that.data.data.type != "5" && that.data.cardType != 100) {
                  tt.setStorage({
                    key: 'couponNum',
                    data: "couponNum"
                  })
                }
              }
            }
          } else {
            if (res) {
              tt.navigateTo({
                url: `/pages/bargain/bargainDatail/bargainDatail?orderId=${res.data.mainOrderId}&composeOrderType=${res.data.composeOrderType}`,
              })
            }
          }
        })
    }).catch(err => {
      console.log(err)
      if (err.code == 11004) {
        tt.redirectTo({
          url: `/pages/getuserinfo/index?fromflag=coupondetail&couponChannelIdflag=${that.data.couponChannelId}`,
        })
      } else {
        tt.showToast({
          title: err.message,
          icon: "none",
          duration: 2500
        })
      }
    })
  },
  // 获得未支付的订单
  getUnPaidOrder(couponId) {
    let that = this;
    Http.get({
      url: config.api.getUnPaidOrder,
      data: {
        couponId: couponId
      }
    }).then(res => {
      that.setData({
        disOrderNumber: res.data.orderNumber,
        composeOrderType: res.data.composeOrderType
      })

      if (res.data && res.data.pressEndDate) {
        that.setData({
          dispressEndDate: true
        })
      } else {
        that.setData({
          dispressEndDate: false
        })
      }
      if (that.data.dispressEndDate) {
        tt.showModal({
          title: '提示',
          content: "您有未支付订单,请到“我的-我的砍价”进行支付",
          confirmText: "我的砍价",
          success: function (res) {
            if (res.confirm) {
              tt.navigateTo({
                url: `/pages/bargain/bargainDatail/bargainDatail?orderId=${that.data.disOrderNumber}&composeOrderType=${that.data.composeOrderType}`,
              })
            }
          }
        })
      } else {
        tt.showModal({
          title: '提示',
          content: '您有未支付订单,请先进行支付',
          confirmText: "去支付",
          success: function (res1) {
            if (res1.confirm) {

              if (that.data.composeOrderType > 0) {//券包
                tt.navigateTo({
                  url: `/pages/order/detail/index?orderId=${res.data.composeOrderId}`,
                })
              } else {
                tt.navigateTo({
                  url: `/pages/order/detail/index?orderId=${res.data.composeOrderId}`,
                })
              }

            }
          }
        })
      }
    }).catch(error => {
      tt.showToast({
        title: error.message,
        icon: "none",
        duration: 3000
      })
    })
  },

  
  onShow() {
    this.ifGetUser()//判断是否授权抖音
    this.setData({
      mouldType: app.globalData.mouldType,
      showbutton: false,
      showbutton1: false
    })
    if (this.data.end_time && this.data.activityStatus != 0) {
      this.countdown(this.data.end_time)
    } else if (this.data.begin_time && this.data.activityStatus == 0) {
      this.countdown(this.data.begin_time)
    }
  },
  onUnload: function () {
    let that = this;
    clearInterval(that.data.setInterval)
  },
  onHide: function () {
    let that = this;
    clearInterval(that.data.setInterval)
  },
  onShareAppMessage: function (options) {
    app.globalData.previewFlag = true
    var that = this;
    console.log(options)
    var shareObj = {
      title: that.data.data.title,
      path: `/pages/index/index?couponChannelId=${that.data.couponChannelId}`,
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok') { }
      },
      fail: function (err) {
        // if (err.errMsg == 'shareAppMessage:fail cancel') { } else if (err.errMsg == 'shareAppMessage:fail') { }
      }
    };
    // 来自页面内的按钮的转发
    if (options.from == 'button' && options.channel != 'video') {
      var eData = options.target.dataset.id;
      shareObj.path = `/pages/index/index?couponChannelId=${eData}&frommd=JC`;

    } else
      if (options.channel == 'video') {
        // return {
        // channel: 'video',   // 必写 video
        // 　　　　templateId: '',　　　// 分享的模版 id （如果未设置就是默认，下面会说如何设置）
        // title: `${that.data.barTitle}`,　　　　　// 分享的标题
        // desc: `${that.data.data.dyTitle}`,　　　　　// 分享的内容介绍目前没有用
        // 　　　　path: `/pages/index/index`,　　// 分享的路径
        // extra: {
        //     videoTopics: [ that.data.data.dyTitle] // 只有抖音才会有的属性
        // },
        // }
        shareObj.channel = 'video';
        shareObj.title = `${that.data.data.title}`;
        shareObj.extra = {
          spu_id: that.data.spuIdObj.spuId
        }
      }
    console.log(shareObj)

    // 返回shareObj
    return shareObj;
  },


//   onShareAppMessage: function(e) {
//     console.log("onShareAppMessage", e);
//     return {
//         channel: 'video',
//         title: "测试小程序分享",
//         desc: "这是默认的分享文案，用户可以直接发送，也可以在发布器内修改",
//         extra: {
//             spu_id:"7091460633887279111"    //开发者在抖音开放平台设置的商品id
//         },
//         success: function(e) {
//             console.log("分享成功");
//         },
//         fail: function(e) {
//             console.log(e,"分享成功失败")
//         }
//     };
// },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.getDetail(this.data.couponChannelId);
    tt.stopPullDownRefresh()
  },
  onReachBottom: function () {
    this.setData({
      page: this.data.page + 1
    })

    if (this.data.idList.length > 0) {
      this.getCouponList(this.data.idList)
    }
  }
});