<template>
  <view class="call-view">
    <view class="nav-bar">
      <text class="duration">{{duration}}</text>
    </view>

    <view class="user-list">
      <view v-for="(member,index) in members" :key="index">
        <view v-if="member.status !== 'Quit'" class="user-item">
          <!-- #ifdef APP -->
          <grtc-video v-if="currentCall.mediaType === 1 && member.status === 'InCall' && !member.cameraMuted" :userId="member.id" class="callee-view"></grtc-video>
          <image v-else class="user-item-avatar" mode="widthFix" :src="member.data.avatar"></image>
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <web-grtc-video v-if="currentCall.mediaType === 1 && member.status === 'InCall' && !member.cameraMuted" :userId="member.id" class="callee-view"></web-grtc-video>
          <image v-else class="user-item-avatar" mode="widthFix" :src="member.data.avatar"></image>
          <!-- #endif -->
          <view v-if="member.micMuted" class="user-muted">
            <image class="user-muted-icon" mode="widthFix" src="/static/images/microphone-red.png" />
          </view>
        </view>
      </view>
    </view>

    <view class="action-box">
      <view class="action-top">
        <view class="action-item" @click="toggleMic()">
          <view v-if="self.micMuted">
            <view class="item-background-disable">
              <image class="action-bar-icon" src="/static/images/microphone-disable.png"></image>
            </view>
            <text class="action-text">麦克风已关</text>
          </view>
          <view v-else>
            <view class="item-background">
              <image class="action-bar-icon" src="/static/images/microphone.png"></image>
            </view>
            <text class="action-text">麦克风已开</text>
          </view>
        </view>
        <view class="action-item" @click="toggleSpeaker()">
          <view v-if="currentCall.speakerOn">
            <view class="item-background">
              <image class="action-bar-icon" src="/static/images/speaker.png"></image>
            </view>
            <text class="action-text">扬声器已开</text>
          </view>
          <view v-else>
            <view class="item-background-disable">
              <image class="action-bar-icon" src="/static/images/speaker-disable.png"></image>
            </view>
            <text class="action-text">扬声器已关</text>
          </view>
        </view>
        <view class="action-item" @click="toggleCamera()" v-if="currentCall.mediaType === 1">
          <view v-if="self.cameraMuted">
            <view class="item-background-disable">
              <image class="action-bar-icon" src="/static/images/camera-disable.png"></image>
            </view>
            <text class="action-text">摄像头已关</text>
          </view>
          <view v-else>
            <view class="item-background">
              <image class="action-bar-icon" src="/static/images/camera.png"></image>
            </view>
            <text class="action-text">摄像头已开</text>
          </view>
        </view>
      </view>
      <view class="action-item" @click="end()">
        <view class="end-background">
          <image class="action-icon" src="/static/images/phoneEnd.png"></image>
        </view>
      </view>
      <view class="switch-camera" @click="switchCamera()" v-if="currentCall.mediaType === 1">
        <image class="switch-camera-icon" src="/static/images/switch-camera.png"></image>
      </view>
    </view>
  </view>
</template>

<script>
  import webGrtcVideo from '../components/web-grtc-video/web-grtc-video.vue';
  const GRTC = uni.$GRTC;
  let interval = null;
  export default {
    data() {
      return {
        currentCall: GRTC.currentCall(),
        self: null,
        duration: null
      }
    },
    components: {
      webGrtcVideo,
    },
    computed: {
      members() {
        const { callees, caller } = this.currentCall;
        const allMembers = [...callees, caller];
        const sortedMembers = allMembers.sort((a, b) => {
          if (a.id === uni.$currentUser.id) return 1;
          if (b.id === uni.$currentUser.id) return -1;
          return 0;
        });
        return sortedMembers;
      },
    },
    onLoad() {
      this.self = this.getSelf();
      interval = setInterval(() => {
        this.duration = this.formattedDuration();
      }, 1000);
      this.initListener();
    },
    onUnload() {
      GRTC.off(GRTC.EVENT.USER_RANG, this.onUserRang);
      GRTC.off(GRTC.EVENT.USER_ACCEPTED, this.onUserAccepted);
      GRTC.off(GRTC.EVENT.USER_QUIT, this.onUserQuit);
      GRTC.off(GRTC.EVENT.CALL_ENDED, this.onCallEnded);
      GRTC.off(GRTC.EVENT.USER_MIC_CHANGED, this.onUserMicChanged);
      GRTC.off(GRTC.EVENT.USER_CAMERA_CHANGED, this.onUserCameraChanged);
    },
    onBackPress(event) {
      return event.from === 'backbutton';  // 禁止安卓侧滑返回
    },
    methods: {
      getSelf() {
        if (uni.$currentUser.id === this.currentCall.caller.id) {
          return this.currentCall.caller
        } else {
          const index = this.currentCall.callees.findIndex(member => member.id === uni.$currentUser.id);
          return this.currentCall.callees[index]
        }
      },
      initListener() {
        GRTC.on(GRTC.EVENT.USER_RANG, this.onUserRang);
        GRTC.on(GRTC.EVENT.USER_ACCEPTED, this.onUserAccepted);
        GRTC.on(GRTC.EVENT.USER_QUIT, this.onUserQuit);
        GRTC.on(GRTC.EVENT.CALL_ENDED, this.onCallEnded);
        GRTC.on(GRTC.EVENT.USER_MIC_CHANGED, this.onUserMicChanged);
        GRTC.on(GRTC.EVENT.USER_CAMERA_CHANGED, this.onUserCameraChanged);
      },
      onUserRang(event) {
        uni.showToast({
        	title: event.user.data.name+"已响铃",
        	icon: "none"
        });
      },
      onUserAccepted(event) {
        uni.showToast({
        	title: event.user.data.name+"已接听",
        	icon: "none"
        });
      },
      onUserQuit(event) {
        const username = event.user.id === uni.$currentUser.id ? '' : event.user.data.name;
        let message = '';
        switch (event.reason) {
          case 'GOEASY_DISCONNECTED':
            message = `${username}网络异常`;
            break;
          case 'HUNG_UP':
            message = `${username}已挂断`;
            break;
          case 'REJECTED':
            message = `${username}已拒绝`;
            break;
        }
        uni.showToast({title: message,icon: "none"});
      },
      onCallEnded() {
        clearInterval(interval);
        uni.navigateBack();
      },
      onUserMicChanged(event) {
        console.log("onUserMicChange",event);
      },
      onUserCameraChanged(event) {
        console.log("onUserCameraChanged",event);
      },
      switchCamera() {
        GRTC.switchCamera();
      },
      toggleSpeaker() {
        GRTC.toggleSpeaker(!this.currentCall.speakerOn);
      },
      toggleMic() {
        GRTC.muteMic(!this.self.micMuted);
      },
      toggleCamera() {
        GRTC.muteCamera(!this.self.cameraMuted);
      },
      end() {
        clearInterval(interval);
        GRTC.end();
      },
      formattedDuration() {
        const seconds = this.currentCall.getDuration();
        const minutes = Math.floor(seconds / 60);
        const formattedSeconds = String(seconds % 60).padStart(2, '0');
        const formattedMinutes = String(minutes).padStart(2, '0');
        return `${formattedMinutes}:${formattedSeconds}`; // mm:ss
      }
    }
  }
</script>

<style scoped>
  @import url('/static/style/rtcCallStyle.css');
</style>