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, // 观看列表状态
      upStatus: false,
      downStatus: false
    }
  },
  computed: {
    count() {
      let count = 0
      for (const key in runtimeModel.lookList) {
        if (Object.prototype.hasOwnProperty.call(runtimeModel.lookList, key)) {
          const item = runtimeModel.lookList[key];
          if (item.userRoomType === 2 || item.userRoomType === 4) {
            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);
    event.on(LIVE_EVENT_MESSAGE["RC:Chatroom:MemberCountUp"], this.onMemberCount);
    setTimeout(() => {
      this.loadingLook = false;
    })
  },
  beforeUnmount() {
    event.off(LIVE_EVENT_MESSAGE["RC:Chatroom:Welcome"], this.onWelcome);
    event.off(LIVE_EVENT_MESSAGE["RC:Chatroom:MemberCountUp"], this.onMemberCount);
  },
  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 {
        //
      }
    },
    /**
     * 当后端发送人数消息时，更新人数
     */
    onMemberCount(evt: any) {
      runtime.lookCount = evt.content.count || 0
      RuntimeUtils.sendMessage({ count: runtime.lookCount }, 'MemberCount')
    },
    async 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);
          console.log('添加观看人员', tempObj)
          // runtime.lookCount += 1;
        }

        // 同步移动端观看人数
        // await RuntimeUtils.sendMessage({ count: runtime.lookCount }, 'MemberCount')

        this.loadingLook = false
      }
    },
    async onUpLook(item: any) {
      try {
        console.log(this.count, runtimeModel.lookList, 'this.count, runtimeModel.lookList')
        if(this.count > 3) {
          return
        }
        // 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: String(item.id),
          teacherId: String(state.user?.id),
          teacherName: state.user?.speakerName,
          userRoomType: 2,
          type: 1
        }
        item.userRoomType = 2;
        await RuntimeUtils.sendMessage(data, 'SeatApply')
      } catch {
        //
      }
    },
    async onDownLook(item: any) {
      try {
        const data = {
          ...item,
          audienceName: item.name,
          audienceId: String(item.id),
          teacherId: String(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>
                {/* 1、最多三个人上麦；2、老师主动邀请；3、没有开始直播 */}
                {item.userRoomType !== 4 ? <ElButton size="small" type="primary" disabled={this.count > 3 || item.userRoomType === 2 || runtime.videoStatus !== 'liveing'} 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>
    )
  }
})
