import { defineComponent } from "vue";
import { ElDropdownMenu, ElDropdown, ElDropdownItem, ElMessage } from "element-plus";
import router from "/src/router";
import styles from './index.module.less';
import request from '/src/helpers/request';
import runtime, * as RuntimeUtils from "/src/components/live-broadcast/runtime";
import { removeToken } from "/src/utils/auth";
import { removeMedia } from '/src/components/live-broadcast/helpers'
import { state } from '/src/state'
import userLogo from '/src/assets/home/placehorder-icon.png'

export default defineComponent({
  methods: {
    async loginOut() {
      try {
        await RuntimeUtils.leaveIMRoom()
        try {
          await request.post('/api-auth/exit', { data: {} });
        } catch {}
        RuntimeUtils.closeDevice('camera')
        RuntimeUtils.closeDevice('microphone')
        state.user = null
        runtime.syncLikeTimer && clearTimeout(runtime.syncLikeTimer)
        ElMessage.success('退出成功');
        removeToken();
        (this as any).$router.push({
          path: '/login',
          query: {
            ...this.$route.query
          }
        });
      } catch(e) {
        // TODO: handle error
      }
    }
  },
  render() {
    return (
      <div class={styles.liveHeader}>
        <div class={styles.liveHeaderLeft}>
          <div class={styles.liveHeaderLeftIcon}>
            <img class={styles.liveLogo} src={state.user?.tenantLogo} alt=""/>
            {state.user?.tenantName}
          </div>
          <div class={styles.liveHeaderLeftText}>
            《{state.user?.roomTitle}》
          </div>
        </div>
        <ElDropdown trigger={'hover'}
          // @ts-ignore
          vSlots={{
            dropdown: () => (
              <ElDropdownMenu>
                <ElDropdownItem command="1" onClick={this.loginOut}>
                  <span>安全退出</span>
                </ElDropdownItem>
              </ElDropdownMenu>
            )
          }}>
          <div class={styles.avatarWrapper}>
            {state.user?.speakerPic ? <img class={styles.userAvatar} src={state.user?.speakerPic} /> : <img class={styles.userAvatar} src={userLogo} />}
            <span>{ state.user?.speakerName }</span>
          </div>
        </ElDropdown>
      </div>
    )
  }
})
