auction-detail.js 8.36 KB
import {
  getBindtapData,
  formatDateTime,
} from '../../utils/util';
let Date = require('../../utils/date.js');
var timer = require('../../utils/wxTimer.js');

var wxTimer;

let app = getApp();
Page({
  data: {
    authorizeVisible: false,
    auctionBidVisible: false,
    auctionBidSuccessVisible: false,
    auctionBidFailVisible: false,
    userInfo: {},
    productInfo: {},
    priceInfo: [],
    priceTotal: 0,
    maxPrice: 0,
    navBackTimeout: 0,
    socketStatus: 'closed',
    hasLogin: false,
    waitingResponse: false,
    loading: false,
    options: {},
    wxTimerList: {},
    lastTime: "",
    bidPrice: 0, // 我的出价 单位元
  },
  onShareAppMessage() {},
  showAuth() {
    this.setData({
      authorizeVisible: true
    })
  },
  onShow() {
    if (wxTimer) {
      wxTimer.calibration()
    }
  },
  onLoad(options) {
    this.setData({
      options
    })
    this.initData();
  },
  onUnload() {
    this.removeTimer();
    this.closeSocket()
  },

  initData() {
    this.queryMember().then((result) => {
      this.queryAuctionDetail().then((result) => {
        this.startTimer();
      })
      this.queryAuctionRecordLast();
      this.openSocket();
    });
  },

  // 开始倒计时
  startTimer() {
    let _this = this;
    if (wxTimer) {
      wxTimer.stop();
    }
    let beginTime = _this.getTimeStr();
    console.log("beginTime:", beginTime);
    if (!beginTime) return;
    wxTimer = new timer({
      beginTime: beginTime,
      complete() {
        _this.removeTimer();
        _this.queryAuctionDetail();
      },
      interval: 1,
      intervalFn() {
        let lastTime = _this.getTimeStr({
          day: true
        });
        _this.setData({
          lastTime
        })
        // console.log("lastTime:", lastTime);
      }
    })
    wxTimer.start(_this);
  },

  /**
   * 移除倒计时
   */
  removeTimer() {
    if (wxTimer) {
      wxTimer.stop()
    }
  },

  /**
   * 获取时间字符串
   * @param {*} initObj
   */
  getTimeStr(initObj) {
    let productInfo = this.data.productInfo;
    let endTime = productInfo && productInfo.endTime || 0;
    return formatDateTime(endTime, initObj)
  },

  /**
   * 点击显示详情
   */
  onShowAuctionBidDetailHandler(evt) {
    app.router.push({
      path: "auctionBidDetail",
      query: {
        code: this.data.options.code
      }
    })
  },

  /**
   * 我要出价
   */
  onSubmitHandler() {
    let productInfo = this.data.productInfo;
    if (productInfo && productInfo.status == 1) {
      this.setData({
        auctionBidVisible: true
      })
      let maxPrice = this.data.maxPrice;
      let minBidPrice = maxPrice + productInfo.minScope;
      this.auctionBidComp = this.selectComponent("#auctionBidComp");
      if (this.auctionBidComp) {
        this.auctionBidComp.setBidPrice(minBidPrice);
      }
    }
  },

  /**
   * 秒杀详情
   */
  queryAuctionDetail() {
    let code = this.data.options.code;
    // 45ebd46114904467824644b55654c27a
    // cf8bc80aef3446b58d17abc6167ad536
    let _this = this;
    return new Promise((resolve, reject) => {
      app.post({
        url: app.api.auctionDetail,
        data: {
          auctionCode: code
        }
      }).then((result) => {
        this.setData({
          productInfo: result
        })
        // wx.setNavigationBarTitle({
        //   title: result.auctionName || "拍卖活动"
        // })
        resolve();
      }).catch((err) => {
        clearTimeout(_this.data.navBackTimeout);
        _this.data.navBackTimeout = setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 1000);
      });
    })
  },

  /**
   * 获得最高价 和列表
   */
  queryAuctionRecordLast() {
    return new Promise((resolve, reject) => {
      let code = this.data.options.code;
      if (code) {
        app.post({
          url: app.api.auctionRecordLast,
          data: {
            auctionCode: code
          }
        }).then((result) => {
          let priceInfo = result.list || [];
          priceInfo.forEach(element => {
            element.recordTime = new Date(element.recordTime).toString("yyyy.MM.dd hh:mm:ss");
            element.memberPhone = element.memberPhone.substr(0, 3) + '****' + element.memberPhone.substr(7);
          });
          this.setData({
            priceInfo: priceInfo,
            maxPrice: result.maxPrice || 0,
            priceTotal: result.total || 0
          })
          resolve();
        });
      } else {
        resolve();
      }
    })
  },

  /**
   * 拍卖出价提交
   * @param {*} price
   */
  queryAuctionSubmit(price) {
    let code = this.data.options.code;
    this.setData({
      bidPrice: price
    })
    app.post({
      toast: false,
      loading: true,
      url: app.api.auctionSubmit,
      data: {
        auctionCode: code,
        price: price * 100 //转成分
      }
    }).then((result) => {
      console.log("result:", result);
      this.queryAuctionRecordLast().then((res2) => {
        this.setData({
          auctionBidSuccessVisible: true
        })
      })
    }).catch((err) => {
      console.log("queryAuctionSubmit err:", err);
      this.queryAuctionRecordLast().then((res2) => {
        switch (err.code) {
          // 来晚一步,该价格已经被其他用户提交 显示组件
          case 1010:
            this.setData({
              auctionBidFailVisible: true
            })
            break;

          default:
            wx.showToast({
              title: err.errMsg || "系统开小差"
            })
            break;
        }
      })
    });
  },

  /**
   * 获取会员信息
   */
  queryMember() {
    return new Promise((resolve, reject) => {
      app.post({
        url: app.api.member,
        data: {}
      }).then((result) => {
        this.setData({
          userInfo: result
        })
        resolve(result);
      })
    });
  },

  /**
   * 打开websocket
   */
  openSocket() {
    let memberCode = this.data.userInfo.memberCode;
    let auctionCode = this.data.options.code;
    let wsUrl = 'wss://ow.go.qudone.com/zlzm/websocket/auction/' + memberCode + auctionCode;
    // console.log("wsUrl:", wsUrl);
    if (!memberCode || !auctionCode) {
      wx.showModal({
        content: "信息丢失,无法同步实时数据",
        showCancel: false,
        success(res) {}
      })
      return;
    }

    wx.onSocketOpen(() => {
      console.log('WebSocket 已连接');
      this.setData({
        socketStatus: 'connected',
        waitingResponse: false
      })
    })

    wx.onSocketClose(() => {
      console.log('WebSocket 已断开')
      this.setData({
        socketStatus: 'closed'
      })
      this.openSocket();
    })

    wx.onSocketError(error => {
      console.error('socket error:', error)
      this.setData({
        loading: false
      })
    })

    // 监听服务器推送消息
    wx.onSocketMessage(message => {
      console.log('socket message:', message)
      this.setData({
        loading: false
      })
    })

    // 打开信道
    wx.connectSocket({
      // url: 'wss://echo.websocket.org',
      url: wsUrl
    })

  },

  /**
   * 关闭websocket
   */
  closeSocket() {
    if (this.data.socketStatus === 'connected') {
      wx.closeSocket({
        success: () => {
          console.log("Socket已断开");
          this.setData({
            socketStatus: 'closed'
          })
        }
      })
    }
  },

  sendMessage(msg) {
    if (this.data.socketStatus === 'connected') {
      wx.sendSocketMessage({
        data: msg
      })
    }
  },

  // 隐藏蒙层
  hideMask() {
    this.setData({
      authorizeVisible: false,
      auctionBidVisible: false,
      auctionBidSuccessVisible: false,
      auctionBidFailVisible: false,
    })
  },
  // 子组件事件
  evtcomp(evt) {
    let {
      name,
      data
    } = evt.detail;
    console.log("@auction-detail || evt:", name)
    switch (name) {

      // 隐藏弹窗
      case "_evt_hide_mask":
        this.hideMask();
        break;

        // 拍卖出价
      case "_evt_bid_submit":
        let {
          bidPrice
        } = data;
        console.log("bidPrice:", bidPrice);
        this.hideMask();
        this.queryAuctionSubmit(bidPrice);
        break;

        // 返回活动
      case "_evt_continue_auction":
        this.hideMask();
        break;

        // 重新报价
      case "_evt_re_bid":
        this.hideMask();
        this.onSubmitHandler();
        break;

      default:
        break;
    }
  },
})