// packageD/directSeeding/live_monitoring/live_monitoring.js
import TIM from "../../tim-wx-sdk/tim-wx";
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    roomid: "",
    show2: false,
    show3: false,
    taideRoom: "",
    tim: "",
    lasttime: "",
    //消息列表
    messageList: [],
    messagesTop: 0,
    active: 0,
    now_goods: "",
    speak: {
      memberAvatar: "",
      nickName: "",
      index: "",
      memberId: "",
    },
    shiftout: {
      memberAvatar: "",
      nickName: "",
      index: "",
      memberId: "",
    },
    chatBanList: [],
    roomBanList: [],
    //more
    chatBanisLoadMore: true,
    chatBanpage: 1,
    chatBantotal_page: 0,
    //more
    roomBanisLoadMore: true,
    roomBanpage: 1,
    roomBantotal_page: 0,
    liveBol: true,
    video_url: "",

    isLivePK: false,
    livePKData:{},
    livePKSrc:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.roomid) {
      this.setData({
        roomid: options.roomid,
      });
    }
    this.getsdkappid();
  },
  logout() {
    let that = this;
    let promise = that.data.tim.logout();
    promise
      .then(function (imResponse) {
        console.log(imResponse.data); // 登出成功
      })
      .catch(function (imError) {
        console.warn("logout error:", imError);
      });
  },
  stopcomments(e) {
    let index = e.currentTarget.dataset.index;
    let memberId = e.currentTarget.dataset.memberid;
    this.setData({
      speak: {
        memberAvatar: this.data.messageList[index].memberAvatar,
        nickName: this.data.messageList[index].nickName,
        index: index,
        memberId: memberId,
      },
      show2: true,
    });
  },
  speakaffirmbtn(e) {
    let index = e.currentTarget.dataset.index;
    let memberId = e.currentTarget.dataset.memberid;
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor-aide.chat-ban"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.taideRoom.id,
        member_id: memberId,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: "禁言成功",
            duration: 1500,
          });
          that.setData({
            ["messageList[" + index + "].show"]: false,
            show2: false,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          that.setData({
            ["messageList[" + index + "].show"]: false,
            show2: false,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  speakcancelbtn(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      ["messageList[" + index + "].show"]: false,
      show2: false,
    });
  },
  liftBanBtn(e) {
    let index = e.currentTarget.dataset.index;
    let memberId = e.currentTarget.dataset.memberid;
    let nickname = this.data.chatBanList[index].nickname;
    let chatBanList = this.data.chatBanList;
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor-aide.chat-reply"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.taideRoom.id,
        member_id: memberId,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: "已将" + nickname + "解除禁言",
            duration: 1500,
          });
          chatBanList.splice(index, 1);
          that.setData({
            chatBanList: chatBanList,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  recoverBnt(e) {
    let index = e.currentTarget.dataset.index;
    let memberId = e.currentTarget.dataset.memberid;
    // let nickname = this.data.roomBanList[index].nickname;
    let roomBanList = this.data.roomBanList;
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor-aide.room-reply"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.taideRoom.id,
        member_id: memberId,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: "该会员已恢复",
            duration: 1500,
          });
          roomBanList.splice(index, 1);
          that.setData({
            roomBanList: roomBanList,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  kickingPlayerBtn(e) {
    let index = e.currentTarget.dataset.index;
    let memberId = e.currentTarget.dataset.memberid;
    this.setData({
      shiftout: {
        memberAvatar: this.data.messageList[index].memberAvatar,
        nickName: this.data.messageList[index].nickName,
        index: index,
        memberId: memberId,
      },
      show3: true,
    });
  },
  shiftoutAffirmbtn(e) {
    let index = e.currentTarget.dataset.index;
    let memberId = e.currentTarget.dataset.memberid;
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor-aide.room-ban"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.taideRoom.id,
        member_id: memberId,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: "成功踢出直播间",
            duration: 1500,
          });
          that.setData({
            ["messageList[" + index + "].show"]: false,
            show3: false,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          that.setData({
            ["messageList[" + index + "].show"]: false,
            show3: false,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  show2CloseBtn() {
    this.setData({
      show2: false,
    });
  },
  show3CloseBtn() {
    this.setData({
      show3: false,
    });
  },
  shiftoutCancelbtn(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      ["messageList[" + index + "].show"]: false,
      show3: false,
    });
  },
  morebtn(e) {
    let index = e.currentTarget.dataset.index;
    let that = this;
    for (let i = 0; i < that.data.messageList.length; i++) {
      that.setData({
        ["messageList[" + i + "].show"]: false,
      });
    }
    that.setData({
      ["messageList[" + index + "].show"]: true,
    });
  },
  setActivebtn(e) {
    let that = this;
    let num = e.currentTarget.dataset.num;
    this.setData({
      active: num,
    });
    if (num == 2) {
      that.setData({
        //more
        chatBanisLoadMore: true,
        chatBanpage: 1,
        chatBantotal_page: 0,
      });
      this.getchatBanList();
    } else if (num == 3) {
      that.setData({
        //more
        roomBanisLoadMore: true,
        roomBanpage: 1,
        roomBantotal_page: 0,
      });
      this.getroomBanList();
    }
  },
  getchatBanList() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor-aide.chat-ban-list"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.taideRoom.id,
        page: this.data.chatBanpage,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            chatBanList: res.data.data,
            chatBantotal_page: res.data.last_page,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  statechangePK(e){
    let code = e.detail.code;
    console.log("拉取连麦:::", code);
    if (code == "2002" || code == "2002") {
      wx.hideLoading({});
    }
  },
  errorPK(e) {
    wx.hideLoading({});
    wx.showToast({
      title: '拉取连麦失败',
      icon: 'success',
      duration: 2000
    });
    console.log("拉取连麦失败:::", e);
  },
  getroomBanList() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor-aide.room-ban-list"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.taideRoom.id,
        page: this.data.roomBanpage,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            roomBanList: res.data.data,
            roomBantotal_page: res.data.last_page,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  setgoods(e) {
    let index = e.currentTarget.dataset.index;
    let that = this;
    let api = "";
    let urlStr = "";
    let goods = that.data.taideRoom.goods[index];
    if (this.data.now_goods && goods.id == this.data.now_goods.goods_id) {
      api = "plugin.room.frontend.anchor-aide.cancel-explain";
      urlStr = app.getNetAddresss(api);
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          id: that.data.roomid,
          goods_id: goods.id,
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              now_goods: "",
            });
            wx.showToast({
              icon: "none",
              title: "取消成功",
              duration: 1500,
            });
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    } else {
      api = "plugin.room.frontend.anchor-aide.explain-goods";
      urlStr = app.getNetAddresss(api);
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          id: that.data.roomid,
          goods_id: goods.id,
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              "now_goods.goods_id": goods.id,
            });
            wx.showToast({
              icon: "none",
              title: "设置成功",
              duration: 1500,
            });
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  getsdkappid() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.im.get-im-sdk");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let options = {
            SDKAppID: res.data.sdkappid, // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
          };
          // 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
          that.data.tim = TIM.create(options); // SDK 实例通常用 tim 表示
          that.data.tim.setLogLevel(0);
          that.chatEventList(); //加载聊天事件
          that.getaideRoom();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  //查询我的个人信息
  chatMyProfile() {
    let that = this;
    let promise = that.data.tim.getMyProfile();
    promise
      .then(function (imResponse) {
        console.log(imResponse.data); // 个人资料 - Profile 实例
        let myData = imResponse.data;
        if (!myData.nick) {
          that.changeMyProfile();
        }
      })
      .catch(function (imError) {
        console.warn("getMyProfile error:", imError); // 获取个人资料失败的相关信息
      });
  },
  //修改我的个人信息
  changeMyProfile() {
    let that = this;
    let promise = that.data.tim.updateMyProfile({
      nick: that.data.taideRoom.userNickname,
      avatar: that.data.taideRoom.userAvatar,
    });
    promise
      .then(function (imResponse) {
        console.log(imResponse.data); // 更新资料成功
      })
      .catch(function (imError) {
        console.warn("updateMyProfile error:", imError); // 更新资料失败的相关信息
      });
  },
  //聊天事件
  chatEventList() {
    let that = this;
    // 监听事件，例如：
    that.data.tim.on(TIM.EVENT.SDK_READY, function (event) {
      // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
      that.chatMyProfile();
      // that.chatJoinGroup()
      // event.name - TIM.EVENT.SDK_READY
    });
    that.data.tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event) {
      //防止重新接受两条信息
      if (that.data.lasttime == event.data[0].time) {
        return;
      } else {
        that.data.lasttime = event.data[0].time;
      }
      let message = event.data;
      message.forEach(function (val, index) {
        let conversationType = val.conversationType;
        //判断消息来源群或者个人
        if (conversationType == TIM.TYPES.CONV_GROUP) {
          let data = val;
          //后台发送过来的消息处理
          // if (data.from == "administrator") {
          // } else if (data.type == "TIMTextElem") {
          // } else
          if(data.payload.extension == "customPkGroup"){
            that.setData({
              livePKData: JSON.parse(data.payload.description),
              livePKSrc: that.data.roomData.play_url_rtmp.match(/(\S*)\/live\//)[1]+'/live/' + data.payload.description.streamid,
              isLivePK: true,
            });
          } else if (data.payload.extension == "customQuitPkGroup") {
            // 结束连麦
            that.setData({
              livePKData: {},
              livePKSrc: "",
              isLivePK: false
            });
          } else if (data.type == "TIMCustomElem") {
            //自定义类型解析
            if (data.payload.extension == "customText") {
              let messageList = that.data.messageList;
              let messageListData = JSON.parse(data.payload.description);
              messageListData.show = false;
              messageList.push(messageListData);
              that.setData({
                messageList,
                messagesTop: messageList.length * 1000,
              });
            }
          }
        }
        // else if (conversationType == TIM.TYPES.CONV_C2C) {
        // }
      });
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
    });

    that.data.tim.on(TIM.EVENT.MESSAGE_REVOKED, function (event) {
      // 收到消息被撤回的通知
      // event.name - TIM.EVENT.MESSAGE_REVOKED
      // event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isRevoked 属性值为 true
    });

    that.data.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function (event) {
      // 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
      // event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
      // event.data - 存储 Conversation 对象的数组 - [Conversation]
    });

    that.data.tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function (event) {
      // 收到群组列表更新通知，可通过遍历 event.data 获取群组列表数据并渲染到页面
      // event.name - TIM.EVENT.GROUP_LIST_UPDATED
      // event.data - 存储 Group 对象的数组 - [Group]
    });

    that.data.tim.on(TIM.EVENT.GROUP_SYSTEM_NOTICE_RECEIVED, function (event) {
      // 收到新的群系统通知
      // event.name - TIM.EVENT.GROUP_SYSTEM_NOTICE_RECEIVED
      // event.data.type - 群系统通知的类型，详情请参见 GroupSystemNoticePayload 的 operationType 枚举值说明
      // event.data.message - Message 对象，可将 event.data.message.content 渲染到到页面
    });

    that.data.tim.on(TIM.EVENT.PROFILE_UPDATED, function (event) {
      // 收到自己或好友的资料变更通知
      // event.name - TIM.EVENT.PROFILE_UPDATED
      // event.data - 存储 Profile 对象的数组 - [Profile]
    });

    that.data.tim.on(TIM.EVENT.BLACKLIST_UPDATED, function (event) {
      // 收到黑名单列表更新通知
      // event.name - TIM.EVENT.BLACKLIST_UPDATED
      // event.data - 存储 userID 的数组 - [userID]
    });

    that.data.tim.on(TIM.EVENT.ERROR, function (event) {
      // 收到 SDK 发生错误通知，可以获取错误码和错误信息
      // event.name - TIM.EVENT.ERROR
      // event.data.code - 错误码
      // event.data.message - 错误信息
    });

    that.data.tim.on(TIM.EVENT.SDK_NOT_READY, function (event) {
      // 收到 SDK 进入 not ready 状态通知，此时 SDK 无法正常工作
      // event.name - TIM.EVENT.SDK_NOT_READY
    });

    that.data.tim.on(TIM.EVENT.KICKED_OUT, function (event) {
      // 收到被踢下线通知
      // event.name - TIM.EVENT.KICKED_OUT
      // event.data.type - 被踢下线的原因，例如:
      //    - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
      //    - TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
      //    - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢
      wx.showToast({
        icon: "none",
        title: "您的IM被踢下线了",
        duration: 2000,
      });
    });
  },
  getaideRoom() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.room.frontend.anchor-aide.room");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        id: this.data.roomid,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            taideRoom: res.data,
            now_goods: res.data.now_goods,
          });
          if (res.data.status && res.data.status == 4) {
            that.setData({
              liveBol: false,
              video_url: res.data.video_url,
            });
          }
          if (res.data.voice_status) {
            that.setData({
              livePKData: res.data.voice_anchor,
              livePKSrc: res.data.voice_anchor.play_url.play_url_rtmp,
              isLivePK: true
            });
          }
          setTimeout(() => {
            that.chatLogin();
          }, 1000);
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      },
    });
  },
  //聊天登录
  chatLogin() {
    let that = this;
    let promise = that.data.tim.login({
      userID: that.data.taideRoom.userID.toString(),
      userSig: that.data.taideRoom.userSig,
    });
    promise
      .then(function (imResponse) {
        console.log(imResponse.data); // 登录成功
        that.chatJoinGroup();
      })
      .catch(function (imError) {
        console.warn("login error:", imError); // 登录失败的相关信息
      });
  },
  //获取群详细资料
  chatJoinGroup() {
    let that = this;
    that.data.lastGroupId = that.data.taideRoom.groupId;
    let promise = that.data.tim.joinGroup({
      groupID: that.data.taideRoom.groupId,
      type: TIM.TYPES.GRP_CHATROOM,
    });
    promise
      .then(function (imResponse) {
        switch (imResponse.data.status) {
        case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
          break; // 等待管理员同意
        case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
          console.log(imResponse.data.group); // 加入的群组资料
          break;
        default:
          break;
        }
      })
      .catch(function (imError) {
        console.warn("joinGroup error:", imError); // 申请加群失败的相关信息
      });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

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

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

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.active == 2) {
      if (this.data.chatBanisLoadMore) {
        this.getchatBanMoreData();
      } else {
        console.log("没有更多数据");
      }
    } else if (this.data.active == 3) {
      if (this.data.roomBanisLoadMore) {
        this.getroomBanMoreData();
      } else {
        console.log("没有更多数据");
      }
    }
  },
  //获取更多数据
  getchatBanMoreData() {
    const that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor-aide.chat-ban-list"
    );
    that.data.chatBanisLoadMore = false; // 防止多次请求分页数据
    if (this.data.chatBanpage >= this.data.chatBantotal_page) {
      return;
    } else {
      this.data.chatBanpage = this.data.chatBanpage + 1;
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          id: this.data.taideRoom.id,
          page: this.data.chatBanpage,
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              chatBanList: that.data.chatBanList.concat(res.data.data),
            });
          } else {
            that.setData({
              chatBanpage: that.data.chatBanpage - 1,
              chatBanisLoadMore: false,
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  //获取更多数据
  getroomBanMoreData() {
    const that = this;
    let urlStr = app.getNetAddresss(
      "plugin.room.frontend.anchor-aide.room-ban-list"
    );
    that.data.roomBanisLoadMore = false; // 防止多次请求分页数据
    if (this.data.roomBanpage >= this.data.roomBantotal_page) {
      return;
    } else {
      this.data.roomBanpage = this.data.roomBanpage + 1;
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          id: this.data.taideRoom.id,
          page: this.data.roomBanpage,
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              roomBanList: that.data.roomBanList.concat(res.data.data),
            });
          } else {
            that.setData({
              roomBanpage: that.data.roomBanpage - 1,
              roomBanisLoadMore: false,
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
