const tools = require('../../utils/tools.js');
const getusersig = require('../../utils/getUserSig.js');
const TIM = require('../../utils/tim-wx.js');
const COS = require('../../utils/cos-wx-v5.js');
const util = require('../../utils/util.js');
Page({
  data: {
    rtcConfig: {
      sdkAppID: 1400404379, // 必要参数 开通实时音视频服务创建应用后分配的 sdkAppID
      userID: '', // 必要参数 用户 ID 可以由您的帐号系统指定
      userSig: '', // 必要参数 身份签名，相当于登录密码的作用
      template: '1v1', // 必要参数 组件模版，支持的值 1v1 grid custom ，注意：不支持动态修改, iOS 不支持 pusher 动态渲染
    },
    roomIdandcourseId: "",
    currentGroup: null,
    chatContent: [],
    inputValue: '',
    // second: 5,
    showmodal: false,
    bottom: "", //滑到底状态 防止弹出消息不跳到最后一条
    talkStatus: true, //初始值为true
    onSdkReady: function (event) {
      let _this = this;
      console.log(event, "im准备好了")
      let promise = _this.data.tim.getGroupList();
      console.log(promise, "我获取到promise的值了")
      promise.then((imResponse) => {
        console.log(imResponse.data.groupList, "我是群组列表"); // 群组列表
        if (imResponse.data.groupList.length == 0) {
          let promise = _this.data.tim.joinGroup({
            groupID: _this.data.roomIdandcourseId,
            type: TIM.TYPES.GRP_MEETING
          });
          promise.then((imResponse) => {
            switch (imResponse.data.status) {
              case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
                console.log(_this.data.currentGroup, "等待管理员同意")
                break;
              case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
                _this.setData({
                  currentGroup: imResponse.data.group
                })
                _this.getjyList(imResponse.data.group)
                console.log(_this.data.currentGroup, "加群成功") // 加入的群组资料
                break;
              case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
                console.log(imResponse, "已经在群中")
                break;
              default:
                break;
            }
          }).catch(function (imError) {
            console.warn('申请加群失败的相关信息', imError); // 申请加群失败的相关信息
          });
        } else {
          for (let i = 0; i < imResponse.data.groupList.length; i++) {
            if (imResponse.data.groupList[i].groupID == _this.data.roomIdandcourseId) {
              // console.log(imResponse.data.groupList[i])
              // let pushArr = this.data.currentGroup.push(imResponse.data.groupList[i])
              // console.log(pushArr, "我是push完的东西")
              _this.setData({
                currentGroup: imResponse.data.groupList[i]
              })
              _this.getjyList(imResponse.data.groupList[i])
            }
            if (_this.data.currentGroup == null) {
              let promise = _this.data.tim.joinGroup({
                groupID: _this.data.roomIdandcourseId,
                type: TIM.TYPES.GRP_MEETING
              });
              promise.then((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;
                  case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
                    break;
                  default:
                    break;
                }
                _this.setData({
                  currentGroup: imResponse.data.group
                })
                _this.getjyList(imResponse.data.group)
                console.log(_this.data.currentGroup, "0000000000000000")
              }).catch(function (imError) {
                console.warn('申请加群失败的相关信息', imError); // 申请加群失败的相关信息
              });
            }
          }
        }
      }).catch(function (imError) {
        console.log(imError, "获取群组列表失败的相关信息"); // 获取群组列表失败的相关信息
      });
      //修改成员名字
      let promise1 = _this.data.tim.updateMyProfile({
        nick: _this.data.miniName
      });
      promise1.then(function (imResponse) {
        console.log(imResponse.data, "更新资料成功"); // 群组列表
      }).catch(function (imError) {
        console.log(imError, "更新资料失败"); // 获取群组列表失败的相关信息
      });
    },
    onSdkRecived: function (event) {
      let _this = this;
      console.log(event.data[0], "我收到消息了")
      if (event.data[0].conversationType == "GROUP" && event.data[0].to == _this.data.currentGroup.groupID) {
        console.log("我找到这个会话了", _this.data.chatContent)
        let currentTime = util.formatTime(new Date());
        if (_this.data.chatContent.length > 0) { // 表示不是第一次填数据，可以使用push
          console.log("表示不是第一次填数据，可以使用push", _this.data.chatContent)
          const chatContent = _this.data.chatContent
          event.data[0].currentTime = currentTime;
          chatContent.push(event.data[0])
          // chatContent.push({
          //   currentTime: currentTime
          // })
          console.log(chatContent, "我是收到消息的数组")
          _this.setData({
            chatContent: chatContent,
            bottom: 'scrollBottom'
            // currentTime: currentTime
          })
        } else { // 表示第一次填数据
          // let currentTime = util.formatTime(new Date());
          console.log("表示第一次填数据", _this.data.chatContent)
          // const chatContent = _this.data.chatContent
          // let Arr = [];
          event.data[0].currentTime = currentTime
          let chatContent = []
          chatContent.push(event.data[0])
          // Arr.push(event.data)
          // console.log(event.data)
          // Arr.push({currentTime:currentTime})
          _this.setData({
            chatContent: chatContent,
            bottom: 'scrollBottom'
            // currentTime: currentTime
          })
        }
      }
      if (event.data[0].payload.data == "stopLive") {
        wx.showModal({
          content: "当前直播结束了！",
          showCancel: false,
          success(res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
      }
      if (event.data[0].payload.data == "putLocalStream") {
        _this.trtcRoomContext.publishLocalVideo();
        _this.trtcRoomContext.publishLocalAudio();
      }
      if (event.data[0].payload.data == "stopPutLocalStream") {
        _this.trtcRoomContext.unpublishLocalVideo();
        _this.trtcRoomContext.unpublishLocalAudio();
      }
      if (event.data[0].payload.data == "readyPutLocalStream") {
        _this.trtcRoomContext.showTeacherTalk();
        // _this.setData({
        //   showmodal: true
        // })
        // _this.countdown()
      }
      if (event.data[0].payload.data == "stopTalk") {
        _this.setData({
          talkStatus: false
        })
        wx.showToast({
          title: '您被老师禁言啦', //提示文字
          duration: 3000, //显示时长
          mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false  
          icon: 'none' //图标，支持"success"、"loading"  
        })
      }
      if (event.data[0].payload.data == "keepTalk") {
        _this.setData({
          talkStatus: true
        })
        wx.showToast({
          title: '您的禁言被解除了，可以正常发言啦', //提示文字
          duration: 3000, //显示时长
          mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false  
          icon: 'none' //图标，支持"success"、"loading"  
        })
      }
      // if (event.data[0].payload.data == "stopTalkList") {
      //   console.log(event.data[0].payload, "1111111111")
      //   if (event.data[0].payload.description == "false") {
      //     _this.setData({
      //       talkStatus: false
      //     })
      //     wx.showToast({
      //       title: '您被老师禁言啦', //提示文字
      //       duration: 3000, //显示时长
      //       mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false  
      //       icon: 'none' //图标，支持"success"、"loading"  
      //     })
      //   }
      // }
    }
  },
  answer() {
    // this.setData({
    //   showmodal: false,
    //   second: 5
    // });
    // clearTimeout(this.data.timer);
    let _this = this;
    let message = _this.data.tim.createCustomMessage({
      to: "teacher-" + _this.data.currentGroup.groupID,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        data: 'yesStudentPutHand'
      }
    });
    let promise = _this.data.tim.sendMessage(message);
    promise.then(function (imResponse) {
      console.log(imResponse, "我给老师发消息说我同意啦");
    }).catch(function (imError) {
      console.warn('我给老师发消息说我同意失败啦', imError);
    });
  },
  refuse() {
    // this.setData({
    //   showmodal: false,
    //   second: 5
    // });
    // clearTimeout(this.data.timer);
    let _this = this;
    let message = _this.data.tim.createCustomMessage({
      to: "teacher-" + _this.data.currentGroup.groupID,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        data: 'notStudentPutHand'
      }
    });
    let promise = _this.data.tim.sendMessage(message);
    promise.then(function (imResponse) {
      console.log(imResponse, "我给老师发消息说我不同意");
    }).catch(function (imError) {
      console.warn('我给老师发消息说我不同意失败啦', imError);
    });
  },
  // countdown() {
  //   var second = this.data.second
  //   if (second == 0) {
  //     this.refuse();
  //     return;
  //   }
  //   this.setData({
  //     timer: setTimeout(() => {
  //       this.setData({
  //         second: second - 1
  //       });
  //       this.countdown();
  //     }, 1000)
  //   })
  // },
  // 举手
  handsup() {
    console.log(this.data.currentGroup, "0000000000")
    if (this.data.talkStatus) {
      let message = this.data.tim.createCustomMessage({
        to: "teacher-" + this.data.currentGroup.groupID,
        conversationType: TIM.TYPES.CONV_C2C,
        payload: {
          data: 'studentPutHand'
        }
      });
      let promise = this.data.tim.sendMessage(message);
      promise.then(function (imResponse) {
        console.log(imResponse);
        wx.showToast({
          title: '举手成功',
          icon: 'success',
          duration: 2000,
          mask: true
        })
      }).catch(function (imError) {
        console.warn('sendMessage error:', imError);
      });
    } else {
      wx.showToast({
        title: '您被老师禁言啦', //提示文字
        duration: 3000, //显示时长
        mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false  
        icon: 'none' //图标，支持"success"、"loading"  
      })
    }
  },
  //发送禁言列表消息
  getjyList(e) {
    let message = this.data.tim.createCustomMessage({
      to: "teacher-" + e.groupID,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        data: 'getStopTalkList'
      }
    });
    let promise = this.data.tim.sendMessage(message);
    promise.then(function (imResponse) {
      console.log("成功", imResponse);
    }).catch(function (imError) {
      console.warn('sendMessage error:', imError);
    });
  },
  // 发消息
  sendMessage() {
    if (this.data.talkStatus) {
      if (this.data.inputValue == null || this.data.inputValue == "") {
        wx.showModal({
          content: "不可以发送空消息哦!",
          showCancel: false
        })
        return false
      }
      console.log(this.data.currentGroup)
      let message = this.data.tim.createTextMessage({
        to: this.data.currentGroup.groupID,
        conversationType: TIM.TYPES.CONV_GROUP,
        priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
        payload: {
          text: this.data.inputValue
        }
      });
      let promise = this.data.tim.sendMessage(message);
      promise.then((imResponse) => {
        console.log(imResponse, "发送成功");
        let currentTime = util.formatTime(new Date());
        console.log(currentTime, "00000")
        if (this.data.chatContent.length > 0) { // 表示不是第一次填数据，可以使用push
          console.log("表示不是第一次填数据，可以使用push", this.data.chatContent)
          const chatContent = this.data.chatContent
          chatContent.push({
            nick: this.data.miniName,
            payload: {
              text: this.data.inputValue
            },
            currentTime: currentTime
          })
          console.log(chatContent, "11111")
          this.setData({
            chatContent: chatContent,
            bottom: 'scrollBottom'
          })
        } else { // 表示第一次填数据
          console.log("表示第一次填数据", this.data.chatContent)
          this.setData({
            chatContent: [{
              nick: this.data.miniName,
              payload: {
                text: this.data.inputValue
              },
              currentTime: currentTime
            }],
            bottom: 'scrollBottom'
          })
          console.log(this.data.chatContent, "2222")
        }
        this.setData({
          inputValue: ''
        })
      }).catch(function (imError) {
        console.warn('发送失败', imError);
      });
    } else {
      wx.showToast({
        title: '您被老师禁言啦', //提示文字
        duration: 3000, //显示时长
        mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false  
        icon: 'none' //图标，支持"success"、"loading"  
      })
    }
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  // 滑动聊天室
  scrollToTop() {
    this.setAction({
      scrollTop: 0
    })
  },
  async onTim() {
    this.data.tim.on(TIM.EVENT.SDK_READY, this.data.onSdkReady, this);
    this.data.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.data.onSdkRecived, this);
    const sig = await getusersig.genTestUserSig(this.data.rtcConfig.userID, this.data.rtcConfig.sdkAppID, "f1ca85809aed35d82d8bb76612787e38dada5d0a6f233662777b42bdb7eb880b")
    let promise = this.data.tim.login({
      userID: this.data.rtcConfig.userID,
      userSig: sig.userSig
    });
    promise.then((imResponse) => {
      console.log(imResponse.data, "登录成功"); // 登录成功
      if (imResponse.data.repeatLogin === true) {
        console.log(imResponse.data.errorInfo);
      }
    }).catch(function (imError) {
      console.warn('登录失败的相关信息', imError); // 登录失败的相关信息
    });
  },
  offTim() {
    this.data.tim.off(TIM.EVENT.SDK_READY, this.data.onSdkReady);
    this.data.tim.off(TIM.EVENT.MESSAGE_RECEIVED, this.data.onSdkRecived);
    console.log(this.data.roomIdandcourseId, "我是退出的群组")
    this.data.tim.quitGroup(this.data.roomIdandcourseId);
    let promise = this.data.tim.logout();
    promise.then(function (imResponse) {
      console.log(imResponse.data, " 登出成功");
    }).catch(function (imError) {
      console.warn(' 登出失败:', imError);
    });
  },
  bindTRTCRoomEvent: function () {
    console.log(this.data.roomIdandcourseId, typeof (this.data.roomIdandcourseId), "我开始监听了。。。。。")
    this.trtcRoomContext.enterRoom({
      roomID: Number(this.data.roomIdandcourseId) //课程id
      // userID: this.data.rtcConfig.userID
    })
    const TRTC_EVENT = this.trtcRoomContext.EVENT
    this.trtcRoomContext.on(TRTC_EVENT.LOCAL_JOIN, (event) => {
      console.log('我加入房间了', event)
    })
    this.trtcRoomContext.on(TRTC_EVENT.LOCAL_LEAVE, (event) => {
      console.log('我离开房间了', event)
    })
    this.trtcRoomContext.on(TRTC_EVENT.ERROR, (event) => {
      console.log('进入房间出错了', event)
    })
    // 远端用户进入房间
    this.trtcRoomContext.on(TRTC_EVENT.REMOTE_USER_JOIN, (event) => {
      console.log('远端用户进入房间')
    })
    // 远端用户退出
    this.trtcRoomContext.on(TRTC_EVENT.REMOTE_USER_LEAVE, (event) => {
      console.log('远端用户退出')
    })
    this.trtcRoomContext.on(TRTC_EVENT.REMOTE_AUDIO_ADD, (event) => {
      console.log(event, "lalalallalalalalal")
      this.trtcRoomContext.subscribeRemoteAudio({
        userID: event.data.userID
      }).then(() => {
        console.log("音频订阅成功")
      })
    })
    // 远端用户取消推送音频
    this.trtcRoomContext.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, (event) => {
      this.trtcRoomContext.unsubscribeRemoteAudio({
        userID: event.data.userID
      }).then(() => {
        console.log("音频取消订阅")
      })
    })
    this.trtcRoomContext.on(TRTC_EVENT.REMOTE_VIDEO_ADD, (event) => {
      this.trtcRoomContext.subscribeRemoteVideo({
        userID: event.data.userID,
        streamType: event.data.streamType
      }).then(() => {
        console.log("远端视频订阅成功")
      })
    })
    this.trtcRoomContext.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, (event) => {
      this.trtcRoomContext.unsubscribeRemoteVideo({
        userID: event.data.userID,
        streamType: event.data.streamType
      }).then(() => {
        console.log("远端视频取消订阅")
      })
    })
  },
  onLoad(options) {
    console.log(options, "99999");
    this.setData({
      roomIdandcourseId: options.id
    })
  },
  async onShow() {

    const sessionKey = await tools.checkSessionAndLogin();
    const information = await tools.request('/wx/student/selStudentSessionKeyEcho', {
      sessionKey
    }, 'POST');
    this.setData({
      miniName: information.data.data.miniName,
      ['rtcConfig.userID']: information.data.data.id.toString()
    })
    const sig = await getusersig.genTestUserSig(this.data.rtcConfig.userID, this.data.rtcConfig.sdkAppID, "f1ca85809aed35d82d8bb76612787e38dada5d0a6f233662777b42bdb7eb880b")
    this.setData({
      ['rtcConfig.userSig']: sig.userSig
    })
    //保持页面常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
    })
    this.trtcRoomContext = this.selectComponent('#trtcroom')
    this.bindTRTCRoomEvent()
    let option = {
      SDKAppID: 1400404379 // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
    };
    this.setData({
      tim: TIM.create(option)
    })
    this.data.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
    this.data.tim.registerPlugin({
      'cos-wx-sdk': COS
    });
    this.onTim();
  },
  onHide() {
    console.log("我onhide了")
    this.trtcRoomContext.unpublishLocalVideo();
    this.trtcRoomContext.unpublishLocalAudio();
    this.offTim();
  },
  onUnload() {
    console.log("onUnload")
    this.trtcRoomContext.unpublishLocalVideo();
    this.trtcRoomContext.unpublishLocalAudio();
    this.offTim();
  }
})