// pages/live/live.js
var time;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    liveUrl: '',      //拉流地址
    detailOpen: false,//左抽屉开关
    setInter: '',     //秒刷函数
    goodsKid: '',     //当前商品ID
    openData: {},     //openData
    biddingOpen: false,//右抽屉开关
    animationData: {},//动画函数
    nowTime: null,    //服务器时间
    endAuction: false,
    endTimeText: 9,
    endTimeShow: false,
    flag: true,
    new_bidder: 0,      //需要操作的价格
    apply: null,       //报名人数
    payDeposit: false, //是否支付保证金
    code: '',          //支付保证金后显示的号牌
    countDownInter: '',
    notPlay: true,
    chatText: '',
    chatTime: null,
    chatList: [],
    prodUrl: app.globalData.prodUrl,
    auction : true,
    time : 0,
    scrollTop : 300,
    contentText : "",
    onlineCount : 0,
    chatBool : true,
    timer : null,
    detailBool : false,
    mask : false,
    productBool : false,
    selectIndex : 0,
    SelectKid : "",
    timerContr: null,
    setInter1 :null,
    limit : 8,
    page :　1,
    sumPage : null,
    textTitle : "点击加载更多..."

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    this.setData({
      liveid: options.liveid,
      title: options.title
    },function() {
      _this.data.timer = setInterval(() => {
        _this.getChatList();
      },1000)
    });
    //设置动态标题
    wx.setNavigationBarTitle({
      title: options.title
    });
    //创建animation实例
    let animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'linear'
    });
    this.animation = animation;
    //动态设置页面高度
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          pageWidth: res.windowWidth,
          pageHeight: res.windowHeight - 50
        })
      }
    });
    //初始化页面数据
    if (options.isshare) {
      //console.log('是分享进入');
      let getlogin = app.getLogs(app);
      getlogin.then(function () {
        _this.getNewData(options.liveid);
      }).catch(function () {
        //console.log('错误')
      })
      this.setData({
        'isshare': options.isshare
      })
    } else {
      _this.getNewData(options.liveid);
    }
    // setInterval(() => {
    //   var a = Math.floor(Math.random() * (100 - 20 + 1) + 20);
    //   _this.setData({
    //     onlineCount : a
    //   }) 
    // },3000)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    //console.log('123132')
    var _this = this;
    return {
      title: '和我一起来玩拍~',
      path: '/pages/live/live?isshare=true&liveid=' + _this.data.liveid + "&title=" + _this.data.title,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  playstate: function (e) {
  },
  btn:function (e) {
    //console.log(e)
  },
  //初始化页面数据
  getNewData: function (liveid) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/live_item_detail',
        data: { live_room_id: liveid, limit: _this.data.limit, page: _this.data.page },
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        if(data.data.live_room.live_status === "已开始") {
          _this.setData({
            auction : false
          })
        }

        _this.setData({
          liveUrl: data.data.live_room.live_url, //设置拉流地址
          nowTime: data.data.nowtime, //设置服务器时间
          chatTime: data.data.nowtime, //设置聊天时间戳
          listData: data.data.data,   //设置左侧列表数据
          contentText : data.data.live_room.content,
          sumPage : data.data.count
        }, () => {
          let auction = [], wait = [], end = [],start = [];
          for (let i = 0; i < _this.data.listData.length; i++) {
            if (_this.data.listData[i].bid_opening === '已开拍') {
              auction.push(_this.data.listData[i]);
                start.push(i);   
            } else if (_this.data.listData[i].bid_opening === '未开拍') {
              wait.push(_this.data.listData[i]);
            } else if (_this.data.listData[i].bid_opening === '已结束') {
              end.push(_this.data.listData[i]);
            };
          }
          _this.setData({
              selectIndex : start[0]
          })
          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);
            });
          };
           // _this.data.timerContr = setInterval(()=>{
               // if (_this.data.openData.price_bidder) {
                    _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);
              //  }
           // })
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  //设置服务器时间
    setServerTime: function (nowTime) {
        let _this = this;
        _this.setData({
        nowTime: nowTime + 1000
        });
    },
    //加载更多
    loadMore() {
        var _this = this;
        var page = this.data.page + 1;
        var sumPage = this.data.sumPage / 8 > Math.floor(this.data.sumPage / 8) ? Math.floor(this.data.sumPage / 8) + 1 : this.data.sumPage / 8;
        _this.setData({
            page
        },function() {
            if (page <= sumPage) {
                _this.listData(_this.data.liveid);
            } else {
                _this.setData({
                    textTitle : "已经到底了,无更多商品了!!!"
                })
            }
        })
    },
  //左侧列表数据
  listData: function (liveid) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/live_item_detail',
        data: { live_room_id: liveid, limit: _this.data.limit, page: _this.data.page},
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
          _this.setData({
              listData: _this.data.listData.concat(data.data.data)
          },function() {
            var select = _this.data.SelectKid || _this.data.goodsKid
            _this.initData(select);
          })
        //   var ind = null;
        //   for(var i = 0;i< _this.data.listData.length ; i ++) {
        //       if (data.data.data[i].price_bidder !== _this.data.listData[i].price_bidder) {
        //         ind = i;
        //         console.log(ind)
        //       }
        //   }
        //   if (ind) {
        //       var list = 'listData[' + ind + ']';
        //   }
        // _this.setData({
        //   [list] : data.data.data[ind]   //设置左侧列表数据
        // }, () => {

        //   let auction = [], wait = [], end = [];
        //   for (let i = 0; i < _this.data.listData.length; i++) {
        //     if (_this.data.listData[i].bid_opening === '已开拍') {
        //       auction.push(_this.data.listData[i]);
        //     } else if (_this.data.listData[i].bid_opening === '未开拍') {
        //       wait.push(_this.data.listData[i]);
        //     } else if (_this.data.listData[i].bid_opening === '已结束') {
        //       end.push(_this.data.listData[i]);
        //     };
        //   }

           // var select = _this.data.SelectKid || _this.data.goodsKid
            //_this.initData(select);
        //   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.setData({
        //       goodsKid: end[end.length-1].kid
        //     }, () => {
        //       _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],
          code: data.data.code,
          payDeposit: data.data.item_submit,
          apply: data.data.submit_count,
          record: data.data.data[0].record,
          // onlineCount: data.data.online_count
        });
        if (data.data.data[0].price_bidder === 0) {
          _this.setData({
            new_bidder: data.data.data[0].price_start + data.data.data[0].price_add
          })
        } else {
          _this.setData({
            new_bidder: data.data.data[0].price_bidder + data.data.data[0].price_add
          })
        }
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
    selectGood(e){
        var _this = this;
        var price = this.data.bidder;
        var kid = e.currentTarget.dataset.kid;
        var index = e.currentTarget.dataset.ind;
        this.setData({
            selectIndex : index,
            SelectKid : kid,
            goodsKid : kid,
        })
        this.initData(kid)
        wx.showToast({
            title: '已切换商品,请到右侧“我要出价”查看',
            icon: 'none',
            duration: 2000
        });
    },
  //刷新商品状态
  checkState: function (goodsKid, price) {
    let _this = this;
      if (price){
        wx.request({
            url: app.globalData.prodUrl + 'web-pm/wx/pm/check_live_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);
                    if (data.data.offer_price_persion !== wx.getStorageSync('persion').persion.kid)
                        wx.showToast({
                            title: '有新的报价！',
                            icon: 'none',
                            duration: 3000
                        });
                };
                if (data.data.archive_status && _this.data.flag) {
                    _this.setData({
                        flag: false
                    }, () => {
                        _this.endTime(data.data.close_time)
                    });
                };
                if (!data.data.archive_status && !_this.data.flag) {
                    clearInterval(_this.data.countDownInter);
                    _this.setData({
                        endTimeShow: false,
                        flag: true
                    });
                };
                if (data.data.bid_opening != _this.data.openData.bid_opening) {
                    if (data.data.bid_opening === '已结束' && data.data.bidding_man === wx.getStorageSync('persion').persion.kid) {
                        _this.setData({
                            mask: true
                        })
                        // wx.showToast({
                        //   title: '恭喜您竞价成功！',
                        //   icon: 'success',
                        //   duration: 3000
                        // });
                        clearInterval(_this.data.countDownInter);
                    } else if (data.data.bid_opening === '已结束' && data.data.bidding_man !== wx.getStorageSync('persion').persion.kid) {
                        wx.showToast({
                            title: '很遗憾，竞价失败！',
                            icon: 'none',
                            duration: 3000
                        });
                    }
                    _this.listData(_this.data.liveid);
                };
                _this.setData({
                    onlineCount: data.data.online_count,
                })

            },
            fail: function (res) { },
            complete: function (res) { },
        });
    }    
  },
  //结束倒计时
  endTime: function (closeTime) {
    let _this = this;
    var time = parseInt(((closeTime + 15000) - _this.data.nowTime)/1000 );
    _this.data.countDownInter = setInterval(function(){
      if ( time > 0 ) {
        time -= 1;
        _this.setData({
          endTimeText: time,
          endTimeShow: true
        })
      } else if (time <= 0) {
        clearInterval(_this.data.countDownInter);
        _this.setData({
          endTimeText: time,
          endTimeShow: false,
          flag: true
        });
      };
    },1000);
  },
  //减价
  reducePrice: function (e) {
    let _this = this;
    let new_bidder = _this.data.new_bidder - _this.data.openData.price_add;
    if (new_bidder <= _this.data.openData.price_bidder ){
      wx.showToast({
        title: '出价不得低于最低加价幅度',
        icon: 'none',
        duration: 3000
      })
    } else {
      _this.setData({
        new_bidder: new_bidder
      })
    }
  },
  //加价
  reduceIncrease: function (e) {
    let _this = this;
    let new_bidder = (_this.data.new_bidder + _this.data.openData.price_add);
    _this.setData({
      new_bidder: new_bidder
    })
  },
  //出价
  bid:function (e) {
    let _this = this;
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/compete_price',
      data: {
        pm_item_id: _this.data.openData.kid,
        price_bidder: _this.data.new_bidder === 0 ? 1 : _this.data.new_bidder
      },
      header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function(data) {
        if(data.data.success) {
          _this.setData({
            record: data.data.record,
            bidder: data.data.pm_item_submit_offer.price_bidder,
            new_bidder: data.data.pm_item_submit_offer.price_bidder + _this.data.openData.price_add
          },function() {
          })
            var selectkid = _this.data.SelectKid || _this.data.goodsKid;
            new Promise((resolve,reject) => {
                _this.initData(selectkid);
                resolve();
            }).then(() => {
                _this.listData(_this.data.liveid);
            }) 
          wx.showToast({
            title: data.data.tip.msg,
            icon: 'none',
            duration: 3000
          })
        } else {
          wx.showToast({
            title: data.data.tip.msg,
            icon: 'none',
            duration: 3000
          })
        }
        
      },
      fail: function(res) {
      
      },
      complete: function(res) {
       
      },
    })
  },
  //打开关闭商品详请
  openDetail: function (e) {
    let move = this.data.pageWidth * 0.9;
    if(this.data.detailOpen) {
      this.animation.translate(0).step()
      this.setData({
        detailOpen: false,
        chatBool: true,
        notPlay: true,
        animationData: this.animation.export()
      })
    } else {
      this.animation.translate(move).step()
      this.setData({
        detailOpen: true,
        chatBool: false,
          notPlay: false,
        animationData: this.animation.export()
      })
    }
  },
  //打开关闭出价页面
  openBidding: function (e) {
    let move = this.data.pageWidth * 0.9;
    if (this.data.biddingOpen) {
      this.animation.translate(0).step()
      this.setData({
        biddingOpen: false,
        chatBool : true,
        notPlay : true,
        animationData: this.animation.export()
      })
    } else {    
      this.animation.translate(-move).step()
      this.setData({
        biddingOpen: true,
        chatBool: false,
          notPlay: false,
        animationData: this.animation.export()
      })
    }
  },
  //交保证金
  subDeposit: function (e) {
    let _this = this;
    wx.navigateTo({
        url: '../payDeposit/payDeposit?kid=' + this.data.openData.kid + '&deposit=' + _this.data.openData.price_guarantee + '&auction_way=' + _this.data.openData.auction_way + "&time=" + _this.data.openData.time_opening,
      success: function (res) {
        clearInterval(_this.data.setInter);
        clearInterval(_this.data.countDownInter);
      }
    })
  },
  //保存聊天文本
  chatText: function (e) {
    this.setData({
      chatText: e.detail.value
    });
  },
  //发送聊天文本
  send: function (e) {
    let _this = this;
    if ( _this.data.chatText !== '' ) {
      wx.request({
        url: app.globalData.prodUrl + 'web-pm/wx/pm/add_chitchat',
        data: {
          content: _this.data.chatText,
          liveroom_id: _this.data.liveid
        },
        header: { 'ydw-token': wx.getStorageSync('key').ydw_token },
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        success: function (data) {
          _this.setData({
            chatText: ''
          },function() {
            _this.getChatList()
          })
        }
      })
    } else {
    }
  },
  //检测拍卖状态
  getLiveState: function (e) {
  },
  getNetworkState: function (e) {
    let _this = this;
    if(e.detail.info.netSpeed === 0) {
      _this.setData({
        notPlay: true
      })
    } else {
      _this.setData({
        notPlay: false
      })
    }
  },
  //跳转首页
  backHome: function () {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  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.time
      },
      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,
                time
            }, function () {
                _this.pageScrollToBottom();
            })
        }
      }
    })
  },
  pageScrollToBottom: function () {
    var _this = this;
    this.setData({
      scrollTop: this.data.scrollTop + 40
    }, function () {
      
    }
    )
  },
  lookDetail() {
    this.setData({
      detailBool: !this.data.detailBool
    })
  },
  gopay: function (e) {
    wx.navigateTo({
      url: '/pages/mine/wxml/beingphotographed/beingphotographed'
    })
  },
    closePay: function (e) {
        this.setData({
            mask : false
        }) 
    },
  opDetail : function(e) {
    var a = e.currentTarget.dataset.ind;
    var arr = this.data.listData;
    for (var i = 0; i < arr.length ; i ++) {
      if(a === i) {
        arr[i].bool = true
      }
    }
    this.setData({
      // productBool : true,
      listData : arr
    })
  },
  closeDetail : function(e) {
    var a = e.currentTarget.dataset.ind;
    var arr = this.data.listData;
    for (var i = 0; i < arr.length; i++) {
      if (a === i) {
        arr[i].bool = false
      } 
    }
    this.setData({
      // productBool: true,
      listData: arr
    })
  }
})