import { defineComponent } from "vue";
import styles from "./index.module.less";
import { ElButton } from "element-plus";
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 runtime, * as RuntimeUtils from "/src/components/live-broadcast/runtime";
import runtimeModel, * as RuntimeModelUtils from "/src/components/live-message/model/runtime";
import request from "/src/helpers/request";

export default defineComponent({
  data() {
    return {
      joinList: {} as { [key: string]: any }, // 连麦学生列表
      loadingJoin: false, // 连麦列表状态
      upStatus: false,
      downStatus: false,
      refreshStatus: 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.userRoomType === 4) {
            count += 1;
          }
          if (count > 3) {
            break;
          }
        }
      }
      return count;
    },
  },
  mounted() {
    // userRoomType
    // 1 普通
    // 2 老师邀请
    // 3 学生申请
    // 4 连麦中
    event.on(LIVE_EVENT_MESSAGE["RC:Chatroom:SeatApply"], this.onSeatApply);
    event.on(LIVE_EVENT_MESSAGE["RC:Chatroom:SeatResponse"], this.onSeatApply);
    event.on(LIVE_EVENT_MESSAGE["RM:RTC:UserLeave"], this.onSeatApply);
    event.on(LIVE_EVENT_MESSAGE["RC:Chatroom:downSeat"], this.onDownSeat);
    event.on(LIVE_EVENT_MESSAGE["RM:RTC:SwitchRole"], this.onSwitchRole);
    // event.on(LIVE_EVENT_MESSAGE["RC:Chatroom:Leave"], this.onLeave); // 移动端接收的消息
    event.on(LIVE_EVENT_MESSAGE["RC:LookerLoginOut"], this.onLeave); // 后台接收的消息
  },
  unmounted() {
    event.off(LIVE_EVENT_MESSAGE["RC:Chatroom:SeatApply"], this.onSeatApply);
    event.off(LIVE_EVENT_MESSAGE["RC:Chatroom:SeatResponse"], this.onSeatApply);
    event.off(LIVE_EVENT_MESSAGE["RM:RTC:UserLeave"], this.onSeatApply);
    event.off(LIVE_EVENT_MESSAGE["RM:RTC:SwitchRole"], this.onSwitchRole);
    // event.off(LIVE_EVENT_MESSAGE["RC:Chatroom:Leave"], this.onLeave); // 移动端接收的消息
    event.off(LIVE_EVENT_MESSAGE["RC:LookerLoginOut"], this.onLeave); // 后台接收的消息
  },
  methods: {
    async onLeave(value: any) {
      // 学生离开时处理
      const userId = value.userId || value.fromUserId;
      if (runtimeModel.joinList[userId]) {
        RuntimeModelUtils.removeJoin(userId);
      }
      if (runtimeModel.lookList[userId]) {
        RuntimeModelUtils.removeLook(userId);

        // 判断是否有学生
        // runtime.lookCount =
        //   runtime.lookCount - 1 >= 0 ? runtime.lookCount - 1 : 0;
      }
      // 同步移动端观看人数
      await RuntimeUtils.sendMessage(
        { count: runtime.lookCount },
        "MemberCount"
      );

      // this.onRefresh();
    },
    onSeatApply(evt: any) {
      // console.log(evt, 'onSeatApply joinModel')
      if (Array.isArray(evt)) {
        for (const id of evt) {
          console.log("onSeatApply", id);
          RuntimeModelUtils.removeJoin(id);
        }
        return;
      }
      const response =
        evt.$EventMessage.messageType === "RC:Chatroom:SeatResponse";
      const userRoomType = response ? 4 : 3;
      // if(evt.$EventMessage.messageType === 'RC:Chatroom:SeatResponse')
      const sendTime = dayjs(evt.$EventMessage.sentTime || new Date()).format(
        "HH:mm:ss"
      );
      let tempObj = {
        name: evt.audienceName,
        id: String(evt.audienceId),
        system: 1,
        isSelf: false,
        content: "",
        sendTime,
      };
      // 申请连麦
      if (evt.type === 3) {
        console.log(evt, "申请连麦");
        const params = {
          name: evt.audienceName,
          id: evt.audienceId,
          userRoomType: userRoomType,
          type: evt.type,
        };
        RuntimeModelUtils.addJoin(evt.audienceId, params);
        RuntimeModelUtils.addLook(evt.audienceId, params);

        tempObj.content = response ? "同意了连麦申请" : "发起了连麦申请";
        RuntimeModelUtils.addMessage(tempObj);
        event.emit("MESSAGE:Change");
      }
      // 取消连麦
      if (evt.type === 4) {
        console.log(evt, "取消连麦");
        if (runtimeModel.joinList[evt.audienceId]) {
          RuntimeModelUtils.removeJoin(evt.audienceId);
        }
        if (runtimeModel.lookList[evt.audienceId]) {
          let userLook = runtimeModel.lookList[evt.audienceId];
          userLook.userRoomType = 1;
          RuntimeModelUtils.addLook(evt.audienceId, userLook);
        }

        //
        tempObj.content = response ? "拒绝了连麦申请" : "取消了连麦申请";
        RuntimeModelUtils.addMessage(tempObj);
        event.emit("MESSAGE:Change");

        setTimeout(() => {
          this.onRefresh();
        }, 500);
      }
    },
    agree(item: any) {
      if (this.count > 3 || this.upStatus) {
        console.log(true, 2323);
        return;
      }
      this.upStatus = true;
      const data = {
        ...item,
        audienceName: item.name,
        audienceId: String(item.id),
        teacherId: String(state.user?.id),
        teacherName: state.user?.speakerName,
        userRoomType: 4,
        type: 1,
      };
      RuntimeModelUtils.addJoin(item.id, data);
      RuntimeModelUtils.addLook(item.id, data);
      RuntimeUtils.sendMessage(data, "SeatResponse");
      setTimeout(() => {
        this.upStatus = false;
      }, 300);
    },
    refuse(item: any) {
      if (this.downStatus) {
        return;
      }
      this.downStatus = true;
      const data = {
        ...item,
        audienceName: item.name,
        audienceId: String(item.id),
        teacherId: String(state.user?.id),
        teacherName: state.user?.speakerName,
        userRoomType: 4,
        type: 5,
      };
      RuntimeModelUtils.addJoin(item.id, data);
      RuntimeUtils.sendMessage(data, "SeatApply");
      setTimeout(() => {
        this.downStatus = false;
      }, 50000);
    },
    onDownSeat(evt: any) {
      this.downStatus = false;
      console.log(evt, "onDownSeat");
      if (runtimeModel.joinList[evt.audienceId]) {
        const users = runtimeModel.joinList[evt.audienceId];
        const sendTime = dayjs(new Date()).format("HH:mm:ss");
        console.log(
          evt.$EventMessage.senderUserId,
          state.user?.speakerId,
          "onDownSeat"
        );
        let message = users.type == 5 ? "被抱下麦" : "取消了连麦申请";
        let tempObj = {
          name: evt.audienceName,
          id: evt.audienceId,
          system: 1,
          isSelf: false,
          content: message,
          sendTime,
        };
        RuntimeModelUtils.addMessage(tempObj);
        event.emit("MESSAGE:Change");

        RuntimeModelUtils.removeJoin(evt.audienceId);
      }
    },
    onSwitchRole(evt: any) {
      console.log(evt, "onSwitchRole");
      if (runtimeModel.lookList[evt.userId] && evt.role === 2) {
        let userLook = runtimeModel.lookList[evt.userId];
        userLook.userRoomType = 1;
        RuntimeModelUtils.addLook(evt.userId, userLook);
      }
    },
    async onRefresh() {
      // 刷新连麦列表
      console.log(runtime.joinedRoom?.getRemoteUserIds(), "remoteUserIds");
      this.refreshStatus = true;
      const userIds: string[] | undefined =
        runtime.joinedRoom?.getRemoteUserIds();
      const noJoinUserIds = userIds?.filter((item: string) => {
        return !runtimeModel.joinList[item];
      });
      const noLookList = noJoinUserIds?.filter((item: string) => {
        return !runtimeModel.lookList[item];
      });
      const inLookList = noJoinUserIds?.filter((item: string) => {
        return runtimeModel.lookList[item];
      });
      const joinUserList = inLookList?.map((item: any) => {
        const user = runtimeModel.lookList[item];
        user.userRoomType = 4;
        return user;
      });
      console.log(joinUserList);
      if (noLookList && noLookList?.length > 0) {
        const fetchList = await this.FetchUserDetails(noLookList);
        console.log(fetchList, "fetchList");
        fetchList.forEach((item: any) => {
          joinUserList?.push({
            name: item.userName,
            id: item.userId,
            sendTime: dayjs(new Date()).format("HH:mm:ss"),
            userRoomType: 4,
            type: 1,
          });
        });
      }
      // 判断是否在连麦列表中
      if (joinUserList && joinUserList?.length > 0) {
        joinUserList?.forEach((item: any) => {
          RuntimeModelUtils.addJoin(item.id, item);
        });
      }
      setTimeout(() => {
        this.refreshStatus = false;
      }, 300);
    },
    async FetchUserDetails(userIds: string[]) {
      try {
        const res = await request.post(
          "/api-web/imLiveBroadcastRoom/queryBaseUserInfo",
          {
            requestType: "json",
            data: userIds,
          }
        );
        return res.data;
      } catch (error) {}
      return [];
    },
  },
  render() {
    const list = Object.values(runtimeModel.joinList);
    return (
      <div style={{ minHeight: "100%", position: "relative" }}>
        {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>
                    {item.userRoomType !== 4 ? (
                      <span style={{ paddingLeft: "10px" }}>申请连麦</span>
                    ) : (
                      <span
                        style={{
                          paddingLeft: "10px",
                          color: "var(--live-text-color)",
                        }}
                      >
                        正在连麦
                      </span>
                    )}
                  </p>
                  {item.userRoomType !== 4 ? (
                    <div class={styles.joinText}>
                      <div class={styles.join}>{/* 申请连麦 */}</div>
                      <ElButton
                        size="small"
                        type="primary"
                        disabled={this.count > 3}
                        class={styles.btn}
                        onClick={() => this.agree(item)}
                      >
                        上麦
                      </ElButton>
                    </div>
                  ) : (
                    <div class={styles.joinText}>
                      <div class={styles.join}>{/* 正在连麦 */}</div>
                      <ElButton
                        loading={this.downStatus}
                        size="small"
                        plain
                        class={[styles.btn, styles.downBtn]}
                        onClick={() => this.refuse(item)}
                      >
                        下麦
                      </ElButton>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))
        ) : this.loadingJoin ? (
          <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-join"
          />
        )}
        {/* <div
          class={[
            styles.refresh,
            styles["refresh-animation"],
            this.refreshStatus ? styles.refreshStart : styles.refreshStop,
          ]}
          onClick={this.onRefresh}
        >
          <SvgIcon
            name="message-refresh"
            color={"#01A79E"}
            style={{ width: "20px", height: "20px" }}
          />
        </div> */}
      </div>
    );
  },
});
