import {
  ApiModel
} from "../../utils/api";
const _Http = new ApiModel;
let rep = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dataTypes: 0, //0-全部数据 1-单独数据
    tabsList: ["我要直播", "合作商直播"], //"展会直播" tabs列表
    buttonTabs: ["当前直播", "历史直播"], //按钮tabs
    tabsIndex: 0, //tabs下标
    accountStatus: -1, //直播账号状态 1-账号正常 2-账号审核中 3-没有账号
    //liveDataCount: {}, 实时数据统计
    liveDataCountForSession: {}, //单场次数据统计
    liveSessionList: [], //直播场次列表
    liveUserList: [], //直播用户观看记录
    crLiveUserList: [], //当前直播用户观看记录
    pageNumber: 1, //当前页码
    pageTotal: 1, //列表总页数
    userPageNumber: 1, //用户当前页码
    userPageTotal: 1, //用户总列表
    isSy: true, //是否为私域直播
    myShowModel: false, //自定义model
    myShowModel2: false, // 真正申请中提示
    myShowMode3: false,
    listRowIndex: -1, //列表选中项
    CheckTheType: '当前直播', //查看类型
    onlineNumber: 0, //实时观看人数
    oldDialogue: [], //老直播聊天数据
    newDialogue: [], //新直播聊天数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取直播账号
    this.getLiveInfo()
  },
  /* 按钮tab回调 */
  tabsSelectedIitem({
    detail
  }) {
    if (detail == this.data.CheckTheType) return;
    if (detail == '历史直播') {
      if (this.data.liveSessionList.length == 0) return wx.showToast({
        title: '当前没有开播记录',
        icon: "none"
      })
    }
    this.setData({
      CheckTheType: detail
    })
  },
  /* 实时 */
  realTime() {
    /* 获取当前用户列表 */
    this.getRealTimeViewerList();
    //获取聊天
    this.getRealTimeMessageList();
    //实时观看人数
    this.getRealTimeViewers();
    rep = setInterval(() => {
      /* 获取当前用户列表 */
      this.getRealTimeViewerList();
      //获取聊天
      this.getRealTimeMessageList();
      //实时观看人数
      this.getRealTimeViewers();
    }, 3000)
  },
  //实时观看人数
  getRealTimeViewers() {
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": "getRealTimeViewers",
      "content": {
        "channelid": this.data.accountMsg.channelid
      }
    }, false).then(res => {
      if (res.msg != '成功') return;
      this.setData({
        onlineNumber: res.data.count
      })
    })
  },
  //获取聊天
  getRealTimeMessageList() {
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": "getRealTimeMessageList",
      "content": {
        "pageNumber": 1,
        "pageSize": 999,
        "channelid": this.data.accountMsg.channelid
      }
    }, false).then(res => {
      if (res.msg != '成功') return wx.showToast({
        title: res.data,
        icon: "none"
      })
      for (let i = 0; i < res.data.length; i++) {
        let data = res.data[i].datetime.split(" ");
        res.data[i].datetime = data[1]
      }
      this.setData({
        oldDialogue: res.data
      })
      /* if (this.data.oldDialogue.length == 0) {
        
      } else {
        let oldDialogue = this.data.oldDialogue,
          newDialogue = res.data;
        if (!Object.is(JSON.stringify(oldDialogue), JSON.stringify(newDialogue))) {
          let data = JSON.stringify(oldDialogue)
          for (let i = 0; i < newDialogue.length; i++) {
            if (!data.includes(newDialogue[i].id)) {
              let data = newDialogue[i].datetime.split(" ");
              newDialogue[i].datetime = data[1]
              oldDialogue.unshift(newDialogue[i]);
            }
          }
          this.setData({
            oldDialogue
          })
        }
      } */
    })
  },
  /* 获取当前用户列表 */
  getRealTimeViewerList() {
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": "getRealTimeViewerList",
      "content": {
        "pageNumber": this.data.pageNumber,
        "pageSize": 20,
        "channelid": this.data.accountMsg.channelid
      }
    }, false).then(res => {
      if (res.msg != '成功') {
        if (this.data.liveUserList.length <= 0) return wx.showToast({
          title: res.data,
          icon: "none"
        });
        return;
      }
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].playduration = Math.ceil(res.data[i].playduration / 60)
      }
      this.setData({
        crLiveUserList: res.data,
        pageTotal: res.pageTotal
      })
    })
  },
  /* 自定义model回调 */
  showModelCallBack({
    detail
  }) {
    if (detail == 'true') this.copyTheAddress(this.data.accountMsg.fliveurl_web);
  },
  showModelCallBack1({
    detail
  }) {
    if (detail == 'true') this.copyTheAddress(this.data.accountMsg.fassistanturl);
  },
  /* 显示自定义model */
  showMyModel() {
    this.setData({
      myShowModel: true
    })
  },
  showMyMode3() {
    this.setData({
      myShowMode3: true
    })
  },
  /* 申请直播账号 */
  /* applyForLive() {
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": "applySYLive",
      "content": {}
    }).then(res => {
      if (res.code == 1) {
        wx.showToast({
          title: res.msg,
          icon: "none"
        })
        this.setData({
          accountStatus: 2
        })
      } else {
        if (res.data == '私域直播已申请') return this.setData({
          myShowModel2: true
        })
      }
    })
  }, */
  /* 复制地址 */
  copyTheAddress(e) {
    const url = (typeof e == "string" || typeof e == String) ? e : e.target.dataset.url;
    wx.setClipboardData({
      data: url,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log('内容已复制') // data
          }
        })
      }
    })
  },
  /* 获取直播账号详情 */
  getLiveInfo() {
    /* const method = (this.data.tabsIndex == 0) ? 'getSYLiveInfo' : 'getLiveInfo'; */
    const method = 'getLiveInfo';
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": method,
      "content": {}
    }).then(res => {
      const isSy = (method == "getSYLiveInfo") ? true : false;
      console.log("直播账号详情", res)
      this.setData({
        accountStatus: res.code,
        accountMsg: res.data[0],
        isSy
      })
      //获取实时数据
      this.realTime()
      //直播场次列表查询
      if (res.code == 1) this.getLiveSessionList();
    })
  },
  /* 直播场次列表查询 */
  getLiveSessionList() {
    /*  const method = (this.data.tabsIndex == 0) ? "getSYLiveSessionList" : "getLiveSessionList" */
    const method = "getLiveSessionList";
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": method,
      "content": {
        "getdatafromdbanyway": true,
        "pageNumber": this.data.pageNumber,
        "pageSize": 999,
        "channelid": this.data.accountMsg.channelid
      }
    }).then(res => {
      console.log("6545654",res)
      if (res.msg != '成功') return wx.showToast({
        title: res.data,
        icon: "none"
      });
      let sessionList = [];
      for (let i = 0; i < res.data.length; i++) {
        let checkdate = res.data[i].starttime,
          time = checkdate.slice(0, checkdate.lastIndexOf('.')),
          t = time.split(' ');
        res.data[i].starttime = t[0];
        sessionList.push(t[0])
      };
      this.setData({
        liveSessionList: res.data,
        pageTotal: res.pageTotal,
        sessionList
      });
      if (res.data.length > 0) this.viewDetails(0);
    })
  },
  /* 查看场次详情 */
  selectorChange(e) {
    this.viewDetails(e.detail.value);
  },
  viewDetails(index) {
    const sessionid = this.data.liveSessionList[index].sessionid;
    this.setData({
      showStartTime: this.data.liveSessionList[index].starttime,
      sessionid
    })
    /*  const method = (this.data.tabsIndex == 0) ? "getSYLiveDataCountForSession" : "getLiveDataCountForSession" */
    const method = 'getLiveDataCountForSession';
    /* 场次详情统计 */
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": method,
      "content": {
        "sessionid": sessionid
      }
    }).then(res => {
      if (res.msg != '成功') wx.showToast({
        title: '数据统计获取失败，请稍后再试',
        icon: "none"
      })
      res.data.viewDuration = Math.ceil(res.data.viewDuration / 60);
      res.data.viewDurationAvg = Math.ceil(res.data.viewDurationAvg / 60);
      this.setData({
        liveDataCountForSession: res.data
      })
    });
    this.LiveUserList();
    this.setData({
      dataTypes: 1
    })
  },
  /* 观看用户列表 */
  LiveUserList() {
    /* 用户观看列表 */
    /* const method = (this.data.tabsIndex == 0) ? "getSYLiveUserList" : "getLiveUserList"; */
    const method = "getLiveUserList";
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": method,
      "content": {
        "getdatafromdbanyway": true,
        "pageNumber": this.data.userPageNumber,
        "pageSize": 10,
        "sessionid": this.data.sessionid,
        "channelid": this.data.accountMsg.channelid
      }
    }).then(res => {
      if (res.msg != '成功') wx.showToast({
        title: '观看列表获取失败，请稍后再试',
        icon: "none"
      })
      for (let i = 0; i < res.data.length; i++) {
        const index = res.data[i].datetime.lastIndexOf('.');
        res.data[i].datetime = res.data[i].datetime.slice(0, index);
        res.data[i].playduration = Math.ceil(res.data[i].playduration / 60);
      }
      this.setData({
        userPageTotal: res.pageTotal,
        liveUserList: res.data
      })
    });
  },
  /* 下一页 */
  buttonRightClick() {
    if (this.data.CheckTheType == '当前直播') {
      if (this.data.pageNumber == this.data.pageTotal) return wx.showToast({
        title: '已经到达最后一页',
        icon: "none"
      });
      this.setData({
        pageNumber: this.data.pageNumber + 1
      })
      this.getRealTimeViewerList()
    } else {
      if (this.data.userPageNumber == this.data.userPageTotal) return wx.showToast({
        title: '已经到达最后一页',
        icon: "none"
      });
      this.setData({
        userPageNumber: this.data.userPageNumber + 1
      })
      this.LiveUserList()
    }
  },
  /* 上一页 */
  buttonLifeClick() {
    if (this.data.CheckTheType == '当前直播') {
      if (this.data.pageNumber == 1) return wx.showToast({
        title: '已经在第一页了',
        icon: "none"
      });
      this.setData({
        pageNumber: this.data.pageNumber - 1
      })
      this.getRealTimeViewerList()
    } else {
      if (this.data.userPageNumber == 1) return wx.showToast({
        title: '已经在第一页了',
        icon: "none"
      });
      this.setData({
        userPageNumber: this.data.userPageNumber - 1
      })
      this.LiveUserList()
    }
  },
  /* 选中行 */
  listRowAvtion(e) {
    this.setData({
      listRowIndex: e.currentTarget.dataset.index
    })
  },
  /* tabs回调 */
  setIndex({
    detail
  }) {
    if (this.data.tabsIndex == detail) return;
    this.setData({
      tabsIndex: detail,
      pageNumber: 1,
      pageTotal: 1,
      userPageNumber: 1,
      userPageTotal: 1
    });
    // if (detail != 2) this.getLiveInfo();
    if (detail == 0) this.getLiveInfo();
    if (detail == 1) this.getCooperationAgentsLiveList();
  },
  /* 获取合作商直播列表 */
  getCooperationAgentsLiveList() {
    _Http.basic({
      "accesstoken": wx.getStorageSync('userData').token,
      "classname": "customer.live.live",
      "method": "getCooperationAgentsLiveList",
      "content": {}
    }).then(res => {
      this.setData({
        partnerLiveList: res.data
      })
    })
  },
  /* 查看合作商直播 */
  /*   toLive(e) {
      const {
        index
      } = e.currentTarget.dataset,
        data = this.data.partnerLiveList[index];
      if (data.fisneedauth == 1) {
        _Http.basic({
          "accesstoken": wx.getStorageSync('userData').token,
          "classname": "enterprise.live.live",
          "method": "liveauthorization",
          "content": {
            "tliveid": data.tliveid
          }
        }).then(res => {
          console.log(res)
          if (res.data != '成功') return wx.showToast({
            title: '网络错误，请稍后再试',
          })
          let str = res.msg;
          const url = str.slice(0, 8) + '04de51d4c1.' + str.slice(8);
          wx.navigateTo({
            url: '/pages/webView/index?url=' + encodeURIComponent(url),
          })
        })
      } else {
        let str = data.fliveshowurl;
        const url = str.slice(0, 8) + '04de51d4c1.' + str.slice(8);
        wx.navigateTo({
          url: '/pages/webView/index?url=' + encodeURIComponent(url)
        })
      }
    }, */
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

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

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

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(rep)
  },

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let str = this.data.accountMsg.fliveshowurl;
    const url = str.slice(0, 8) + '04de51d4c1.' + str.slice(8)
    return {
      title: this.data.accountMsg.channelname,
      path: "/pages/webView/index?url=" + url,
      imageUrl: this.data.accountMsg.channelcoverimageurl
    }
  }
})