// packageD/directSeeding/anchorDetail/anchorDetail.js
var app = getApp();
var colOneHeight = 0;
var colTwoHeight = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    recordsList: [],
    focusBol: true,
    roomList: [],
    dataInfo: "",
    id: "",
    playBackData: "",
    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,

    activeName:0,
    videoList: [],
    activitys1: [],
    activitys2: [],
    titleArr: [],
    dataList:[],
    showLoading: false,
    imgCount: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id,
      });
    }
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

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

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

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    for (let i = 0; i < this.data.roomList.length; i++) {
      if (this.data.roomList[i].clearTime) {
        clearTimeout(this.data.roomList[i].clearTime);
      }
    }
  },

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  //跳转直播页
  goPage(e) {
    let status = e.currentTarget.dataset.status;
    let id = e.currentTarget.dataset.id;
    if (status == 3) {
      wx.navigateTo({
        url:
          "/packageD/directSeeding/livePage/livePage?id=" +
          id +
          "&playerType=live",
      });
    } else {
      wx.navigateTo({
        url: "/packageD/directSeeding/foreshow/foreshow?id=" + id,
      });
    }
  },
  focusBtn() {
    if (this.data.focusBol) {
      this.addConcern();
    } else {
      this.cancelConcern();
    }
  },
  changeTabs(e){
    this.setData({
      activeName: e.currentTarget.dataset.index
    });
    this.handleClick();
  },
  addConcern() {
    //添加关注
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.anchor.concern");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        member_id: this.data.id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          that.setData({
            focusBol: false,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  cancelConcern() {
    //取消关注
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor.cancel-concern"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        member_id: this.data.id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          that.setData({
            focusBol: true,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.anchor.get-anchor");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        member_id: this.data.id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let roomData = res.data.room;
          if (roomData && roomData.length > 0) {
            let nowTime = new Date().getTime();
            for (let i = 0; i < roomData.length; i++) {
              let live_time = roomData[i].live_time;
              let beginTime = new Date(live_time).getTime() * 1000;
              roomData[i].day = "00";
              roomData[i].hou = "00";
              roomData[i].min = "00";
              roomData[i].sec = "00";
              if (nowTime > beginTime) {
                roomData[i].stop = true;
              } else {
                that._countDown(i, roomData[i].live_time);
                roomData[i].stop = false;
              }
            }
          } else {
            roomData = [];
          }
          that.setData({
            dataInfo: res.data,
            roomList: roomData,
          });
          console.log(that.data.roomList);
          if (that.data.dataInfo.is_concern == 1) {
            that.setData({
              focusBol: false,
            });
          }
          if (that.data.dataInfo.is_back == 1) {
            // that.getBack();
            that.data.titleArr.push({
              name: "live",
              title:'直播回放',
              url: "plugin.room.frontend.anchor.get-back"
            });
          }
          if (res.data.short_video_display) {
            that.data.titleArr.push({
              name: "video",
              title:'短视频',
              url: "plugin.room.frontend.anchor.get-video"
            });
          }
          that.setData({
            titleArr: that.data.titleArr
          });
          that.data.titleArr.forEach((val, index) => {
            that.data.dataList.push({
              isLoadMore: true,
              page: 1,
              total_page: 0,
              list: [],
              url: val.url
            });
          });
          that.handleClick();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  _countDown: function (index, endTime_1) {
    let newTime = new Date().getTime();
    let endTime = new Date(endTime_1).getTime() * 1000;
    // 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);
      this.setData({
        ["roomList[" + index + "].day"]: this._timeFormat(day),
        ["roomList[" + index + "].hou"]: this._timeFormat(hou),
        ["roomList[" + index + "].min"]: this._timeFormat(min),
        ["roomList[" + index + "].sec"]: this._timeFormat(sec),
      });
    } else {
      //活动已结束，全部设置为'00'
      this.setData({
        ["roomList[" + index + "].day"]: "00",
        ["roomList[" + index + "].hou"]: "00",
        ["roomList[" + index + "].min"]: "00",
        ["roomList[" + index + "].sec"]: "00",
        ["roomList[" + index + "].stop"]: false,
      });
    }
    if (endTime - newTime < 0) {
      this.setData({
        ["roomList[" + index + "].day"]: "00",
        ["roomList[" + index + "].hou"]: "00",
        ["roomList[" + index + "].min"]: "00",
        ["roomList[" + index + "].sec"]: "00",
        ["roomList[" + index + "].stop"]: false,
      });
    } else {
      this.data.roomList[index].clearTime = setTimeout(
        this._countDown.bind(this, index, endTime_1),
        1000
      );
    }
  },
  //小于10的格式化函数
  _timeFormat(param) {
    //小于10的格式化函数
    return param < 10 ? "0" + param : param;
  },
  handleClick() {
    let that = this;
    if (this.data.dataList[that.data.activeName].list.length>0) {
      that.data.isLoadMore = this.data.dataList[that.data.activeName].isLoadMore;
      return;
    }
    let urlStr = app.getNetAddresss(that.data.dataList[that.data.activeName].url);
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        page: 1,
        member_id: this.data.id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isLoadMore: true,
            ['dataList[' + that.data.activeName + '].isLoadMore']: true,
            ['dataList[' + that.data.activeName + '].total_page']: res.data.last_page,
            ['dataList[' + that.data.activeName + '].list']: res.data.data
          });
          
          if (that.data.titleArr[that.data.activeName].name == "video") {
            that.setData({
              activitys1:[],
              activitys2: [],
              videoList: res.data.data
            });
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  //获取更多数据
  _getMoreData() {
    const that = this;
    let json = {};
    let api = "";
    let urlStr = "";
    that.data.isLoadMore = false; // 防止多次请求分页数据
    that.data.dataList[that.data.activeName].isLoadMore = false;

    if (this.data.dataList[that.data.activeName].page >= this.data.dataList[that.data.activeName].total_page) {
      return;
    } else {
      this.data.dataList[that.data.activeName].page = this.data.dataList[that.data.activeName].page + 1;
      api = this.data.dataList[that.data.activeName].url;
      json = {
        member_id: this.data.id,
        page: this.data.dataList[that.data.activeName].page,
      };
      urlStr = app.getNetAddresss(api);
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              isLoadMore: true,
              showLoading:true,
              ['dataList[' + that.data.activeName + '].isLoadMore']:true,
              ['dataList[' + that.data.activeName + '].list']: that.data.dataList[that.data.activeName].list.concat(res.data.data),
            });
            // if (that.data.titleArr[that.data.activeName].name == "video") {
            //   that.onImageLoad();
            // }

          } else {
            that.setData({
              ['dataList[' + that.data.activeName + '].isLoadMore']:false,
              ['dataList[' + that.data.activeName + '].page']:that.data.page - 1,
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData();
    } else {
      console.log("没有更多数据");
    }
  },
  addNotice(e) {
    let that = this;
    let _parameter = e.currentTarget.dataset.notice;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let _url = null;
    if (_parameter == 1) {
      _url = "plugin.room.frontend.live-list.cancel-notice"; //取消开播提醒
    } else {
      _url = "plugin.room.frontend.live-list.play-notice"; //设置开播提醒
    }
    let urlStr = app.getNetAddresss(_url);
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: id,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (_parameter == 1) {
            that.setData({
              ["roomList[" + index + "].notice"]: 0,
            });
            wx.showToast({
              icon: "none",
              title: "已取消提醒",
              duration: 1500,
            });
          } else {
            that.setData({
              ["roomList[" + index + "].notice"]: 1,
            });
            wx.showToast({
              icon: "none",
              title: "已成功订阅",
              duration: 1500,
            });
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  goPlayBackData(e) {
    let roomid = e.currentTarget.dataset.roomid;
    let backid = e.currentTarget.dataset.backid;
    wx.navigateTo({
      url:
        "/packageD/directSeeding/livePage/livePage?id=" +
        roomid +
        "&playerType=video" +
        "&backid=" +
        backid +
        "&memberid=" +
        this.data.id,
    });
  },
  /**
	 * 图片加载函数
	 * 图片加载完成后，根据图片的高度，依次往第一列和第二列中推入数据
	 */
  onImageLoad (options) {
    let currentId = options.currentTarget.id;
    let imageWidth = options.detail.width; // 图片宽度
    let imageHeight = options.detail.height; // 图片高度

    let activitys = this.data.videoList; // 获取所有的数据资源
    let activityObj = null;
    let scle  = (imageWidth/imageHeight);

    for (let i = 0; i < activitys.length; i++) {
      if (activitys[i].video_id == currentId) {
        activityObj = activitys[i];
        break;
      }
    }

    this.data.imgCount += 1;
    let activitys1 = this.data.activitys1;
    let activitys2 = this.data.activitys2;

    if (colOneHeight <= colTwoHeight) {
      colOneHeight += (176/scle) + 60;
      activitys1.push(activityObj);
    } else {
      colTwoHeight += (176/scle) + 60;
      activitys2.push(activityObj);
    }
    // console.log("activitys1",activitys1,activitys2)
    let data = {
      activitys1: activitys1,
      activitys2: activitys2
    };

    if (this.data.imgCount >= this.data.videoList.length){
      this.setData({
        showLoading : true
      });
    }else{
      this.setData({
        showLoading : false
      });
    }

    this.setData(data);
  },
  toVideo(e) {
    let item = e.currentTarget.dataset.item;
    let page = this.data.videoList.findIndex((value, index, arr) => {
      return value.video_id === item.video_id;
    });
    page = Math.ceil((page + 1) / 10);
    wx.navigateTo({
      url: '/packageC/video_goods/VideoDetail/VideoDetail?vid=' + item.video_id + '&page=' + page
    });
  },
});
