import { GetRoomInfo, GetRoomUser, GetShowUser, GetApplySpeak, PostMuteAll, PostOpenMicr, PostOpenCamera, DeleteRoomManager } from '../../api/meeting/index'
import { GetRoomRtcToken } from '../../api/form/index'
import { agora } from '../../utils/agora'
import { onInvoke, onSignalr, getSignIr, offSignalr, onStop } from '../../utils/singlr'
import { role, getStorage } from '../../utils/utils'
import { Message, Toast } from 'tdesign-miniprogram';
import * as signalR from "signalr-for-wx";
import dayjs from 'dayjs';
const computedBehavior = require('miniprogram-computed').behavior;
let reconnectTime = "" as any;
let refreshTime = "" as any;
let isAutoApplySpeakTime = "" as any;
let isSpeakTime = "" as any;
let netWorkTime = "" as any;
let isReconnecTime = "" as any;
Page({
  behaviors: [computedBehavior],
  data: {
    footerList: [
      {
        title: '关闭听筒',
        titleActive: '开启听筒',
        active: true,
        icon: '/assets/icon1.png',
        iconActive: '/assets/icon1-active.png',
        show: false,
      },
      {
        title: '静音',
        titleActive: '解除静音',
        active: false,
        icon: '/assets/icon2.png',
        iconActive: '/assets/icon2-active.png',
        show: true,
      },
      {
        title: '关闭视频',
        titleActive: '打开视频',
        active: false,
        icon: '/assets/icon3.png',
        iconActive: '/assets/icon3-active.png',
        show: true,
      },
      {
        title: '翻转',
        titleActive: '翻转',
        active: true,
        icon: '/assets/icon4.png',
        iconActive: '/assets/icon4.png',
        show: false,
      },
      {
        title: '聊天',
        titleActive: '聊天',
        active: true,
        icon: '/assets/icon5.png',
        iconActive: '/assets/icon5.png',
        show: true,
      },
      {
        title: '成员',
        titleActive: '成员',
        active: true,
        icon: '/assets/icon6.png',
        iconActive: '/assets/icon6.png',
        show: true,
      },
      {
        title: '申请发言',
        titleActive: '结束发言',
        active: true,
        icon: '/assets/icon7.png',
        iconActive: '/assets/icon7-active.png',
        show: true,
      },
    ],
    channelId: '',
    tabBarIndex: 1,
    roomInfo: '',
    roomUserList: [],
    audioList: [],
    userVolume: 0,
    chatList: [],
    isAdmin: 0,
    currentUid: '',
    currentUser: '',
    userNumer: 0,
    scrollTop: 0,
    noViewChatList: 0,
    applySpeakDialog: false,
    leaveDialog: false,
    userPopupVisible: false,
    chatPopupVisible: false,
    inputPopupVisible: false,
    isFullscreen: false,
    muted: false,
    currentRequestSpeakType: '',
    user: '',
    messageStr: '',
    inputStr: '',
    commonlyChatList: [
      '能听到我说话吗？',
      '听得到',
      '听不到',
      '我要发言',
    ],
    isFirstShow: true,
    isCurrePage: true,
    isReconnec: false,
    isAutoApplySpeakDialog: false,
    showScroll: false,
    reconnecNumber: 0,
    setting: {
      voiceStimulation: true, //语音激励
    },
    network: 0,
    meSrc: '',
    watchUids: []
  },
  watch: {
    'roomUserList.**': function (roomUserList) {
      this.setData({
        isAdmin: roomUserList.filter((item: any) => (role.ID.includes(item.roleId) || item.isRoomManager) && item.isRoom).length,
        userNumer: roomUserList.filter((item: any) => item.isRoom).length,
        audioList: roomUserList.map(item => {
          return {
            volume: item.volume || '0%',
            volumeNumber: item.volumeNumber || 0,
            uid: item.uid,
          }
        })
      })
      const item = roomUserList.find(row => row.uid == this.data.currentUid || row.screenShareId == this.data.currentUid)
      if (item) {
        this.setData({
          currentUser: item,
        })
        if (!((role.ID.includes(item.roleId) || item.isRoomManager) && item.isRoom)) {
          this.getShowUser()
        }
      }
    },
    'footerList.**': function (footerList) {
      const footerListTemplate = [...footerList];
      footerListTemplate[3].show = footerListTemplate[2].active
      // if (!footerListTemplate[1].active && !footerListTemplate[2].active) {
      //   if (isAutoApplySpeakTime) {
      //     clearTimeout(isAutoApplySpeakTime)
      //     isAutoApplySpeakTime = ''
      //   }
      //   isAutoApplySpeakTime = setTimeout(() => {
      //     let userItem = this.data.roomUserList.find((item: any) => item.uid === this.data.user.uid)
      //     if (!role.ID.includes(this.data.user.roleId) && userItem && userItem.isRoomManager) {
      //       DeleteRoomManager({
      //         roomId: this.data.roomInfo.id,
      //         roomNum: this.data.channelId,
      //         userId: userItem.uid
      //       })
      //       this.setData({
      //         isAutoApplySpeakDialog: true
      //       })
      //     }
      //     clearTimeout(isAutoApplySpeakTime)
      //     isAutoApplySpeakTime = ''
      //   }, 1000 * 60 * 5);
      // } else {
      //   if (isAutoApplySpeakTime) {
      //     clearTimeout(isAutoApplySpeakTime)
      //     isAutoApplySpeakTime = ''
      //   }
      // }
      this.setData({
        footerList: footerListTemplate
      })
    },
    'isClicked': function (isClicked) {
      if (isClicked) {
        let timer = setTimeout(() => {
          this.setData({
            isClicked: false,
          })
          clearTimeout(timer)
        }, 10000);
      }
    },
    'isCurrePage': function (isCurrePage) {
      if (isCurrePage) {
        this.clearTimer()
      } else {
        refreshTime = setInterval(() => {
          GetRoomUser(this.data.channelId).then(res => {
            if (res.code === 200) {
              res.data.forEach((item: any) => {
                let row = this.data.roomUserList.find((row: any) => row.uid == item.uid);
                if (row) {
                  row.enableCamera = item.enableCamera;
                  row.enableMicr = item.enableMicr;
                  row.isRoomManager = item.isRoomManager;
                  row.isAdmin = role.ID.includes(item.roleId) || item.isRoomManager;
                }
              });
              this.changeAgoraDevice()
            }
          })
        }, 1000 * 30)
      }
    },
    'currentUid': function (currentUid) {
      this.data.roomUserList.forEach(item => {
        if (item.src) {
          if (item.uid == currentUid) {
            agora.setRemoteVideoStreamType(Number(item.uid), 0)
          } else {
            agora.setRemoteVideoStreamType(Number(item.uid), 1)
          }
        }
      });
      const item = this.data.roomUserList.find(row => row.uid == currentUid || row.screenShareId == currentUid)
      if (item) {
        this.setData({
          currentUser: item,
        })
      }
    },
    'isAdmin': function (isAdmin) {
      const query = wx.createSelectorQuery()
      query.select('#meeting-content-smallvideo').fields({ size: true, scrollOffset: true }, (res) => {
        this.setData({
          showScroll: Math.ceil(isAdmin * 94) > Math.ceil(res.height)
        })
      })
      query.exec()
    }
  },
  async onLoad(option) {
    wx.enableAlertBeforeUnload({
      message: "确定要离开房间吗？"
    })
    this.setData({
      channelId: option.roomNum,
      user: await getStorage('user')
    })
    await this.joinChannel()
    await this.getRoomUser()
    await this.getShowUser()
    this.startClientEvent()
    this.startSignalr()
    await this.getRoomInfo()
    const that = this;
    wx.getStorage({
      key: 'historicalList',
      success(res: any) {
        const list = [...res.data]
        if (list.length >= 3) {
          list.splice(0, 1)
        }
        list.push({
          nickName: option.nickName,
          roomNum: option.roomNum,
          roomName: that.data.roomInfo.roomName
        })
        wx.setStorage({
          key: "historicalList",
          data: list
        })
      },
      fail() {
        wx.setStorage({
          key: "historicalList",
          data: [{
            nickName: option.nickName,
            roomNum: option.roomNum,
            roomName: that.data.roomInfo.roomName
          }]
        })
      }
    })
  },
  onReady() {
    wx.onNetworkStatusChange(this.listener)
    this.setStorageData()
  },
  async onShow() {
    if (netWorkTime) {
      clearTimeout(netWorkTime)
      netWorkTime = ''
    }
    this.getNetWorkSpeed()
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
    this.setData({
      isCurrePage: false
    })
    if (this.data.isFirstShow) {
      this.setData({
        isFirstShow: false,
      })
    } else {
      this.reconnecFun()
    }
    isSpeakTime = setInterval(() => {
      if (this.data.setting.voiceStimulation) {
        function getMaxObject(arr) {
          let maxObject = arr[0];
          for (let i = 1; i < arr.length; i++) {
            if (arr[i].volumeNumber > maxObject.volumeNumber) {
              maxObject = arr[i];
            }
          }
          return maxObject;
        }
        const isShare = this.data.roomUserList.find(item => item.shareSrc)
        const item = getMaxObject(this.data.audioList)
        const user = this.data.roomUserList.find(row => item.uid === row.uid)
        if (item && (this.data.currentUid !== item.uid && !isShare && (user && user.isRoom) && item.volumeNumber > 0 && item.uid !== this.data.user.uid)) {
          this.setData({
            currentUid: item.uid
          })
        }
      }
    }, 3000)
  },
  // 隐藏
  onHide() {
    this.setData({
      isCurrePage: true,
    })
    this.clearTimer()
  },
  // 卸载
  onUnload() {
    wx.offNetworkStatusChange(this.listener)
    this.clearTimer()
  },
  // 获取网络质量
  getNetWorkSpeed() {
    this.getNetworkStatus().then(networkStatus => {
      this.setData({
        network: networkStatus,
      })
      netWorkTime = setTimeout(() => {
        this.getNetWorkSpeed()
      }, 3000);
    })
  },
  getNetworkStatus() {
    const DOWNLOAD_TIME = [500, 1500];
    return new Promise((resolve) => {
      try {
        let networkStatus = 0
        this.getNetworkType().then(({ networkType }) => {
          if (['unknown', 'none'].includes(networkType)) {
            return resolve(-1);
          }
          if (['2g', '3g'].includes(networkType)) {
            return resolve(2);
          }
          const startTime = +new Date();
          this.requestImage().then(() => {
            const requestTime = +new Date() - startTime;
            if (requestTime < DOWNLOAD_TIME[0]) {
              networkStatus = 0;
            } else if (requestTime > DOWNLOAD_TIME[1]) {
              networkStatus = 1
            } else {
              networkStatus = 2;
            }
            return resolve(networkStatus);
          })
        });
      } catch (error) {
        resolve(0);
      }
    })
  },
  requestImage() {
    return new Promise((resolve) => {
      wx.request({
        url: `https://meeting-api.23544.com/meeting/update/ddq.png?t=${+new Date()}`,
        success() {
          resolve('');
        },
        fail() {
          resolve('')
        }
      })
    })
  },
  getNetworkType() {
    return new Promise((resolve) => {
      wx.getNetworkType({
        success(res) {
          resolve(res);
        },
        fail(err) {
          resolve(err);
        }
      })
    })
  },
  // 设置缓存
  async setStorageData() {
    const setting: any = await getStorage('setting')
    if (setting) {
      this.setData({
        setting
      })
    } else {
      wx.setStorage({
        key: "setting",
        data: this.data.setting
      })
    }
  },
  // 重连
  async reconnecFun() {
    if (isReconnecTime) {
      clearTimeout(isReconnecTime)
      isReconnecTime = ''
    }
    isReconnecTime = setTimeout(() => {
      wx.hideLoading()
      this.setData({
        isReconnec: true
      })
    }, 1000 * 30);
    wx.hideLoading()
    wx.showLoading({
      title: '重连中',
      mask: true
    })
    if (reconnectTime) {
      clearTimeout(reconnectTime)
      reconnectTime = ''
    }
    agora.destroy(() => {
      this.startReconnec()
    })
  },
  async startReconnec() {
    if (getSignIr() === signalR.HubConnectionState.Connected) {
      clearTimeout(reconnectTime)
      reconnectTime = ''
      await GetRoomRtcToken(this.data.channelId).then(res => {
        if (res.code === 200) {
          agora.reconnecSetOption(res.data, async (bool) => {
            if (bool) {
              await this.joinChannel()
              this.startClientEvent()
              this.startSignalr()
              await this.getRoomUser()
              await this.getShowUser()
              Message.success({
                context: this,
                offset: [20, 32],
                duration: 3000,
                content: '重连成功',
              });
              this.setData({
                isReconnec: false
              })
              if (isReconnecTime) {
                clearTimeout(isReconnecTime)
                isReconnecTime = ''
              }
            } else {
              this.setData({
                isReconnec: true
              })
            }
            wx.hideLoading()
          })
        } else {
          wx.hideLoading()
          this.setData({
            isReconnec: true
          })
        }
      }).catch(() => {
        wx.hideLoading()
        this.setData({
          isReconnec: true
        })
      })
    } else {
      if (this.data.reconnecNumber > 10) {
        this.setIsConnectedBack()
      } else {
        this.setData({
          reconnecNumber: this.data.reconnecNumber + 1
        })
        reconnectTime = setTimeout(() => {
          this.startReconnec()
        }, 3000)
      }
    }
  },
  // 清除定时器
  clearTimer() {
    if (refreshTime) {
      clearInterval(refreshTime)
      refreshTime = ''
    }
    if (reconnectTime) {
      clearTimeout(reconnectTime)
      reconnectTime = ''
    }
    if (isAutoApplySpeakTime) {
      clearTimeout(isAutoApplySpeakTime)
      isAutoApplySpeakTime = ''
    }
    if (isSpeakTime) {
      clearInterval(isSpeakTime)
      isSpeakTime = ''
    }
    if (netWorkTime) {
      clearTimeout(netWorkTime)
      netWorkTime = ''
    }
    if (isReconnecTime) {
      clearTimeout(isReconnecTime)
      isReconnecTime = ''
    }
  },
  // 显示聊天输入框
  showInputPopup() {
    this.setData({
      inputPopupVisible: true,
      inputStr: this.data.messageStr,
      chatPopupVisible: false
    })
  },
  // 隐藏聊天输入框
  hideInputPopup() {
    this.setData({
      inputPopupVisible: false,
      messageStr: this.data.inputStr,
      chatPopupVisible: true
    })
  },
  // 申请发言提示框
  confirmIsAutoApplySpeakDialog() {
    if (!this.data.isClicked) {
      GetApplySpeak(this.data.channelId).then(res => {
        if (res.code === 200) {
          this.setData({
            isClicked: true,
          })
          this.message('申请发言成功').success()
        }
        this.setData({
          isAutoApplySpeakDialog: false
        })
      }).catch(() => {
        this.setData({
          isAutoApplySpeakDialog: false
        })
      })
    } else {
      this.message('申请太频繁了，请稍后重试！').error();
    }
  },
  // 关闭发言断开弹窗
  cancelIsAutoApplySpeakDialog() {
    this.setData({
      isAutoApplySpeakDialog: false
    })
  },
  // socket监听
  startSignalr() {
    offSignalr()
    onSignalr(async (item) => {
      if (this.data.isCurrePage) {
        const item = this.data.roomUserList.find(row => row.uid === this.data.user.uid)
        if (item && !item.isRoomManager) {
          return
        }
      }
      const userInfo: any = await getStorage('user')
      switch (item.key) {
        // 聊天
        case 'ReceiveMessage':
          if (!this.data.chatPopupVisible) {
            this.setData({
              noViewChatList: this.data.noViewChatList += 1
            })
          }
          item.timestamp = dayjs(item.timestamp).format('HH:mm:ss')
          this.setData({
            chatList: [...this.data.chatList, item]
          })
          this.scrollToBottom()
          break;
        // 扩展操作
        case 'Operation':
          // 4:屏幕共享
          break;
        // 全员离开房间
        case 'AllLeave':
          wx.setStorage({
            key: "isAllLeave",
            data: true
          })
          this.closeRoom()
          break;
        // 移出会议
        case 'ForceExitRoom':
          wx.setStorage({
            key: "isForceExitRoom",
            data: true
          })
          this.closeRoom()
          break;
        // 更新视图模式
        case 'RefreshView':

          break;
        // 全员看他
        case 'ShowUser':
          if (item.operUid && item.operUserName) {
            if (item.operUid !== userInfo.uid) {
              if (item.uid === userInfo.uid) {
                this.message(`${item.operUserName}设置全员看你`).success()
              } else {
                this.message(`${item.operUserName}设置全员看${item.uname}`).success()
              }
            }
          }
          this.getShowUser()
          break;
        // 用户加入频道回调
        case 'UserJoined':
          this.setAllUserListData('UserJoined', item)
          break;
        // 用户退出频道回调
        case 'UserLeave':
          this.setAllUserListData('UserLeave', item)
          if (item.uid === this.data.currentUid) {
            this.getShowUser();
          }
          break;
        // 所有用户开闭麦
        case 'OperAllMicr':
          this.setAllUserListData('OperAllMicr', item)
          break;
        // 用户关闭开启麦克风
        case 'OperMicr':
          if (item.operUid !== userInfo.uid) {
            if (item.user.uid === userInfo.uid) {
              this.message(item.user.enableMicr ? '管理员已取消你的静音' : '你已被管理员静音').success()
            }
          }
          this.setAllUserListData('OperMicr', item)
          break;
        // 用户开启关闭摄像头
        case 'OperCamera':
          if (item.operUid !== userInfo.uid) {
            if (item.user.uid === userInfo.uid) {
              this.message(item.user.enableCamera ? '管理员已开启你的摄像头' : '管理员已关闭你摄像头').success()
            }
          }
          this.setAllUserListData('OperCamera', item)
          break;
        // 发言人用户信息刷新
        case 'ManagerRefresh':
          this.setAllUserListData('ManagerRefresh', item, async () => {
            if (item.user.uid === item.uid) {
              if (item.user.uid === userInfo.uid) {
                await agora.allJoinChannelEx(item.user, false, (url: string) => {
                  const roomUserListTemp = [...this.data.roomUserList]
                  const itemUser = roomUserListTemp.find(row => row.uid == userInfo.uid)
                  itemUser.src = url
                  this.setData({
                    meSrc: url,
                    roomUserList: roomUserListTemp,
                  })
                })
                this.message(`操作成功`).success()
                await agora.setRole(item.user.isRoomManager, (url: string) => {
                  const roomUserListTemp = [...this.data.roomUserList]
                  const itemUser = roomUserListTemp.find(row => row.uid == userInfo.uid)
                  itemUser.src = url
                  this.setData({
                    meSrc: url,
                    roomUserList: roomUserListTemp,
                  })
                })
                await this.postOpenMicrApi(item.user.isRoomManager, userInfo.uid, false)
                await this.postOpenCameraApi(false, userInfo.uid) // 不管身份如何改变都关闭摄像头
              } else {
                this.message(`${item.user.userName}已结束发言`).success()
              }
            } else {
              if (item.user.uid === userInfo.uid) {
                await agora.allJoinChannelEx(item.user, false, (url: string) => {
                  const roomUserListTemp = [...this.data.roomUserList]
                  const itemUser = roomUserListTemp.find(row => row.uid == userInfo.uid)
                  itemUser.src = url
                  this.setData({
                    meSrc: url,
                    roomUserList: roomUserListTemp,
                  })
                })
                this.message(`管理员${item.user.isRoomManager ? '设置' : '取消'}您为发言人`).success()
                await agora.setRole(item.user.isRoomManager, (url: string) => {
                  const roomUserListTemp = [...this.data.roomUserList]
                  const itemUser = roomUserListTemp.find(row => row.uid == userInfo.uid)
                  itemUser.src = url
                  this.setData({
                    meSrc: url,
                    roomUserList: roomUserListTemp,
                  })
                })
                if (this.data.currentRequestSpeakType === 'video') {
                  await this.postOpenCameraApi(item.user.isRoomManager, userInfo.uid)
                } else if (this.data.currentRequestSpeakType === 'audio') {
                  await this.postOpenMicrApi(item.user.isRoomManager, userInfo.uid, false)
                } else {
                  await this.postOpenMicrApi(item.user.isRoomManager, userInfo.uid, false)
                  await this.postOpenCameraApi(false, userInfo.uid)
                }
                this.setData({
                  currentRequestSpeakType: ''
                })
              } else {
                this.message(`管理员${item.user.isRoomManager ? '设置' : '取消'}${item.user.userName}为发言人`).success()
              }
            }
          })
          break;
        // 申请发言
        case 'ApplyToSpeak':

          break;
        // 管理员查看随机用户
        case 'Watch':
          if (!role.ID.includes(userInfo.roleId)) {
            let userId = item.watchUids.find((uid: any) => uid === userInfo.uid)
            this.setData({
              watchUids: item.watchUids
            })
            let userRow = this.data.roomUserList.find((row: any) => row.uid === userId)
            if (userId) {
              await agora.allJoinChannelEx(userRow, true, (url: string) => {
                const roomUserListTemp = [...this.data.roomUserList]
                const itemUser = roomUserListTemp.find(row => row.uid == userInfo.uid)
                itemUser.src = url
                this.setData({
                  roomUserList: roomUserListTemp,
                  meSrc: url,
                })
              })
            } else {
              await agora.allJoinChannelEx(userRow, false, (url: string) => {
                const roomUserListTemp = [...this.data.roomUserList]
                const itemUser = roomUserListTemp.find(row => row.uid == userInfo.uid)
                itemUser.src = url
                this.setData({
                  roomUserList: roomUserListTemp,
                  meSrc: url,
                })
              })
            }
          }
          break;
        // 设备列表
        case 'DriverList':

          break;
        // 设置设备
        case 'SaveDriver':

          break;
        // 显示设备列表
        case 'ShowDriverList':

          break;
        // 修改用户名称
        case 'ModifyNickName':
          this.setAllUserListData('ModifyNickName', item)
          break;
        case 'SetSpeaker':
          await onInvoke('SetSpeakerCallback', item.RoomManagerInputDTO)
          break;
        // 扩展参数
        case 'ReceivedOperation':
          try {
            const temp = JSON.parse(item.contentString)
            if (temp.type === 'audio') {
              await PostOpenMicr({
                roomNum: temp.roomNum,
                uid: temp.uid,
                enableMicr: temp.enableMicr
              })
            } else {
              await PostOpenCamera({
                roomNum: temp.roomNum,
                uid: temp.uid,
                enableCamera: temp.enableCamera
              })
            }
          } catch (error) {

          }
          break;
        // 共享人取消共享屏幕
        case 'StopedSharedScreen':
          this.getShowUser()
          break;
      }
    })
  },
  // 声网监听
  startClientEvent() {
    agora.clientEvent({
      streamAdded: async (url: string, uid: number | string) => {
        const roomUserListTemp = [...this.data.roomUserList]
        const item = roomUserListTemp.find(row => row.uid == uid || row.screenShareId == uid)
        if (item) {
          if (String(uid).length === 9) {
            item.shareSrc = url
          } else {
            item.src = url
          }
        }
        this.setData({
          roomUserList: roomUserListTemp,
        })
      },
      streamRemoved: (uid) => {
        const roomUserListTemp = [...this.data.roomUserList]
        uid.forEach(id => {
          if (String(id).length === 9) {
            const item = roomUserListTemp.find(row => row.uid == id || row.screenShareId == id)
            item.shareSrc = ''
            this.setData({
              roomUserList: roomUserListTemp,
            })
          }
        });
      },
      tokenRef: () => {
        GetRoomRtcToken(this.data.channelId).then(res => {
          if (res.code === 200) {
            agora.renewToken(res.data)
          }
        })
      },
      updateUrl: (e) => {
        const roomUserListTemp = [...this.data.roomUserList]
        const item = roomUserListTemp.find(row => row.uid == e.uid || row.screenShareId == e.uid)
        if (item) {
          if (String(e.uid).length === 9) {
            item.shareSrc = e.url;
          } else {
            item.src = e.url;
          }
        }
      },
      error: (e) => {
        this.reconnecFun()
      },
    })
  },
  // 获取房间用户
  async getRoomUser(): Promise<void> {
    await GetRoomUser(this.data.channelId).then(res => {
      if (res.code === 200) {
        res.data.forEach((item) => {
          item.isRoom = true;
          item.isAdmin = role.ID.includes(item.roleId) || item.isRoomManager
          item.avatarName = item.userName?.slice(-2)
        })
        this.setData({
          roomUserList: res.data
        })
      }
    })
  },
  // 切换tab
  setTabBarIndex(e) {
    this.setData({
      tabBarIndex: Number(e.currentTarget.dataset.tabbarindex)
    })
    this.setStorageData()
  },
  // 修改缓存设置
  changeSetting(e) {
    this.data.setting[e.currentTarget.dataset.str] = e.detail.value
    wx.setStorage({
      key: "setting",
      data: this.data.setting
    })
  },
  // 成员显示用户名称
  showMultiText(e) {
    Toast({
      context: this,
      selector: '#t-toast',
      message: e.currentTarget.dataset.item.userName,
    });
  },
  // 查看全员观看
  async getShowUser(): Promise<void> {
    await GetShowUser(this.data.channelId).then(async (res) => {
      if (res.code === 200 && res.data) {
        this.setData({
          currentUid: res.data,
        })
      }
    })
  },
  // 首次获取用户信息
  async getRoomInfo(): Promise<void> {
    await GetRoomInfo(this.data.channelId).then(async (res) => {
      if (res.code === 200) {
        this.setData({
          roomInfo: res.data,
        })
      }
    })
  },
  // 加入房间
  async joinChannel(): Promise<void> {
    const item = this.data.roomUserList.find(row => row.uid === this.data.user.uid)
    await onInvoke('joinChannel', {
      roomNum: this.data.channelId,
      enableMicr: this.data.footerList[1].active,
      enableCamera: this.data.footerList[2].active,
      isRoomManager: item ? item.isRoomManager : false,
    })
    agora.joinChannel(item ? item.isRoomManager : false, (url: string) => {
      const roomUserListTemp = [...this.data.roomUserList]
      const itemUser = roomUserListTemp.find(row => row.uid == this.data.user.uid)
      itemUser.src = url
      this.setData({
        roomUserList: roomUserListTemp,
      })
    })
    this.changeAgoraDevice()
  },
  // 用户数据组装
  async setAllUserListData(key: string, item: any, callBack?: Function): Promise<void> {
    const { roomUserList } = this.data;
    const userInfo: any = await getStorage('user')
    switch (key) {
      case 'OperMicr':
      case 'OperCamera':
      case 'ManagerRefresh':
        let userItem = roomUserList.find((row: any) => row.uid === item.user.uid)
        if (userItem) {
          for (const keys in item.user) {
            if (keys !== 'enableCamera' && keys !== 'enableMicr') {
              userItem[keys] = item.user[keys];
            }
          }
          if (key === 'OperCamera') {
            userItem.enableCamera = item.user.enableCamera;
            if (userItem.uid === userInfo.uid) {
              // userItem.enableCamera ? agora.startCameraCapture() : agora.stopCameraCapture()
            }
          }
          if (key === 'OperMicr') {
            userItem.enableMicr = item.user.enableMicr;
          }
          userItem.isAdmin = role.ID.includes(item.user.roleId) || item.user.isRoomManager;
          this.setData({
            roomUserList
          })
        }
        if (key === 'ManagerRefresh') {
          callBack && callBack()
        }
        break;
      case 'UserJoined':
        let userJoinedItem = roomUserList.find((row: any) => row.uid === item.user.uid)
        if (userJoinedItem) {
          for (const key in item.user) {
            userJoinedItem[key] = item.user[key];
          }
          userJoinedItem.isRoom = true;
          userJoinedItem.isAdmin = role.ID.includes(item.user.roleId) || item.user.isRoomManager;
          this.setData({
            roomUserList
          })
        } else {
          item.user.isRoom = true;
          item.user.isAdmin = role.ID.includes(item.user.roleId) || item.user.isRoomManager;
          item.user.avatarName = item.user.userName?.slice(-2)
          this.setData({
            roomUserList: [...roomUserList, item.user]
          })
        }
        break;
      case 'UserLeave':
        let userLeaveItem = roomUserList.find((row: any) => row.uid === item.uid)
        if (userLeaveItem) {
          userLeaveItem.isRoom = false
          userLeaveItem.isAdmin = false
          this.setData({
            roomUserList
          })
        }
        break;
      case 'OperAllMicr':
        roomUserList.forEach((row: any) => {
          if (row.uid !== item.uid) {
            row.enableMicr = item.enableMicr
          }
        })
        this.setData({
          roomUserList
        })
        break;
      case 'ModifyNickName':
        let row = roomUserList.find((row: any) => row.uid == item.uid)
        if (row) {
          row.userName = item.nickName
          row.avatarName = item.nickName?.slice(-2)
        }
        this.setData({
          roomUserList
        })
        break;
    }
    this.changeAgoraDevice()
  },
  // 点击底部按钮
  async changeFooterList(e): Promise<void> {
    const userInfo: any = await getStorage('user')
    const { index } = e.currentTarget.dataset;
    const { footerList } = this.data;
    const footerListTemplate = [...footerList]
    const item = footerListTemplate[index];
    let title = item.active ? item.title : item.titleActive;
    switch (title) {
      case '关闭听筒':
      case '开启听筒':

        break;
      case '解除静音':
      case '静音':
        if (item.active) {
          // 静音
          await this.postOpenMicrApi(false, userInfo.uid, false, true)
        } else {
          // 解除静音
          await this.getUserRoomInfo().then(async (res) => {
            if (res) {
              await this.postOpenMicrApi(true, userInfo.uid, false, true)
            } else {
              if (!this.data.isClicked) {
                this.setData({
                  applySpeakDialog: true,
                  currentRequestSpeakType: 'audio'
                })
              } else {
                this.message('申请太频繁了，请稍后重试！').error();
              }
            }
          })
        }
        break;
      case '关闭视频':
      case '打开视频':
        if (item.active) {
          // 关闭视频
          await this.postOpenCameraApi(false, userInfo.uid, true)
        } else {
          // 打开视频
          await this.getUserRoomInfo().then(async (res) => {
            if (res) {
              await this.postOpenCameraApi(true, userInfo.uid, true)
            } else {
              if (!this.data.isClicked) {
                this.setData({
                  applySpeakDialog: true,
                  currentRequestSpeakType: 'video'
                })
              } else {
                this.message('申请太频繁了，请稍后重试！').error();
              }
            }
          })
        }
        break;
      case '申请发言':
      case '结束发言':
        if (item.active) {
          // 申请发言
          if (!this.data.isClicked) {
            this.setData({
              applySpeakDialog: true,
              currentRequestSpeakType: ''
            })
          } else {
            this.message('申请太频繁了，请稍后重试！').error();
          }
        } else {
          // 结束发言
          DeleteRoomManager({
            roomId: this.data.roomInfo.id,
            roomNum: this.data.channelId,
            userId: userInfo.uid
          })
        }
        break;
      case '翻转':
        await this.getUserRoomInfo().then(async (res) => {
          if (res) {
            wx.createLivePusherContext().switchCamera()
          } else {
            this.message('暂无权限').error();
          }
        })
        break;
      case '聊天':
        this.setData({
          chatPopupVisible: true,
          noViewChatList: 0
        })
        this.scrollToBottom()
        break;
      case '成员':
        this.setData({
          userPopupVisible: true
        })
        break;
    }
  },
  // 开关摄像头
  async postOpenMicrApi(enableMicr: boolean, uid: string, isAll: boolean, isMessage: boolean = false): Promise<void> {
    if (isAll) {
      await PostMuteAll({
        roomNum: this.data.channelId,
        enableMicr
      })
    } else {
      await onInvoke('sendOper2User', {
        uid,
        contentString: JSON.stringify({
          roomNum: this.data.channelId,
          uid,
          enableMicr,
          type: 'audio'
        })
      })
      // await PostOpenMicr({
      //   roomNum: this.data.channelId,
      //   uid,
      //   enableMicr
      // })
    }
    if (isMessage) {
      this.message('操作成功').success()
    }
  },
  // 开关摄像头
  async postOpenCameraApi(enableCamera: boolean, uid: string, isMessage: boolean = false): Promise<void> {
    if (enableCamera) {
      // await agora.startCameraCapture()
    } else {
      // await agora.stopCameraCapture();
    }
    await onInvoke('sendOper2User', {
      uid,
      contentString: JSON.stringify({
        roomNum: this.data.channelId,
        uid,
        enableCamera,
        type: 'video'
      })
    })
    // await PostOpenCamera({
    //   roomNum: this.data.channelId,
    //   uid,
    //   enableCamera
    // })
    if (isMessage) {
      this.message('操作成功').success()
    }
  },
  // 关闭弹窗
  async closeDialog(e) {
    const { type } = e.currentTarget.dataset;
    switch (e.type) {
      case "confirm":
        switch (type) {
          case "applySpeakDialog":
            await GetApplySpeak(this.data.channelId).then(res => {
              if (res.code === 200) {
                this.setData({
                  isClicked: true,
                  [type]: false,
                })
                this.message('申请发言成功').success()
              }
            })
            break;
          case "leaveDialog":
            wx.disableAlertBeforeUnload({
              complete: () => {
                wx.navigateBack()
              }
            })
            break;
        }
        break;
      case "cancel":
        this.setData({
          [type]: false
        })
        break;
    }
  },
  // 音量提示
  playerAudioVolumenotify(e) {
    const { uid } = e.currentTarget.dataset;
    const { volume } = e.detail;
    const audioListTemp = [...this.data.audioList]
    const percentage = (volume / 100) * 100
    const item = audioListTemp.find(row => row.uid == uid)
    if (item) {
      item.volume = Math.floor(percentage) + '%'
      item.volumeNumber = Math.floor(percentage)
    }
    this.setData({
      audioList: audioListTemp,
      userVolume: audioListTemp.find(row => row.uid == this.data.user.uid).volume
    })
  },
  // 切换视频
  clickChangeVideo(e) {
    const { item } = e.currentTarget.dataset;
    const isShare = this.data.roomUserList.find(item => item.shareSrc)
    if (isShare) {
      this.message(`正在进行屏幕共享，不允许切换画面。`).error()
    } else {
      this.setData({
        currentUid: item.uid
      })
    }
  },
  // 悬浮提示
  message(content: string) {
    return {
      success: () => {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 2000,
          content,
        });
      },
      error: () => {
        Message.error({
          context: this,
          offset: [20, 32],
          duration: 2000,
          content,
        });
      }
    }
  },
  // 获取当前用户在房间信息
  async getUserRoomInfo(): Promise<any> {
    const userInfo: any = await getStorage('user')
    return new Promise((resolve, _reject) => {
      let userItem = this.data.roomUserList.find((item: any) => item.uid === userInfo.uid)
      if (userItem && (role.ID.includes(userItem.roleId) || userItem.isRoomManager)) {
        resolve(userItem)
      } else {
        resolve('')
      }
    })
  },
  // 更改数据
  async changeAgoraDevice(): Promise<any> {
    const userInfo: any = await getStorage('user')
    this.data.roomUserList.forEach(async (item: any) => {
      if (item.uid == userInfo.uid) {
        const footerListTemplate = [...this.data.footerList]
        footerListTemplate[1].active = item.enableMicr
        footerListTemplate[2].active = item.enableCamera
        item.enableMicr ? await agora.unmuteLocal('audio') : await agora.muteLocal('audio')
        let userId = this.data.watchUids.find((uid: any) => uid === userInfo.uid)
        if (!userId) {
          item.enableCamera ? await agora.unmuteLocal('video') : await agora.muteLocal('video')
        }
        if (!role.ID.includes(userInfo.roleId)) {
          footerListTemplate[6].active = !item.isRoomManager;
        }
        this.setData({
          footerList: footerListTemplate
        })
      }
    });
  },
  // 退出提示
  async back() {
    this.setData({
      leaveDialog: true
    })
  },
  // 关闭聊天和成员
  onVisibleChange() {
    this.setData({
      userPopupVisible: false,
      chatPopupVisible: false,
    })
  },
  // 聊天内容输入框赋值
  changeMessageStr(e) {
    this.setData({
      messageStr: e.detail.value
    })
  },
  // 聊天内容输入框赋值
  changeInputStr(e) {
    this.setData({
      inputStr: e.detail.value
    })
  },
  // 聊天发送
  async sendMeg(e) {
    if (this.data.messageStr || e.target.dataset.item) {
      await onInvoke('sendChannelMsg', {
        roomNum: this.data.channelId,
        msg: e.target.dataset.item || this.data.messageStr
      })
      const item = this.data.roomUserList.find(row => row.uid === this.data.user.uid)
      this.setData({
        chatList: [...this.data.chatList, {
          userName: item.userName,
          message: e.target.dataset.item || this.data.messageStr,
          timestamp: dayjs(+new Date()).format('HH:mm:ss'),
          me: true
        }],
      })
      if (!e.target.dataset.item) {
        this.setData({
          messageStr: ''
        })
      }
      this.scrollToBottom()
    } else {
      this.message('请输入文字！').error()
    }
  },
  // 全屏切换
  changeFullscreen() {
    this.setData({
      isFullscreen: !this.data.isFullscreen
    })
  },
  // 聊天框位置滚动
  scrollToBottom() {
    wx.createSelectorQuery()
      .select('#chatView')
      .node()
      .exec((res) => {
        const scrollView = res[0].node;
        scrollView.scrollTo({
          top: 10000000000000
        })
      })
  },
  // 断网退出房间
  setIsConnectedBack() {
    wx.setStorage({
      key: "isConnected",
      data: true
    })
    wx.disableAlertBeforeUnload({
      complete: () => {
        wx.navigateBack()
      }
    })
  },
  // 监听网络变化
  async listener(res) {
    if (res.isConnected && (res.networkType !== 'none' || res.networkType !== 'unknown')) {

    } else {

    }
  },
  // 重连失败退出房间
  closeRoom() {
    wx.disableAlertBeforeUnload({
      complete: () => {
        this.setData({
          isReconnec: false
        })
        wx.navigateBack()
      }
    })
  },
  // 上箭头滚动
  scrollUp() {
    const query = wx.createSelectorQuery()
    query.select('#meeting-content-smallvideo').scrollOffset((res => {
      this.setData({
        scrollTop: res.scrollTop - 50
      })
    }))
    query.exec()
  },
  // 下箭头滚动
  scrollDown() {
    const query = wx.createSelectorQuery()
    query.select('#meeting-content-smallvideo').scrollOffset((res => {
      this.setData({
        scrollTop: res.scrollTop + 50
      })
    }))
    query.exec()
  },
})