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 {
      lookList: [] as any[], // 观看学生列表
      loadingLook: false, // 观看列表状态
    }
  },
  mounted() {
    // this._init()
    this.loadingLook = true
    event.on(LIVE_EVENT_MESSAGE["RC:Chatroom:Welcome"], this.onWelcome);
    event.on(LIVE_EVENT_MESSAGE["RC:Chatroom:SeatResponse"], this.onSeatResponse);
    event.on(LIVE_EVENT_MESSAGE['RM:RTC:UserLeave'], this.onSeatApply);
    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,
          }
        })
        console.log('_init', res)
      } catch {
        //
      }
    },
    onSeatResponse(value: any) {
      if(value.type == 3) {
        runtimeModel.lookList.forEach((item: any) => {
          if(item.id == value.audienceId) {
            item.type = 1
          }
        })
        // 判断是否是同一个人
        let isExist = runtimeModel.joinList[value.audienceId]
        console.log(runtimeModel.joinList)
        if (!isExist) {
          RuntimeModelUtils.addJoin(value.audienceId, {
            id: value.audienceId,
            name: value.audienceName,
            audienceId: value.audienceId,
            audienceName: value.audienceName,
            teacherId: state.user?.id,
            teacherName: state.user?.speakerName,
            type: 1
          })
        } else {
          runtimeModel.joinList[value.audienceId].type = 1
        }
      }
    },
    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
        }
        // 判断是否有同一个人
        let isExist = false;
        runtimeModel.lookList.forEach((item: any) => {
          if (item.id === tempObj.id) {
            isExist = true
          }
        })
        if (!isExist) {
          RuntimeModelUtils.addLook(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将麦上观众踢下麦
        const data = {
          audienceName: item.name,
          audienceId: item.id,
          teacherId: state.user?.id,
          teacherName: state.user?.speakerName,
          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 {
      }
    },
    onSeatApply(evt: any) {
      if (Array.isArray(evt)) {
        for (const id of evt) {
          RuntimeModelUtils.removeJoin(id)
        }
        return
      }
      // 取消连麦
      console.log(evt)
      if (evt.type === 4) {
        if (runtimeModel.joinList[evt.audienceId]) {
          RuntimeModelUtils.removeJoin(evt.audienceId)

          runtimeModel.lookList.forEach((item: any) => {
            if(item.id == evt.audienceId) {
              item.type = 3
            }
          })
        }
      }
    },
  },
  render() {
    return (
      <div>
        {runtimeModel.lookList.length > 0 ? runtimeModel.lookList.map((item : any) => (
          <div class={styles.itemContent}>
            {/* <img src="/src/assets/home/placehorder-icon.png" alt="" /> */}
            <div class={styles.itemInfo} >
              <div class={styles.itemName}>
                <p class={styles.userName}>{item.name}</p>
                {item.type == 1 ? <ElButton size="small" type="primary" class={styles.btn} onClick={() => this.onUpLook(item)}>上麦</ElButton> : <ElButton size="small" plain class={[styles.btn, styles.downBtn]} onClick={() => this.onDownLook(item)}>下麦</ElButton>}
                {/* {item.type == 1 ? <a href="javascript:;" class={[styles.btn, styles.downBtn]} onClick={() => this.onDownLook(item)}>下麦</a> : <a href="javascript:;" class={styles.btn} onClick={() => this.onUpLook(item)}>上麦</a>} */}
              </div>
            </div>
          </div>
        )) : this.loadingLook ? <div class={styles.loadingStyle} v-loading={this.loadingLook} element-loading-background="rgba(0, 0, 0, 0.8)"></div> : <Empty style={{ paddingTop: '120px' }} text="暂无学员观看！" icon="noData-no-user" />}
      </div>
    )
  }
})
