// packageD/auction/auction/auction_good/auction_good.js
var app = getApp();
import utils from "../../../../utils/util.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showone: false,
    showthr_Mun: "",
    // bid: 200,
    in_status: 1,
    showphone: false,
    goods_id: "",
    id: "",
    now: "",
    // 海报
    posterShow: false,
    // 余额支付状态
    isclick: true,
    //计算后的倒计时
    countDownObj: {
      day: "00",
      hou: "00",
      min: "00",
      sec: "00",
    },
    password: "",
    setIntervalMth: '',
    is_last_bidder: false,
    isEnd:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      now: String(Date.parse(new Date())).substring(0, 10),
    });
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      console.log(scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "member_id") {
            this.setData({
              id: chil_arr[1],
            });
          }
          if (chil_arr[0] == "id") {
            this.setData({
              goods_id: chil_arr[1],
            });
          }
        }
      }
    }
    if (options.id) {
      this.setData({
        goods_id: options.id,
      });
    }
    if (options.member_id) {
      this.setData({
        id: options.member_id,
      });
    }
    this.getStatus();
  },
  is_password(e) {
    console.log(e.detail.value);
    this.setData({
      password: e.detail.value,
    });
  },
  onChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  goto() {
    wx.navigateBack({
      delta: 1,
    });
  },
  gotoCart() {
    wx.reLaunch({
      url: "/packageG/index/index",
    });
  },
  gotoMY() {
    wx.reLaunch({
      url: "/packageG/member_v2/member_v2",
    });
  },
  showthr_del() {
    if (Number(Number(this.data.price) - Number(this.data.auction.mini_markup)) < this.data.price) {
      wx.showToast({
        title: "出价不能低于当前价格",
        icon: "none",
        duration: 1000,
      });
      return;
    }
    this.setData({
      price: Number(Number(this.data.price) - Number(this.data.auction.mini_markup)).toFixed(2),
    });
  },
  toRecord() {
    wx.navigateTo({
      url: "/packageD/auction/auction/auction_record/auction_record",
    });
  },
  showthr_add() {
    this.setData({
      price: Number(Number(this.data.price) + Number(this.data.auction.mini_markup)).toFixed(2),
    });
  },
  isprice(e) {
    console.log(e.detail.value);
    this.setData({
      showthr_Mun: e.detail.value,
    });
    console.log(this.data.showthr_Mun);
  },
  isCoverLayer_passwork() {
    wx.showModal({
      title: "提示",
      content: "不输入店铺密码无法查看拍品详情",
      success(res) {
        if (res.confirm) {
          console.log("用户点击确定");
          wx.navigateBack({
            delta: 1,
          });
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  // 店铺密码确认
  confirm() {
    let json = {
      art: "verifyPassword",
      auction_id: this.data.id,
      passwd: this.data.password,
    };
    var that = this;
    let urlStr = app.getNetAddresss("plugin.auction.api.index.getAuctionData");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            showone: false,
          });
          that.getStatus();
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  isCoverLayer() {
    this.setData({
      // showone: false,
      showtwo: false,
      showthr: false,
      showphone: false,
    });
  },
  celquxiao() {
    this.setData({
      // showone: false,
      showtwo: false,
      showphone: false,
    });
  },
  gotoPay() {
    console.log("去支付");
  },
  goMybtn() {
    wx.navigateTo({
      url: "/packageD/auction/auction-mine/my_index/my_index",
    });
  },
  gomyshop(e) {
    wx.navigateTo({
      url: "/packageD/auction/auctioneer-shop/auctioneer_shop/auctioneer_shop?id=" +
        this.data.id,
    });
  },
  //点击开始时的时间
  // timestart: function (e) {
  //   var _this = this;
  //   _this.setData({
  //     timestart: e.timeStamp,
  //   });
  // },

  // //点击结束的时间
  // timeend: function (e) {
  //   var _this = this;
  //   _this.setData({
  //     timeend: e.timeStamp,
  //   });
  // },
  // 保存图片
  saveImg() {
    wx.previewImage({
      current: 'this.data.posterImg.image_url', // 当前显示图片的http链接
      urls: [this.data.posterImg.image_url] // 需要预览的图片http链接列表
    });
    // var _this = this;
    // var times = _this.data.timeend - _this.data.timestart;
    // if (times > 300) {
    // wx.getSetting({
    //   success(res) {
    //     if (!res.authSetting["scope.writePhotosAlbum"]) {
    //       wx.authorize({
    //         scope: "scope.writePhotosAlbum",
    //         success() {
    //           console.log("授权成功");
    //         },
    //       });
    //     }
    //   },
    // });
    // var imgSrc = this.data.posterImg.image_url;
    // wx.downloadFile({
    //   url: imgSrc,
    //   success: function (res) {
    //     console.log(res);
    //     //图片保存到本地
    //     wx.saveImageToPhotosAlbum({
    //       filePath: res.tempFilePath,
    //       success: function (data) {
    //         wx.showToast({
    //           title: "保存成功",
    //           icon: "none",
    //           duration: 2000,
    //         });
    //       },
    //       fail: function (err) {
    //         console.log(err);
    //         if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
    //           console.log("当初用户拒绝，再次发起授权");
    //           wx.openSetting({
    //             success(settingdata) {
    //               if (settingdata.authSetting["scope.writePhotosAlbum"]) {
    //                 wx.showToast({
    //                   icon: "none",
    //                   title: "获取权限成功,再次长按保存图片",
    //                   duration: 1500,
    //                 });
    //               } else {
    //                 wx.showToast({
    //                   icon: "none",
    //                   title: "获取权限失败,保存图片需要用户授权",
    //                   duration: 1500,
    //                 });
    //               }
    //             },
    //           });
    //         }
    //       },
    //       complete(res) {
    //         console.log(res);
    //       },
    //     });
    //   },
    // });
    // }
  },
  // 立即出价
  bid() {
    console.log(this.data.auction.is_prepay == 0);
    if (this.data.invite_mobile == 0) {
      wx.navigateTo({
        url: "/packageA/member/editmobile/editmobile",
      });
    } else if (this.data.auction.is_prepay == 0) {
      // this.auction.is_prepay是否支付保证金
      wx.showToast({
        duration: 1000,
        title: `需先支付${this.data.auction.prepayment}保证金方可出价`,
        icon: "none",
      });
      this.getPayData();
    } else {
      this.setData({
        showthr: true,
      });
    }
  },
  //获取支付类型参数
  getPayData() {
    this.actionSheetItems = [];
    let json = {
      goods_id: this.data.goods_id,
    };
    var that = this;
    let urlStr = app.getNetAddresss("plugin.auction.api.prepayment.page");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var response = resdata.data;
        if (response.result == 1) {
          let btnData = response.data.buttons;
          that.setData({
            btnData: btnData,
            rewardPayshow: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
          wx.hideLoading();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  payBtn(e) {
    var type = e.currentTarget.dataset.value;
    // var btn = e.currentTarget.dataset.btn;
    if (type == 3 && !this.data.isclick) {
      wx.showToast({
        title: "余额不能重复支付",
        icon: "none",
        duration: 1000,
      });
      return;
    }
    let json = {
      money: Number(this.data.auction.prepayment),
      goods_id: Number(this.data.goods_id),
      pay_way: Number(type),
    };
    wx.showLoading({
      title: "支付中",
      duration: 1000,
      icon: "none",
    });
    var payParams={};
    let urlStr = app.getNetAddresss("plugin.auction.api.prepayment.recharge");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        // this.rewardPayshow = false
        this.setData({
          rewardPayshow: false,
        });
        if (res.result == 1) {
          switch (type) {
          case 1: //微信
            payParams = {
              timeStamp: res.data.config.timestamp,
              nonceStr: res.data.config.nonceStr,
              package: res.data.config.package,
              signType: res.data.config.signType,
              paySign: res.data.config.paySign,
            };
            console.log('ssssss');
            this.WXPay(payParams);
            break;
          case 55: //微信
            payParams = {
              timeStamp: res.data.config.timestamp,
              nonceStr: res.data.config.nonceStr,
              package: res.data.config.package,
              signType: res.data.config.signType,
              paySign: res.data.config.paySign,
            };
            console.log('ssssss');
            this.WXPay(payParams);
            break;
          case 3: //余额
            if (this.data.isclick) {
              this.setData({
                rewardPayshow: false,
                isclick: false,
              });
              this.getData();
            }
            break;
          }
          wx.hideLoading();
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
          wx.hideLoading();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  WXPay: function (payParams) {
    let that = this;
    let urlStr = app.getNetAddresss("order.mini-app.index");
    wx.requestPayment({
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType ? payParams.signType : "MD5",
      paySign: payParams.paySign,
      success: function (res) {
        let json = {
          formID: payParams.package.slice(10),
          orderId: that.data.order_id,
        };
        app._postNetWork({
          url: urlStr,
          showToastIn: false,
          data: json,
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 0) {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            } else {
              wx.showToast({
                title: '支付成功',
              });
              that.getData();
            }
          },
          fail: function (res) {},
        });
      },
      fail: function (res) {
        wx.showToast({
          title: "支付失败请稍后重试",
          icon: "none",
          duration: 2000,
          success: function () {},
          fail: function () {},
        });
      },
    });
  },
  //获取时间-限时购
  _timeCompare(begin) {
    let beginTime = new Date(parseInt(begin) * 1000);
    console.log(beginTime);
    console.log(now >= beginTime);
    let now = new Date();
    if (now >= beginTime) {
      this.setData({
        isTime: true,
      });
      //开启倒计时
      this._countDown();
    } else {
      this.setData({
        isTime: false,
        isBegTime: true,
        begTimeStr: begin * 1000,
      });
      //开启距离开始倒计时
      this.beginDown();
    }
  },
  //倒计时
  _countDown: function () {
    let newTime = new Date().getTime();
    let endTime = this.data.endTime;
    let obj = null;
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt((time % (60 * 60 * 24)) / 3600);
      let min = parseInt(((time % (60 * 60 * 24)) % 3600) / 60);
      let sec = parseInt(((time % (60 * 60 * 24)) % 3600) % 60);
      obj = {
        day: this._timeFormat(day),
        hou: this._timeFormat(hou),
        min: this._timeFormat(min),
        sec: this._timeFormat(sec),
      };
    } else {
      //活动已结束，全部设置为'00'
      obj = {
        day: "00",
        hou: "00",
        min: "00",
        sec: "00",
      };
    }
    this.setData({
      countDownObj: obj,
    });
    if (endTime - newTime < 0) {
      this.setData({
        countDownObj: {
          day: "00",
          hou: "00",
          min: "00",
          sec: "00",
        },
      });
    } else {
      setTimeout(this._countDown.bind(this), 1000);
    }
  },
  //倒计时
  beginDown: function () {
    let newTime = new Date().getTime();
    let endTime = this.data.begTimeStr;
    let obj = null;
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt((time % (60 * 60 * 24)) / 3600);
      let min = parseInt(((time % (60 * 60 * 24)) % 3600) / 60);
      let sec = parseInt(((time % (60 * 60 * 24)) % 3600) % 60);
      obj = {
        day: this._timeFormat(day),
        hou: this._timeFormat(hou),
        min: this._timeFormat(min),
        sec: this._timeFormat(sec),
      };
    } else {
      //活动已结束，全部设置为'00'
      this.setData({
        isTime: true,
        isBegTime: false,
      });
      obj = {
        day: "00",
        hou: "00",
        min: "00",
        sec: "00",
      };
    }
    this.setData({
      beginDownObj: obj,
    });
    if (endTime - newTime < 0) {
      this.setData({
        isTime: true,
        isBegTime: false,
      });
      this.setData({
        beginDownObj: {
          day: "00",
          hou: "00",
          min: "00",
          sec: "00",
        },
      });
    } else {
      setTimeout(this.beginDown.bind(this), 1000);
    }
  },
  //小于10的格式化函数
  _timeFormat(param) {
    //小于10的格式化函数
    return param < 10 ? "0" + param : param;
  },
  // 一口价
  toBuy(e) {
    wx.navigateTo({
      url: "/packageD/buy/myOrder_v2/myOrder_v2?goodsId=" +
        this.data.goods_id +
        "&tag=auction" +
        "&total=1" +
        "&auction_sn=" +
        this.data.auction.acution_sn +
        "&fixed_price=1",
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.setIntervalMth);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  // 价格弹窗的出价
  bidTo() {
    let json = {
      goods_id: Number(this.data.goods_id),
      price: Number(this.data.price),
    };
    var that = this;
    let urlStr = app.getNetAddresss("plugin.auction.api.bid.bid");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: "none",
            success() {
              setTimeout(() => {
                that.setData({
                  showthr: false,
                });
                that.getData();
              }, 500);
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 海报
  posterimgTap() {
    this.setData({
      posterShow: true,
    });
    this.postShow();
  },
  posterClose() {
    this.setData({
      posterShow: false,
    });
  },
  posterClose_reward() {
    this.setData({
      rewardPayshow: false,
    });
  },
  postShow() {
    wx.showLoading({
      title: "海报生成中",
    });
    let json = {
      id: this.data.goods_id,
    };
    var that = this;
    let urlStr = app.getNetAddresss(
      "plugin.auction.api.goodsPoster.generateGoodsPoster"
    );
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            posterImg: res.data,
          });
          wx.hideLoading();
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
          wx.hideLoading();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  toCollect() {
    let json = {
      art: "collectionShop",
      auctioneer_id: this.data.id,
    };
    var that = this;
    let urlStr = app.getNetAddresss("plugin.auction.api.index.getAuctionData");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.getData();
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getStatus() {
    var that = this;
    let urlStr = app.getNetAddresss("plugin.auction.api.index.getAuctionData");
    let json = {
      member_id: that.data.id,
    };
    app._postNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          that.setData({
            status: res.data.getVerify.status,
            is_verify: res.data.getVerify.is_verify,
          });
          if (that.data.is_verify == 0 && that.data.status == 1) {
            that.setData({
              showone: true,
            });
          } else {
            that.setData({
              is_verify: 1,
            });
            that.getData();
            that.data.setIntervalMth = setInterval(() => {
              console.log('进入倒计时');
              that.getData(true);
            }, 10000);
            that.getInvite();
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getInvite() {
    var that = this;
    let urlStr = app.getNetAddresss("member.member.isValidatePage");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            invite_mobile: res.data.invite_mobile,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  finished(e) {
    this.getData();
  },
  finished_start(e) {
    this.setData({
      now: String(Date.parse(new Date())).substring(0, 10),
    });
    this.getData(false, '');
  },
  getData(bor = false, qekey) {
    var that = this;
    let urlStr = app.getNetAddresss("plugin.auction.api.index.getAuctionData");
    let json = {
      member_id: that.data.id,
      goods_id: that.data.goods_id,
      art: "goodsDetail",
    };
    app._postNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            now: String(Date.parse(new Date())).substring(0, 10),
            auction: res.data.goodsDetail.auction,
            price: Number(res.data.goodsDetail.auction.now_price).toFixed(2),
            startTime: utils.formatTimeTwo(
              res.data.goodsDetail.auction.start_shooting,
              "Y-M-D h:m:s"
            ),
            endTime: utils.formatTimeTwo(
              res.data.goodsDetail.auction.end_shooting,
              "Y-M-D h:m:s"
            ),
            record: res.data.goodsDetail.auction.bid_record.data.splice(0, 5),
            record_length: res.data.goodsDetail.auction.bid_record.total
          });
          if(res.data.goodsDetail.auction && res.data.goodsDetail.auction.auc_status == '-1'){
            console.log(res.data.goodsDetail.auction.auc_status,that.data.setIntervalMth)
            clearInterval(that.data.setIntervalMth);
            that.setData({
              isEnd:true
            })
          }
          if (res.data.goodsDetail.auction.bid_record && res.data.goodsDetail.auction.bid_record.is_last_bidder) {
            that.setData({
              is_last_bidder: res.data.goodsDetail.auction.bid_record.is_last_bidder
            });
          }
          if (!bor) {
            that.setData({
              auctioneer: res.data.goodsDetail.auctioneer,
            });
            if (qekey == 'start') {
              if (that.data.is_last_bidder) {
                wx.showModal({
                  content: '您是本场出价最高者，3分钟后自动生成订单，请到我的—待确认栏目里确认订单。',
                  duration: 1500,
                  showCancel: false,
                  success: function (e) {
                    that.getData();
                  }
                });
              }
            }
          }
          that._timeCompare(that.data.auction.end_shooting);
          that._timeCompare(that.data.auction.start_shooting);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
});