// pages/mine/wxml/playpusher/playpusher.js
var time;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    kid: null,
    detailOpen: false,
    biddingOpen: false,
    animationData: {},
    liveRoomData: [],
    openData:{},
    thisId: null,
    record:[],
    nowTime: null,
    btnText: '竞价倒计时',
    submit: true,
    setInter: '',
    chatTime: null,
    chatList: [],
    prodUrl:app.globalData.prodUrl,
    timer : null,
    timear : 0,
    scrollTop : 300
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;

    //console.log(options.live_room_kid)
    this.setData({
      liveid: options.live_room_kid
    },function() {
      _this.data.timer = setInterval(() => {
        _this.getChatList();
      }, 1000)
    })
    //设置动态标题
    // wx.setNavigationBarTitle({
    //   title: options.title
    // });
    //创建animation实例
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear'
    })
    this.animation = animation;
    //动态设置页面高度
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          pageWidth: res.windowWidth,
          pageHeight: res.windowHeight
        });
      }
    });
    //初始化拍卖会数据

    _this.getLiveRoomData(options.live_room_kid);
    
    //创建LivePusherContext实例
    _this.ctx = wx.createLivePusherContext('pusher');
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

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

  },

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

  },
  onState: function (e) {
    //console.log(e.detail.code)
  },
  //初始化拍卖会数据
  getLiveRoomData: function ( live_room_kid ) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/live_room_detail',
      data: {
        live_room_id: live_room_kid
      },
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (data) {
        //console.log(data);
        if ( !data.data.msg ) {
          wx.showModal({
            title: '提示',
            content: '您没有上传拍卖竞买商品，请先上传商品！',
            success(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              } else if (res.cancel) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          });
        } else {
          _this.setData({
            liveRoomData: data.data.data,  //设置拍卖会列表
            pushUrl: data.data.pushUrl,    //设置推流地址
            nowTime: data.data.nowtime,     //设置服务器时间
            chatTime: data.data.nowtime     //设置服务器时间
          },() => {
            //调用请求列表
            _this.listData(live_room_kid);
            //调用刷新页面状态
            _this.data.setInter = setInterval(function () {
              _this.setServerTime(_this.data.nowTime);  //设置服务器时间
              if (_this.data.openData !== {}) {
                _this.checkState(_this.data.goodsKid, _this.data.openData.price_bidder);
              }
            }, 1000);
          });
        }
        // if ( _this.data.kid === null ) {
        //   var goodsState = false;
        //   var item_kid;
        //   for (let i = 0; i<data.data.data.length; i++) {
        //     if (data.data.data[i].bid_opening === "已开拍" ) {
        //       goodsState = true;
        //       item_kid = data.data.data[i].kid;
        //       break;
        //     }
        //   }
        //   if (goodsState) {
        //     _this.setData({
        //       kid: item_kid
        //     })
        //   } else {
        //     _this.setData({
        //       kid: data.data.data[0].kid
        //     })
        //   }
        // };
        //调用同步后台时间
        // _this.getTime(nowTime);
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  //请求列表数据
  listData: function (liveid) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/live_room_detail',
      data: {
        live_room_id: liveid
      },
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        //console.log(data)
        _this.setData({
          liveRoomData: data.data.data   //设置左侧列表数据
        }, () => {
          let auction = [], wait = [], end = [];
          for (let i = 0; i < _this.data.liveRoomData.length; i++) {
            if (_this.data.liveRoomData[i].bid_opening === '已开拍') {
              auction.push(_this.data.liveRoomData[i]);
            } else if (_this.data.liveRoomData[i].bid_opening === '未开拍') {
              wait.push(_this.data.liveRoomData[i]);
            } else if (_this.data.liveRoomData[i].bid_opening === '已结束') {
              end.push(_this.data.liveRoomData[i]);
            };
          }
          if (auction.length > 0) {
            _this.setData({
              goodsKid: auction[0].kid
            }, () => {
              _this.initData(_this.data.goodsKid);
            });
          } else if (auction.length === 0 && wait.length > 0) {
            _this.setData({
              goodsKid: wait[0].kid
            }, () => {
              _this.initData(_this.data.goodsKid);
            });
          } else if (auction.length === 0 && wait.length === 0) {
            _this.initData(_this.data.goodsKid);
          };
        });
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  //同步右侧商品信息
  initData: function (goodsKid) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/get_item_detail',
      data: { item_kid: goodsKid },
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        //console.log(data);
        _this.setData({
          openData: data.data.data[0],
          record: data.data.data[0].record,
          submitNum: data.data.submit_count,
          onlineCount: data.data.online_count
        }, () => {
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  //同步后台时间
  setServerTime: function (nowTime) {
    let _this = this;
    _this.setData({
      nowTime: nowTime + 1000
    });
  },
  //每秒刷新页面状态
  checkState: function (goodsKid, price) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/check_item_status',
      data: { 
        pm_item_id: goodsKid, 
        price: price,
        live_room_id: _this.data.liveid,
        chat_time: _this.data.chatTime  
      },
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        // if (data.data.list.length !== 0) {
        //   let chatlist = _this.data.chatList;
        //   _this.setData({
        //     chatTime: data.data.list[data.data.list.length - 1].created
        //   })
        //   for (var i = 0; i < data.data.list.length; i++) {
        //     chatlist.unshift(data.data.list[i])
        //   };
        //   _this.setData({
        //     chatList: chatlist
        //   })
        // }
        if (data.data.offer_status) {
          _this.listData(_this.data.liveid);
          wx.showToast({
            title: '有新的报价！',
            icon: 'none',
            duration: 3000
          });
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  //选择商品
  selectGoods: function (e) {
    let _this = this;
    for (let i = 0; i < this.data.liveRoomData.length; i++) {
      if (this.data.liveRoomData[i].kid === e.currentTarget.dataset.kid) {
        _this.setData({
          goodsKid: this.data.liveRoomData[i].kid,
          thisId: i
        },() => {
          _this.initData(_this.data.goodsKid);
        });
        wx.showToast({
          title: '已切换商品，请到右侧商品详情中查看。',
          icon: 'none',
          duration: 3000
        });
        //console.log(_this.data.thisId);
      }
    }
  },
  //打开关闭商品列表
  openDetail: function (e) {
    let move = this.data.pageWidth * 0.9;
    if (this.data.detailOpen) {
      this.animation.translate(0).step()
      this.setData({
        detailOpen: false,
        animationData: this.animation.export()
      })
    } else {
      this.animation.translate(move).step()
      this.setData({
        detailOpen: true,
        animationData: this.animation.export()
      })
    }
  },
  //打开关闭商品详情
  openBidding: function (e) {
    let _this = this;
    //动画效果
    let move = this.data.pageWidth * 0.9;
    if (this.data.biddingOpen) {
      this.animation.translate(0).step();
      this.setData({
        biddingOpen: false,
        animationData: this.animation.export()
      });
    } else {
      this.animation.translate(-move).step();
      this.setData({
        biddingOpen: true,
        animationData: this.animation.export()
      });
    };
  },
  //开拍
  startAuction: function (e) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/bidding_status',
      data: {
        item_kid: _this.data.openData.kid,
        is_open: true
      },
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        if (data.data.success) {
          _this.listData(_this.data.liveid);
          wx.showToast({
            title: data.data.tip.msg,
            icon: 'none',
            duration: 3000
          });
        }
      }
    })
  },
  //关拍
  endAuction:function(e) {
    //console.log('点击关拍')
    let _this = this;
    if( _this.data.submit ) {
      wx.request({
        url: app.globalData.prodUrl + 'web-pm/wx/pm/start_countdown',
        data: {
          item_kid: _this.data.openData.kid
        },
        header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        success: function (data) {
          //console.log(data)
          //调用倒计时
          _this.endCountDown(data.data.nowtime, _this.data.nowTime);
          _this.setData({
            submit: false
          })
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    } else {
      return false;
    }
    
  },
  //关拍倒计时
  endCountDown: function ( closeTime, nowTime ) {
    let _this = this;
    let time = parseInt((closeTime + 15000 - nowTime)/1000);
    //console.log(closeTime)
    let countdown = setInterval(function () {
      time -= 1;
      if(time >= 0) {
        _this.setData({
          btnText: '成交倒计时' + time + '秒'
        });
        wx.request({
          url: app.globalData.prodUrl + 'web-pm/wx/pm/get_countdown',
          data: {
            item_kid: _this.data.openData.kid,
            start_time: closeTime
          },
          header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
          method: 'GET',
          dataType: 'json',
          responseType: 'text',
          success: function(data) {
            //console.log(data);
            if (data.data.statuz) {
              wx.showToast({
                title: '有新的报价！',
                icon: 'none',
                duration: 3000,
                success: function(res) {}
              })
              _this.setData({
                btnText: '竞价倒计时',
                submit: true
              });
              clearInterval(countdown);
            }
          },
          fail: function(res) {},
          complete: function(res) {},
        })
      } else {
        wx.request({
          url: app.globalData.prodUrl + 'web-pm/wx/pm/bidding_status',
          data: {
            item_kid: _this.data.openData.kid,
            is_open: false
          },
          header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
          method: 'GET',
          dataType: 'json',
          responseType: 'text',
          success: function (data) {
            //console.log(data);
            if (data.data.success) {
              _this.setData({
                btnText: '竞价倒计时',
                submit: true
              })
              _this.listData(_this.data.liveid);
              wx.showToast({
                title: data.data.tip.msg,
                icon: 'none',
                duration: 3000
              });
            }
          }
        });
        clearInterval(countdown);
      }
    }, 1000)
    //console.log(time);
  },
  //切换后置摄像头
  rotateCamera:function (e) {
    this.ctx.switchCamera({
      success: res => {
        //console.log('switchCamera success')
      },
      fail: res => {
        //console.log('switchCamera fail')
      }
    });
  },
  getChatList() {
    var _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/get_chatting_records',
      data: {
        live_room_id: _this.data.liveid,
        chat_time: _this.data.timear
      },
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (data) {
        var chatList = data.data.data;
        if (chatList.length != 0) {
            var time = data.data.data[0].created;
            _this.setData({
                chatList: chatList,
                timear: time
            }, function () {
                _this.pageScrollToBottom();
            })
        }

      }
    })
  },
  pageScrollToBottom: function () {
    var _this = this;
    this.setData({
      scrollTop: this.data.scrollTop + 40
    }, function () {

    }
    )
  }
})