const util = require('../../../utils/util.js');
const app = getApp();
Page({
  data: {
    showOrderNo: false,
    showGoodsRecom: false,
    showAddress: false, //地址
    imgPath: util.config.imgPath,
    imgUrl: util.config.imgUrl,
    query: {
      orderid: '',
      otype: 0,
      presellStatus: 0
    },
    changeMeal_oid: '',
    info: {},
    percent: 0,
    loadingSuc: true,
    npsOptons: {},
    npsStatus: false, //nps组件是否显示
    isGet: true,
    prevpagePath: '',
    iconView: false,
    showChat: false,
    showSku: false, //换场次弹窗
    invitefbtn: true, //是否显示邀请海报按钮
    refundShow: false,
    type: 0,
    codeShow: false,
    orderInfo: {},
    oid: "",
    atype: 0,
    moreIsShow: false, //更多图片是否显示
    selectIsShow: false, //更多下拉框是否显示
  },
  // 预付信息  orderStatus  1-待付款 2-已付款 3-退款/售后 4-待付尾款 5-订金失效
  onLoad(query) {
    console.log(query)
    this.setData({
      query
    });
    let pages = getCurrentPages();
    let prevpage = pages[pages.length - 2];
    this.setData({
      prevpagePath: prevpage.route
    })
  },
  onUnload() { //由付款页跳转至当前页面的，通过左上角返回至活动详情页
    if (this.data.prevpagePath == 'pages/product/buy/index') {
      let url = '';
      if (this.data.info.atype == 0) {
        url = `/pages/product/activity/index?aid=${this.data.info.aid}`;
      } else {
        url = `/pages/product/goods/detail?aid=${this.data.info.aid}`;
      }
      wx.reLaunch({
        url: url
      })
    }
  },
  onShow() {
    if (this.data.isGet) {
      this.getData();
    }
  },
  showAddressPopup() {
    this.setData({
      showOrderNo: true
    })
  },
  copyAddress(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
  closeOrderNo() {
    this.setData({
      showOrderNo: false
    })
  },
  subOrderNo(e) {
    let data = e.detail,
      that = this;
    util.ajax({
      func: "v2/order/refund/express/save",
      data: data,
      method: 'POST',
    }, function (res) {
      if (res.code == 0) {
        util.showTips(res.reason);
        setTimeout(() => {
          that.closeOrderNo()
          // that.getData();
        }, 500);
      } else {
        util.showTips(res.reason);
      }
    })
  },
  // 规则弹框
  showFund() {
    // if(this.data.orderInfo.refundRule==1){
    //   this.data.type=this.data.orderInfo.refundRule
    // }
    this.setData({
      refundShow: true,
      type: this.data.orderInfo.refundRule,
      // type:3,
      showSku: false
    })
  },
  closeRefund() {
    this.setData({
      refundShow: false
    })
  },
  isOK() {
    this.setData({
      codeShow: false
    })
  },
  showCode() {
    this.setData({
      codeShow: true,
      showSku: false
    })
  },
  // 换场次
  confirmChange(e) {
    console.log(this.data.orderInfo);
    let that = this
    util.ajax({
      func: "v2/order/getRefundPriceByOid",
      data: {
        "oid": that.data.oid
      }
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        console.log("confirmChange" + "执行了" + e);
        let data = {};
        data.newAlipayId = e.detail ? e.detail : '';
        data.oid = that.data.changeMeal_oid;
        data.password = that.data.info.subOrders[0].password
        data.priceInfo = that.data.orderInfo
        console.log(data);
        util.ajax({
          func: "v2/order/change/audit",
          data,
          method: 'POST',
          load: false
        }, function (res) {
          if (res.code == 0) {
            util.showTips('已发起申请，请耐心等待宝大大审核~');
            that.setData({
              showSku: false,
              changeMeal_oid: ''
            })
            that.getData();
          } else {
            util.showTips(res.reason);
          }
        })
      } else if (res.code == -10) {
        util.showTips('不满足更换场次要求，请联系宝大大处理')
      } else {
        util.showTips(res.reason);
      }
    })

  },
  // 活动评价/修改评价
  actEvaluate(e) {
    let val = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: '/pages/order/comment/comment?orderid=' + this.data.info.orderid + '&otype=' + this.data.query.otype + (val == 1 ? '&act=edit' : ''),
    })
  },
  // 修改追评/追加评价
  editEvaluate(e) {
    wx.navigateTo({
      url: '/pages/order/addComment/addComment?orderid=' + this.data.info.orderid +
        '&otype=' + this.data.query.otype +
        '&act=' + (this.data.info.comment.additional == 1 ? 'edit' : ''),
    })
  },
  // 跳转首页
  jumpPage() {
    wx.reLaunch({
      url: '/pages/home/index',
    })
  },
  // 点击联系客服弹窗
  showfixedChat() {
    this.setData({
      showChat: true
    })
  },
  // 修改订单信息
  editOrderDetail() {
    if ( //和修改信息按钮同样判断逻辑
      this.data.info.atype != '1' &&
      this.data.info.orderStatus == 2 &&
      this.data.info.detailStopUpdate != 1 &&
      (this.data.info.waitComment != 2 || (this.data.info.comment.additional == 1 && this.data.info.comment.modified == 1))
    ) {
      wx.navigateTo({
        url: '/pages/order/editOrderDetail/index?orderId=' + this.data.info.orderid,
      })
    }
  },
  // 点击更多
  showMore() {
    this.setData({
      moreIsShow: !this.data.moreIsShow,
      selectIsShow: !this.data.selectIsShow
    })
    // console.log(this.data.selectIsShow);
    // this.setData({showChat:true})
  },
  // 开票页面
  invoicing() {
    console.log(this.data.info);
    if (!this.data.info.verify) {
      util.showTips('需验票后3天才可申请开票')
    } else {
      wx.navigateTo({
        url: '/pages/order/invoicing/index',
      })
    }
  },
  // 客服
  customer() {
    this.setData({
      showChat: true
    })
  },
  // 修改邮寄地址
  chooseAddress() {
    this.setData({
      showAddress: true
    })
  },
  // 提交地址
  submitAddress(e) {
    let that = this,
      data = e.detail,
      info = that.data.info;
    this.setData({
      'info.mailAddress': data.name + ' ' + data.mobile + ' ' + data.provincial + ' ' + data.address
    });
    util.ajax({
      func: "v2/order/mail/address/save",
      data: {
        'orderid': info.orderid,
        'mailAddress': info.mailAddress
      },
      method: 'POST'
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        util.showTips(res.reason);
      } else {
        util.showTips(res.reason);
      }
    })
  },
  // 关闭地址弹窗
  closeAddress(e) {
    this.setData({
      showAddress: false
    })
  },
  close(e) { //关闭nps
    this.setData({
      npsStatus: false
    });
    this.getData();
  },
  getData(val) {
    console.log(val);
    let that = this;
    let data = {};
    if (!util.isEmpty(that.data.query.orderid)) {
      data.orderid = that.data.query.orderid;
    }
    if (!util.isEmpty((val || that.data.query.presellStatus))) {
      data.presellStatus = val || that.data.query.presellStatus
    }
    if (!util.isEmpty(that.data.query.otype)) {
      data.otype = that.data.query.otype
    }
    console.log(data);
    util.ajax({
      func: "v2/order/detail",
      data,
      load: false
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        that.setData({
          atype: res.data.atype
        })
        let datas = res.data;
        // datas.totalFeeStr = datas.totalFee;
        datas.timeContrast = util.timeContrast(datas.stopBuy);
        // if (datas.mdiscount > 0) datas.totalFeeStr += " - " + datas.mdiscount + "(会员折扣)";
        // if (datas.ldiscount > 0) datas.totalFeeStr += " - " + datas.ldiscount + "(早鸟)";
        // if (datas.voucher > 0) datas.totalFeeStr += " - " + datas.voucher + "(现金券)";
        // if (datas.bonus > 0) datas.totalFeeStr += " - " + datas.bonus + "(红包)";
        // if (datas.coin > 0) datas.totalFeeStr += " - " + datas.coin + "(钱包)";
        // if (datas.accountBalance > 0) datas.totalFeeStr += " - " + datas.accountBalance + "(账户余额)";
        // if (datas.mdiscount > 0 || datas.voucher > 0 || datas.bonus > 0 || datas.ldiscount > 0 || datas.coin > 0 || datas.accountBalance > 0) {
        //   datas.totalFeeStr += " = " + datas.price + "元";
        // } else {
        //   datas.totalFeeStr = datas.totalFee + "元";
        // }

        if (!util.isEmpty(datas.mailAddress)) {
          var info = datas.mailAddress.split(" ");
          datas.mail = {};
          datas.mail.name = info[0] || "";
          datas.mail.postMobile = info[1] || "";
          datas.mail.province = info[2] || "";
          datas.mail.address = datas.mail.province.replace("/", "") + info[3];
        }
        if (datas.comment) {
          datas.comment.tag = datas.comment.content.match(/#([^#]+)#/g) ? datas.comment.content.match(/#([^#]+)#/g).join("") : '';
          datas.comment.content = datas.comment.content.replace(/#([^#]+)#/g, "").replace(/<br\/>/g, '\n');
          if (datas.comment.additionalComment.content) {
            datas.comment.additionalComment.content = datas.comment.additionalComment.content.replace(/<br\/>/g, '\n')
          }
        }
        if (datas.saleTime && datas.presellPaymentDeadline) {
          datas.startTime = util.formatDate(util.formatUnixtimestamp(datas.saleTime), 'MM月dd日 hh:mm', false);
          datas.endTime = util.formatDate(util.formatUnixtimestamp(datas.presellPaymentDeadline), 'MM月dd日 hh:mm', false);
        }
        let num = 0,
          length = (datas.groupinfo.discount && !util.isEmpty(datas.groupinfo.discount.users)) ? datas.groupinfo.discount.users.length : 0;
        if (length > 0) {
          datas.groupinfo.discount.users.forEach(el => {
            num = el.status == 4 ? num++ : num;
            if (el.status == 4) {
              num++;
            }
            that.setData({
              iconView: num == 0 ? false : true
            });
          });
        }
        that.setData({
          info: datas
        });
        console.log(that.data.info);
        that.getGoodsRecommend()
        if (datas.groupinfo.gstatus == 0 && datas.groupinfo.discount && datas.groupinfo.discount.status == 0 && datas.groupinfo.discount.deadline > 0) {
          that.data.info.groupinfo.discount.deadline = that.data.info.groupinfo.discount.deadline - new Date().getTime();
          that.updateTime();
        }
      } else
        util.showTips(res.reason);
    });
  },
  getGoodsRecommend() {
    let that = this;
    util.getGoodsRecommend(this.data.info.aid).then(res => {
      that.setData({
        showGoodsRecom: res
      })
    })
  },
  closeSku() {
    this.setData({
      showSku: false,
      changeMeal_oid: ''
    });
  },
  // 获取订单信息
  OrderInfo(oid) {
    // console.log(this.data.oid);
    let that = this
    util.ajax({
      func: "v2/order/getRefundPriceByOid",
      data: {
        "oid": oid
      }
    }, function (res) {
      console.log(res);
      if (res.code == 0) {
        that.setData({
          orderInfo: res.data,
          showSku: true,
          changeMeal_oid: oid
        })
      } else if (res.code == -10) {
        util.showTips('不满足更换场次要求，请联系宝大大处理');
        that.setData({
          showSku: false,
          changeMeal_oid: oid
        });
      } else {
        util.showTips(res.reason);
        that.setData({
          showSku: false,
          changeMeal_oid: oid
        });
      }
    })
  },
  // 换场次
  changeMeals(e) {
    let status = e.currentTarget.dataset.status,
      oid = e.currentTarget.dataset.oid;
    if (status == 1) {
      this.setData({
        showSku: false
      });
      util.showTips('已提交申请，请耐心等待宝大大审核~');
      return false;
    } else {
      this.setData({
        oid: e.currentTarget.dataset.oid
      })
      this.OrderInfo(e.currentTarget.dataset.oid)

    }
    // this.setData({showSku:true,changeMeal_oid:oid});
  },
  cancelOrder(e) {
    let that = this,
      val = e.target.dataset.presellstatus;
    util.ajax({
      func: "order/cancel",
      data: {
        orderid: that.data.info.orderid
      }
    }, function (res) {
      if (res.code == 0) {
        if (val != 2) {
          if (that.data.prevpagePath == 'pages/product/buy/index') {
            wx.reLaunch({
              url: '/pages/product/activity/index?aid=' + that.data.info.aid
            })
          } else {
            wx.navigateBack();
          }
        } else {
          that.getData(1)
        }
      } else {
        utils.showTips(res.reason);
      }
    })
  },

  // 跳转至表单详情页（支付尾款）
  jumpBalancePayment(e) {
    let data = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/product/balancePayment/balancePayment?aid=' + data.aid + '&otype=' + data.otype + '&orderid=' + data.orderid + '&presellstatus=' + data.presellstatus + '&military=' + data.military + '&campSex=' + data.campSex,
    })
  },
  previewImage(e) {
    let index = e.currentTarget.dataset.index,
      id = e.currentTarget.dataset.id,
      comments = [],
      datas = this.data.info;
    if (id == 0) { //评论
      comments = datas.comment.images;
    } else { //追加评论
      comments = datas.comment.additionalComment.images;
    }
    wx.previewImage({
      current: comments[index], // 当前显示图片的http链接
      urls: comments // 需要预览的图片http链接列表
    })
  },
  toDetail() {
    let url = '';
    if (this.data.info.atype == 0) {
      url = `/pages/product/activity/index?aid=${this.data.info.aid}`;
    } else {
      url = `/pages/product/goods/detail?aid=${this.data.info.aid}`;
    }
    wx.navigateTo({
      url: url,
    })
  },
  goPay() {
    let that = this,
      btype = 0;
    util.WXPay({
      orderid: this.data.info.orderid,
      btype: that.data.query.presellStatus == 2 ? 0 : that.data.query.presellStatus
    }, this.data.info.aid, this.data.info.title, ).then(function () {

      that.data.query.otype = 2;
      that.setData({
        query: that.data.query
      });
      that.getData();
    }, function (msg) {
      utils.showTips(msg);
    })
  },
  trip(e) {
    let datas = this.data.info
    wx.reportAnalytics('click_news', {
      aid: datas.aid,
      title: datas.title,
    });
    wx.navigateTo({
      url: '/pages/order/trip/trip?orderid=' + datas.orderid + '&refundpwd=' + e.currentTarget.dataset.refundpwd
    })
  },
  scheduling(e) {
    let oid = e.currentTarget.dataset.oid,
      optionId = e.currentTarget.dataset.optionid;
    wx.navigateTo({
      url: '/pages/order/scheduling/scheduling?oid=' + oid + '&optionId=' + optionId,
    })
  },
  refund(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index
    let datas = this.data.info,
      value = e.currentTarget.dataset;
    console.log(value);
    console.log(this.data.info);
    let info = this.data.info
    let that = this
    // console.log(that.data.info.subOrders[index].oid);

    // v2/order/getRefundPriceByOid
    if (that.data.atype != "1") {
      util.ajax({
        func: "v2/order/getRefundPriceByOid",
        data: {
          oid: that.data.info.subOrders[index].oid,
        }
      }, function (res) {
        console.log(res);
        if (res.code == 0) {
          wx.navigateTo({
            url: '/pages/order/refund/refund?orderid=' + datas.orderid + (value.password ? '&refundpwd=' + value.password : '') + '&refundStatus=' + value.status + (datas.groupinfo && datas.groupinfo.groupid ? ('&groupid=' + datas.groupinfo.groupid) : '') + '&index=' + value.index + '&oid=' + that.data.info.subOrders[index].oid
          })
        } else {
          util.showTips(res.reason);
        }

      })

    } else {
      wx.navigateTo({
        url: '/pages/order/Copyrefund/Copyrefund?orderid=' + datas.orderid + (value.password ? '&refundpwd=' + value.password : '') + '&refundStatus=' + value.status + (datas.groupinfo && datas.groupinfo.groupid ? ('&groupid=' + datas.groupinfo.groupid) : '') + '&index=' + value.index + "&atype=" + that.data.atype
      })
    }

    wx.reportAnalytics('order_refund', {
      aid: datas.aid,
      title: datas.title,
    });

  },
  cancelRefund(e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定取消退款',
      success: function (res) {
        if (res.confirm) {
          wx.reportAnalytics('cancel_refund', {
            aid: that.data.info.aid,
            title: that.data.info.title,
          });
          util.ajax({
            func: "order/cancel_refund",
            data: {
              orderid: that.data.info.orderid,
              password: e.currentTarget.dataset.password || ""
            }
          }, function (res) {
            if (res.code == 0) {
              if (res.data.count <= 0) {
                wx.navigateBack();
              } else {
                that.getData();
              }
            } else {
              util.showTips(res.reason);
            }
          })
        }
      }
    })
  },
  errorImg() {
    this.data.info.logo = "/images/noimg.png";
    this.setData({
      info: this.data.info
    });
  },
  lookContract(e) {
    let datas = this.data.info,
      that = this;
    let type = e.currentTarget.dataset.type
    console.log(type);
    wx.reportAnalytics('look_contract', {
      aid: datas.aid,
      title: datas.title,
    });
    const downloadTask = wx.downloadFile({
      url: e.currentTarget.dataset.url,
      success: function (res) {
        console.log(res)
        if (res.statusCode === 200) {
          var filePath = res.tempFilePath
          if (type == "电子合同") {
            wx.openDocument({
              filePath: filePath,
              fileType: 'pdf',
            })
          } else if (type == "行程单") {
            wx.openDocument({
              filePath: filePath,
              fileType: 'docx',
            })
          }
        } else {
          that.setData({
            loadingSuc: false
          });
        }
      },
      fail: function (res) {
        that.setData({
          loadingSuc: false
        });
        util.showTips('合同链接失效，请联系宝大大处理。');
      }
    })
    downloadTask.onProgressUpdate((res) => {
      that.setData({
        percent: res.progress
      });
    })
  },
  layer() {
    this.setData({
      percent: 0
    })
  },
  qrcode(e) {
    let data = e.currentTarget.dataset;
    if (data.status == 1) {
      wx.navigateTo({
        url: '/pages/order/qrcode/index?password=' + data.password,
      });
    }
  },
  updateTime() {
    let self = this,
      data = this.data.info,
      lag = Math.floor(data.groupinfo.discount.deadline / 1000);
    data.updateTime = {};
    data.updateTime.second = Math.floor(lag % 60);
    data.updateTime.minite = Math.floor((lag / 60) % 60);
    data.updateTime.hour = Math.floor(lag / 3600);
    data.updateTime.day = Math.floor((lag / 3600) / 24);
    data.updateTime.hour = isTimeLeng(data.updateTime.hour);
    data.updateTime.minite = isTimeLeng(data.updateTime.minite);
    data.updateTime.second = isTimeLeng(data.updateTime.second);
    data.groupinfo.discount.deadline = data.groupinfo.discount.deadline - 1000;
    self.setData({
      info: data
    });
    clearTimeout(updateTimer);
    let updateTimer = setTimeout(function () {
      self.updateTime();
    }, 1000);

    function isTimeLeng(val) {
      var s = val.toString();
      return s.length == 1 ? "0" + val : val;
    }
  },
  // 拼团邀请
  inviteGroup(e) {
    this.setData({
      show: true,
      invitefbtn: e.currentTarget.dataset.invitefbtn == '0' ? true : false
    })
  },
  onShareAppMessage(res) {
    let datas = this.data.info,
      article = '';
    let path = '';
    if (res.from === 'button') {
      let str = [];
      str.push('aid=' + datas.aid)
      str.push('orderid=' + datas.orderid)
      str.push('invite=' + app.globalData.userInfo.code)
      str.push('sharesid=' + datas.sid)
      str.push('sharepid=' + datas.pid)
      str.push('sharer=' + app.globalData.userInfo.nickname)
      if (!util.isEmpty(datas.groupinfo.groupid) && datas.groupinfo.groupid != 'null' && datas.groupinfo.groupid != 'undefined' && datas.groupinfo.groupbook == 1 && datas.subOrders[0].status != 15) {
        str.push('groupid=' + datas.groupinfo.groupid)
      }
      path = '/pages/product/activity/index?' + str.join('&');
      wx.reportAnalytics('order_share', {
        aid: datas.aid,
        title: datas.title,
      });
    } else {
      path = '/pages/home/index'
    }
    if (!util.isEmpty(datas.sid) && !util.isEmpty(datas.pid) && util.isEmpty(datas.groupinfo.groupid)) {
      article = app.globalData.userInfo.nickname + '已报名并邀请你一起参与' + datas.title
    } else {
      article = (datas.groupbook != -1 ? '约吗？快来和我家孩子一起拼团挑战' : '') + datas.title;
    }
    return {
      title: article,
      path: path,
      imageUrl: '../images/share.png'
    }
  }
})