import { defineComponent } from "vue";
import { ElButton } from 'element-plus'
import runtime, * as RuntimeUtils from '/src/components/live-broadcast/runtime'
import styles from './index.module.less'
import event, { LIVE_EVENT_MESSAGE } from '/src/components/live-broadcast/event';
import { state } from '/src/state'
import dayjs from 'dayjs';
import Empty from "/src/components/empty";
import runtimeModel, * as RuntimeModelUtils from '/src/components/live-message/model/runtime'
import request from "/src/helpers/request";

export default defineComponent({
  data() {
    return {
      loadingLook: false, // 观看列表状态
    }
  },
  computed: {
    count() {
      let count = 0
      for (const key in runtimeModel.joinList) {
        if (Object.prototype.hasOwnProperty.call(runtimeModel.joinList, key)) {
          const item = runtimeModel.joinList[key];
          if (item.type === 3) {
            count += 1
          }
          if (count > 3) {
            break
          }
        }
      }
      return count
    },
  },
  async mounted() {
    await this._init()
    this.loadingLook = true
    event.on(LIVE_EVENT_MESSAGE["RC:Chatroom:Welcome"], this.onWelcome);
    setTimeout(() => {
      this.loadingLook = false;
    })
  },
  methods: {
    async _init() {
      try {
        const roomUid = sessionStorage.getItem('roomUid')
        const res = await request.get(`/api-web/imLiveBroadcastRoom/queryRoomUserInfo`, {
          params: {
            roomUid: roomUid,
          }
        })
        const resList = res.data
        resList.forEach((item: any) => {
          // 判断是已经，存在学生
          if(!runtimeModel.lookList[item.userId]) {
            runtimeModel.lookList[item.userId] = {
              id: item.userId,
              name: item.userName,
              type: 3,
              userRoomType: 1,
              time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            }
          }
        })
      } catch {
        //
      }
    },
    onWelcome(value: any) {
      // console.log(value)
      if (value && value.user) {
        const sendTime = dayjs(value.$EventMessage.sentTime || new Date()).format('HH:mm:ss')
        let tempObj = {
          name: value.user.name,
          id: value.user.id,
          sendTime,
          userRoomType: 1,
          type: 3
        }
        // 判断是否有同一个人
        let isExist = runtimeModel.lookList[tempObj.id] ? true : false;
        if (!isExist) {
          RuntimeModelUtils.addLook(tempObj.id, tempObj);
        }

        this.loadingLook = false
      }
    },
    async onUpLook(item: any) {
      try {
        // RC:Chatroom:SeatResponse type teacherName teacherId audienceName audienceId
        // 操作类型 1 主讲人同意 2 主讲人拒绝 3 观众同意 4 观众拒绝
        // RC:Chatroom:SeatApply type teacherName teacherId audienceName audienceId
        // 操作类型 1 主讲人邀请 2 主讲人取消邀请 3 观众申请 4 观众取消申请 5将麦上观众踢下麦

        // userRoomType
        // 1 普通
        // 2 老师邀请
        // 3 学生申请
        // 4 连麦中
        const data = {
          audienceName: item.name,
          audienceId: item.id,
          teacherId: state.user?.id,
          teacherName: state.user?.speakerName,
          userRoomType: 2,
          type: 1
        }
        await RuntimeUtils.sendMessage(data, 'SeatApply')
      } catch {
        //
      }
    },
    async onDownLook(item: any) {
      try {
        const data = {
          ...item,
          audienceName: item.name,
          audienceId: item.id,
          teacherId: state.user?.id,
          teacherName: state.user?.speakerName,
          type: 5,
        }
        RuntimeModelUtils.addJoin(item.id, data)
        RuntimeUtils.sendMessage(data, 'SeatApply')
      } catch {
      }
    },
  },
  render() {
    const list = Object.values(runtimeModel.lookList)
    return (
      <div>
        {list.length > 0 ? list.map((item : any) => (
          <div class={styles.itemContent}>
            <div class={styles.itemInfo} >
              <div class={styles.itemName}>
                <p class={styles.userName}>
                  <span class={styles['name-style']}>{item.name}</span>
                </p>
                {item.userRoomType !== 4 ? <ElButton size="small" type="primary" disabled={this.count > 3} class={styles.btn} onClick={() => this.onUpLook(item)}>上麦</ElButton> : <ElButton size="small" plain class={[styles.btn, styles.downBtn]} onClick={() => this.onDownLook(item)}>下麦</ElButton>}
              </div>
            </div>
          </div>
        )) : this.loadingLook ? <div class={styles.loadingStyle} ><div class="el-loading-mask" style="background-color: rgba(0, 0, 0, 0.8);"><div class="el-loading-spinner"><svg class="circular" viewBox="25 25 50 50"><circle class="path" cx="50" cy="50" r="20" fill="none"></circle></svg></div></div></div> : <Empty style={{ paddingTop: '120px' }} text="暂无学员观看！" icon="noData-no-user" />}
      </div>
    )
  }
})
