<template>
  <div class="participant-list-container" ref="rootContainer">
    <div v-if="true" @click="invite" class="action-item">
      <div class="icon">+</div>
      <p>邀请新参与者</p>
    </div>
    <div v-if="false" @click="invite" class="action-item">
      <div class="icon">-</div>
      <p>移除参与者</p>
    </div>
    <ul>
      <li v-for="participant in participants" :key="participant.uid + participant._isScreenSharing">
        <tippy
          v-if="!participant._isScreenSharing"
          :to="'user-' + participant.uid"
          interactive
          theme="light"
          :animate-fill="false"
          placement="left"
          distant="7"
          animation="fade"
          trigger="manual"
        >
          <UserCardView :user-info="participant" />
        </tippy>
        <div
          class="participant-user"
          @contextmenu.stop.prevent="showContextMenu($event, participant)"
          :ref="'userCardTippy-' + participant.uid"
          v-bind:class="{
            active:
              participant.uid === currentParticipant.uid && participant._isScreenSharing === currentParticipant._isScreenSharing,
          }"
          :name="'user-' + participant.uid"
        >
          <div class="avatar-container">
            <img class="avatar" :src="participant.portrait" alt="" />
            <div v-if="selfUserId === session.host && !participant._isHost" @click.stop="kickoff(participant)" class="icon">
              -
            </div>
          </div>
          <div class="name-desc">
            <p class="single-line name">{{ participantName(participant) }}</p>
            <p class="single-line desc">{{ participantDesc(participant) }}</p>
          </div>
          <div class="audio-video">
            <i
              v-if="participant._isAudience || participant._isAudioMuted"
              class="icon-ion-ios-mic-outline"
              style="color: gray"
            ></i>
            <i v-else class="icon-ion-ios-mic"></i>
            <i
              v-if="participant._isAudience || participant._isVideoMuted"
              class="icon-ion-ios-videocam-outline"
              style="color: gray"
            ></i>
            <i v-else class="icon-ion-ios-videocam"></i>
          </div>
        </div>
      </li>
    </ul>

    <vue-context ref="menu" v-slot="{ data: participant }" :close-on-scroll="true" lazy>
      <li v-for="(item, i) in buildParticipantContextMenu(participant)" :key="i">
        <a @click.prevent="item.handler" v-bind:style="item.styleObject">{{ item.title }}</a>
      </li>
    </vue-context>

    <el-dialog
      :visible.sync="pickupVisible"
      title="添加成员"
      width="586px"
      custom-class="dialog-pick-up"
      :close-on-press-escape="false"
      :modal="false"
      append-to-body
      @open="onOpen"
    >
      <div class="transfer">
        <!-- 候选 -->
        <div class="transfer-left">
          <el-input class="transfer-left-query" placeholder="搜索" v-model="pickupName" @input="queryPickup"></el-input>
          <div class="transfer-left-list">
            <div class="transfer-left-list-item" v-for="(item, index) in pickupMemberList" :key="index">
              <el-checkbox v-model="item.checked">
                <div class="info">
                  <el-avatar :size="30">
                    <div class="avatar">{{ item.nameSlice }}</div>
                  </el-avatar>
                  <span class="name">{{ item.name }}</span>
                </div>
              </el-checkbox>
            </div>
          </div>
        </div>
        <div class="transfer-right">
          <div class="transfer-right-header">
            <span class="count">已选：{{ allMembers.filter((x) => !x.active && x.checked).length }}人</span>
            <span class="clear" @click="clearPickup">清空</span>
          </div>
          <div class="transfer-right-list">
            <div
              class="transfer-right-list-item"
              v-for="(item, index) in allMembers.filter((x) => !x.active && x.checked)"
              :key="index"
            >
              <div class="info">
                <el-avatar :size="30">
                  <div class="avatar">{{ item.nameSlice }}</div>
                </el-avatar>
                <span class="name">{{ item.name }}</span>
              </div>
              <i class="icon-remove" @click="item.checked = false"></i>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pickupVisible = false">取 消</el-button>
        <el-button type="primary" @click="addMembers">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ConferenceInviteMessageContent from "../../../wfc/av/messages/conferenceInviteMessageContent";
import Message from "../../../wfc/messages/message";
import ForwardType from "../../main/conversation/message/forward/ForwardType";
import UserCardView from "../../main/user/UserCardView";
import conferenceManager from "./conferenceManager";
import store from "@/store.js";

export default {
  name: "ConferenceParticipantListView",
  props: {
    participants: {
      type: Array,
      required: true,
    },
    session: {
      type: Object,
      required: true,
    },
    allMembers: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      conferenceManager: conferenceManager,
      selfUserId: conferenceManager.selfUserId,
      isContextMenuShow: false,
      currentParticipant: {},
      pickupVisible: false,
      pickupMemberList: [],
      pickupName: "",
      message: null,
    };
  },
  components: {
    UserCardView,
  },
  methods: {
    invite() {
      let callSession = this.session;
      let inviteMessageContent = new ConferenceInviteMessageContent(
        callSession.callId,
        conferenceManager.conferenceInfo.owner,
        callSession.title,
        callSession.desc,
        callSession.startTime,
        callSession.audioOnly,
        callSession.defaultAudience,
        callSession.advance,
        callSession.pin
      );
      // type:audio语音，video视频，videoup视频上拉；
      inviteMessageContent.extra = "{'type': 'invite','initiator': '侯晓晨','organization': ''}";
      console.log("invite", inviteMessageContent);
      this.message = new Message(null, inviteMessageContent);
      // TODO 弹出候选人框框
      this.pickupVisible = true;
      // this.$forwardMessage({
      //   forwardType: ForwardType.NORMAL,
      //   messages: [message],
      // });
      // this.showParticipantList = false;
    },
    onOpen() {
      this.pickupMemberList = this.allMembers.filter((x) => !x.active);
    },
    queryPickup(val) {
      if (val) {
        this.pickupMemberList = this.allMembers.filter((x) => {
          return x.name.indexOf(val) >= 0 && !x.active;
        });
      } else {
        this.pickupMemberList = this.allMembers.filter((x) => !x.active);
      }
    },
    clearPickup() {
      this.allMembers.forEach((member) => {
        if (!member.active) {
          member.checked = false;
        }
      });
    },
    addMembers() {
      const members = this.allMembers.filter((x) => !x.active && x.checked);
      console.log("addMembers", members);
      this.pickupVisible = false;
      if (!members || members.length === 0) {
        return;
      }
      const users = members.map((x) => {
        return {
          uid: x.tencentUserId,
          displayName: x.name,
        };
      });
      users.forEach((user) => {
        store.forwardByCreateConversation(ForwardType.NORMAL, [user], [this.message], "");
      });
    },
    requestChangeMode(user) {
      if (user.uid === this.selfUserInfo.uid) {
        // TODO 需要根据实际产品定义处理，这儿直接禁止
        //this.session.switchAudience(!user._isAudience);
        return;
      }
      this.$alert({
        content: user._isAudience ? `邀请${this.participantName(user)}参与互动?` : `取消${this.participantName(user)}参与互动?`,
        cancelCallback: () => {
          // do nothing
        },
        confirmCallback: () => {
          this.session.requestChangeMode(user.uid, !user._isAudience);
        },
      });
    },

    kickoff(user) {
      this.$alert(`确认将${this.participantName(user)}移除会议?`, "", {
        cancelCallback: () => {
          // do nothing
        },
        confirmCallback: () => {
          console.log(this.session);
          this.session.kickoffParticipant(user.uid);
        },
      }).then(() => {
        this.session.kickoffParticipant(user.uid);
      });
    },

    participantName(user) {
      let name = "";
      if (user.groupAlias) {
        name = user.groupAlias;
      } else if (user.friendAlias) {
        name = user.friendAlias;
      } else if (user.displayName) {
        name = user.displayName;
      } else {
        name = user.name;
      }
      return name;
    },
    participantDesc(user) {
      let desc = "";
      if (user.uid === conferenceManager.selfUserId) {
        desc = "我";
        if (user.uid === conferenceManager.conferenceInfo.owner) {
          desc += "、主持人";
        }
      } else if (user.uid === conferenceManager.conferenceInfo.owner) {
        desc = "主持人";
      } else if (user._isScreenSharing) {
        desc = "屏幕共享";
      }
      return desc;
    },

    buildParticipantContextMenu(participant) {
      let selfUid = conferenceManager.selfUserId;
      let items = [];
      if (!participant) {
        return items;
      }

      items.push({
        title: "查看用户信息",
        handler: () => {
          this.showUserCard(participant);
        },
      });

      if (selfUid === participant.uid) {
        // TODO 临时屏蔽，现在不支持同时开视频和音频
        // if (participant._isAudience) {
        //     items.push({
        //         title: '开启音视频',
        //         handler: () => {
        //             this.$eventBus.$emit('muteAudio', false)
        //             this.$eventBus.$emit('muteVideo', false)
        //         }
        //     })
        // }

        if (participant._isAudience) {
          if (participant._isAudioMuted) {
            items.push({
              title: "开启音频",
              handler: () => {
                this.$eventBus.$emit("muteAudio", false);
              },
            });
          }

          if (participant._isVideoMuted) {
            items.push({
              title: "开启视频",
              handler: () => {
                this.$eventBus.$emit("muteVideo", false);
              },
            });
          }
        } else {
          if (!participant._isAudioMuted) {
            items.push({
              title: "关闭音频",
              handler: () => {
                this.$eventBus.$emit("muteAudio", true);
              },
              styleObject: {
                color: "red",
              },
            });
          }
          if (!participant._isVideoMuted) {
            items.push({
              title: "关闭视频",
              handler: () => {
                this.$eventBus.$emit("muteVideo", true);
              },
              styleObject: {
                color: "red",
              },
            });
          }
          if (!participant._isVideoMuted && !participant._isAudioMuted) {
            items.push({
              title: "关闭音视频",
              handler: () => {
                this.$eventBus.$emit("muteAudio", true);
                this.$eventBus.$emit("muteVideo", true);
              },
              styleObject: {
                color: "red",
              },
            });
          }
        }
      }
      if (selfUid === conferenceManager.conferenceInfo.owner) {
        if (participant.uid !== selfUid) {
          if (participant._isAudience) {
            items.push({
              title: "邀请发言",
              handler: () => {
                conferenceManager.requestMemberMute(participant.uid, false);
              },
            });
          } else {
            items.push({
              title: "取消发言",
              handler: () => {
                conferenceManager.requestMemberMute(participant.uid, true);
              },
            });
          }
        }
        if (participant.uid !== selfUid) {
          items.push({
            title: " 移除成员",
            handler: () => {
              this.kickoff(participant);
            },
          });
        }
        if (conferenceManager.conferenceInfo.focus === participant.uid) {
          items.push({
            title: "取消焦点用户",
            handler: () => {
              conferenceManager.requestCancelFocus();
            },
          });
        } else {
          items.push({
            title: "设置为焦点用户",
            handler: () => {
              conferenceManager.requestFocus(participant.uid);
            },
          });
        }
      }
      return items;
    },

    showContextMenu(event, participant) {
      console.log(event);
      if (this.isContextMenuShow) {
        this.$refs.menu.close();
        this.isContextMenuShow = false;
        this.currentParticipant = {};
        return;
      }
      let ne = {
        type: "contextmenu",
      };
      console.log(this.$refs.rootContainer.parentElement);
      ne.clientX = event.clientX - this.$refs.rootContainer.parentElement.offsetLeft - 560;
      // 160 menu width
      // 360 slider width
      if (ne.clientX + 160 > 350) {
        ne.clientX = ne.clientX - 160;
      }
      ne.clientY = event.clientY - this.$refs.rootContainer.offsetTop - 280;
      this.$refs.menu.open(ne, participant);
      this.$refs.menu.$once("close", () => {
        this.isContextMenuShow = false;
        this.currentParticipant = {};
      });
      this.isContextMenuShow = true;
      this.currentParticipant = participant;
    },
    showUserCard(p) {
      this.$refs["userCardTippy-" + p.uid][0]._tippy.show();
    },
  },
};
</script>

<style scoped lang="scss">
.participant-list-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: auto;
  background-color: #ffffffe5;
  backdrop-filter: blur(6px);
  border-left: 1px solid #e6e6e6;
}

.participant-list-container .action-item {
  height: 50px;
  display: flex;
  padding: 5px 0 0 10px;
  align-items: center;
}

.participant-list-container .action-item .icon {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 3px;
  border: 1px dashed #d6d6d6;
  margin-right: 10px;
}

.participant-user {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px 0 5px 10px;
}

.participant-user.active {
  background: #d6d6d6;
}

.participant-user .name-desc {
  flex: 1;
}

.participant-user .name-desc .desc {
  font-size: 13px;
}

.audio-video {
  color: black;
  padding: 0 10px;
}

.audio-video i {
  padding: 5px;
}

.participant-user .avatar {
  width: 40px;
  height: 40px;
  border-radius: 3px;
  margin-right: 10px;
}

.avatar-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-container .icon {
  width: 40px;
  height: 40px;
  display: none;
  justify-content: center;
  align-items: center;
  border-radius: 3px;
  border: 1px dashed #d6d6d6;
  margin-right: 10px;
}

.avatar-container:hover .icon {
  display: flex;
  position: absolute;
  left: 0;
  top: 0;
  color: white;
  background: #e0d6d6d6;
}

::v-deep .dialog-pick-up {
  background: transparent;
  border-radius: 8px;
  .el-dialog__header {
    height: 46px;
    background: #0f71ff;
    border-radius: 8px 8px 0px 0px;
    border: 1px solid #2f2f2f;
    padding: 0 16px;
    display: flex;
    align-items: center;
    .el-dialog__title {
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC, serif;
      font-weight: 400;
      color: #ffffff;
    }
    .el-dialog__headerbtn {
      top: 15px;
      right: 16px;
      .el-dialog__close {
        color: #ffffff;
      }
    }
  }
  .el-dialog__body {
    background: #1e1e1e;
    padding: 16px;
    .transfer {
      width: 100%;
      height: 499px;
      display: grid;
      grid-template-columns: repeat(2, 50%);
      grid-auto-rows: 100%;
      background: #1e1e1e;
      border: 1px solid #333333;
      border-radius: 8px;
      &-left,
      &-right {
        height: 100%;
      }
      &-left {
        padding: 12px;
        &-query {
          margin-bottom: 12px;
          .el-input__inner {
            width: 100%;
            height: 38px;
            background: #000000;
            border-radius: 8px 8px 8px 8px;
            border: 1px solid #2b2b2b;
            color: #ffffff;
            &::placeholder {
              font-size: 14px;
              font-family: PingFang SC-Regular, PingFang SC, serif;
              font-weight: 400;
              color: #999999;
            }
          }
        }
        &-list {
          width: 100%;
          height: calc(100% - 50px);
          overflow-x: hidden;
          overflow-y: auto;
          &-item {
            width: 100%;
            height: 46px;
            border-radius: 8px 8px 8px 8px;
            //cursor: pointer;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            &:hover,
            &-active {
              width: 100%;
              background: #2b2b2b;
            }
            .info {
              display: flex;
              align-items: center;
              .avatar {
                width: 100%;
                height: 100%;
                border-radius: 50%;
                overflow: hidden;
                //margin-right: 16px;
                background: #0e71ff;
                font-size: 12px;
                font-weight: 400;
                color: #ffffff;
                //margin-right: 8px;
                img {
                  width: 100%;
                  height: auto;
                }
              }
              .name {
                font-size: 12px;
                line-height: 20px;
                font-family: PingFang SC-Regular, PingFang SC, serif;
                font-weight: 400;
                color: #ffffff;
                margin-left: 12px;
              }
            }
          }
        }
      }
      &-right {
        border-left: 1px solid #333333;
        padding: 0 12px;
        &-header {
          width: 100%;
          height: 62px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .count {
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC, serif;
            font-weight: 400;
            color: #ffffff;
          }
          .clear {
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC, serif;
            font-weight: 400;
            color: #0f71ff;
            cursor: pointer;
          }
        }
        &-list {
          width: 100%;
          height: calc(100% - 62px);
          overflow-x: hidden;
          overflow-y: auto;
          &-item {
            width: 100%;
            height: 46px;
            border-radius: 8px 8px 8px 8px;
            //cursor: pointer;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 16px;
            &:hover,
            &-active {
              width: 100%;
              background: #2b2b2b;
            }
            .info {
              display: flex;
              align-items: center;
              .avatar {
                width: 100%;
                height: 100%;
                border-radius: 50%;
                overflow: hidden;
                //margin-right: 16px;
                background: #0e71ff;
                font-size: 12px;
                font-weight: 400;
                color: #ffffff;
                //margin-right: 8px;
                img {
                  width: 100%;
                  height: auto;
                }
              }
              .name {
                font-size: 12px;
                line-height: 20px;
                font-family: PingFang SC-Regular, PingFang SC, serif;
                font-weight: 400;
                color: #ffffff;
                margin-left: 12px;
              }
            }
            .icon-remove {
              width: 12px;
              height: 12px;
              display: block;
              cursor: pointer;
              background: url("~@/assets/images/conversation/关闭 2.png") no-repeat;
              background-size: 100% 100%;
            }
          }
        }
      }
    }
  }
  .el-dialog__footer {
    background: #1e1e1e;
    height: 70px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .el-button {
      width: 120px;
      height: 38px;
      font-size: 14px;
      &--default {
        color: #ffffff;
        background: transparent;
        border: 1px solid #666666;
      }
    }
  }
}
</style>
