auction-detail.js 11.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
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: {
    isOverShare: true,
    authorizeVisible: false,
    auctionBidVisible: false,
    auctionBidSuccessVisible: false,
    auctionBidFailVisible: false,
    commonTipsCompVisible: false,
    signTipsCompVisible: false,
    innerTitle: "提示",
    innerText: "",
    userInfo: {},
    productInfo: {},
    priceInfo: [],
    priceTotal: 0,
    maxPrice: 0,
    navBackTimeout: 0,
    socketStatus: 'closed',
    hasLogin: false,
    waitingResponse: false,
    loading: false,
    options: {},
    wxTimerList: {},
    lastTime: "",
    bidPrice: 0, // 我的出价 单位元
    isTimeEnd: false, //倒计时结束
  },
  onShareAppMessage() {
    let {
      productInfo
    } = this.data;
    let title = `${productInfo.auctionName}拍卖热烈进行中!`;
    let path = `pages/auction-detail/auction-detail?code=${productInfo.auctionCode}&share=true`;
    let imageUrl = productInfo && productInfo.auctionImages[0] || "";
    return {
      title,
      path,
      imageUrl
    }
  },
  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.refreshView();
      this.openSocket();
    });
  },

  /**
   * 刷新页面
   */
  refreshView() {
    this.queryAuctionDetail().then((result) => {
      this.removeTimer();
      this.startTimer();
    })
    this.queryAuctionRecordLast();
  },

  // 开始倒计时
  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.setData({
          isTimeEnd: true
        })
        _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;
    let _this = this;
    console.log("queryAuctionDetail")
    return new Promise((resolve, reject) => {
      app.post({
        toast: false,
        url: app.api.auctionDetail,
        data: {
          auctionCode: code
        }
      }).then((result) => {
        this.setData({
          productInfo: result
        });
        console.log("queryAuctionDetail result:", result);
        // wx.setNavigationBarTitle({
        //   title: result.auctionName || "拍卖活动"
        // })
        resolve();
      }).catch((err) => {
        if (err.code == 1002) {
          _this.setData({
            signTipsCompVisible: true,
          })
        } else {
          _this.setData({
            commonTipsCompVisible: true,
            innerText: err.errMsg || "您未达到进入条件"
          })
        }
      });
    })
  },

  /**
   * 获得最高价 和列表
   */
  queryAuctionRecordLast() {
    return new Promise((resolve, reject) => {
      let code = this.data.options.code;
      if (code) {
        app.post({
          toast: false,
          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
          })
          console.log("queryAuctionRecordLast result:", result);
          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
        })
      })
      console.log("queryAuctionSubmit result:", result);
    }).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
        })
        console.log("queryMember result:", 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
      })
      // this.refreshView();
    })

    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);
      let socketData = message && message.data || "";
      let result = null;
      if (socketData) {
        let parseData = JSON.parse(socketData);
        result = parseData && parseData.content || null;
      }
      // console.log("result:", result);

      if (!result) return;
      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
      })

      // 重置倒计时
      let productInfo = this.data.productInfo;
      let endTime = result.endTime || 0;
      productInfo.endTime = endTime
      this.setData({
        isTimeEnd: endTime <= 0,
        productInfo
      })
      this.removeTimer();
      this.startTimer();
      // this.setData({
      //   loading: false
      // });
      // this.refreshView();
    })

    // 打开信道
    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,
      commonTipsCompVisible: false,
      signTipsCompVisible: false,
    })
  },



  /**
   * 去验证
   */
  toVipLoginHandler() {
    app.router.push({
      openType: "redirect",
      path: "vipLogin"
    })
  },

  // 子组件事件
  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;

        // 通用按钮
      case "_evt_common_comp_button":
        this.hideMask();
        if (options.share) {
          app.router.push({
            openType: "reLaunch",
            path: "index"
          })
        } else {
          wx.navigateBack({
            delta: 1
          });
        }
        break;

        // 去验证
      case "_evt_to_verify":
        this.hideMask();
        this.toVipLoginHandler();
        break;

        // 暂不验证
      case "_evt_not_verify":
        let {
          options
        } = this.data;
        this.hideMask();
        if (options.share) {
          app.router.push({
            openType: "reLaunch",
            path: "index"
          })
        } else {
          wx.navigateBack({
            delta: 1
          });
        }
        break;


      default:
        break;
    }
  },
})