<template>
  <div>
    <i class="icon icon-chat-setting" @click="toggleShow"></i>
    <div class="manage" :class="[isH5 ? 'manage-h5' : '']" v-if="show" ref="dialog">
      <header :class="['manage-header', currentTab === 'onlyMute' ? 'currentModel' : '']">
        <i class="icon icon-back" v-if="isH5 && !currentTab" @click="toggleShow"></i>
       
        <aside class="manage-header-left">
          <i class="icon icon-back" v-if="currentTab" @click="() =>{
            currentModel = 'not_mute'
            setTab('')
          }"></i>
          <main v-if="currentTab !== 'onlyMute'">
            <h1>{{ TabName }} <span v-if="currentTab === 'member'"> {{ groupDetail.memberNum || 0 }}{{ $t(`TUIChat.manage.人`) }} </span></h1>
          </main>
           <n-tabs
            v-else
              justify-content="center"
              style="margin-left: -14Px;flex: 1; --n-tab-padding: 6px 0; --n-tab-gap: 34px; --n-tab-text-color: #000; --n-tab-text-color-hover: #0f0f0f; --n-tab-text-color-active: #000; --n-tab-font-weight-active: 600; --n-bar-color: #198cfe"
              :bar-width="20"
              :value="currentModel"
              @update:value="
                (val: any) => {
                  currentModel = val;
                  mutePage = 1
                  muteSearch = ''
                  getUserList()
                }
              "
            >
            <n-tab-pane name="not_mute" tab="未禁言"></n-tab-pane>
            <n-tab-pane name="mute" tab="已禁言"></n-tab-pane>
          </n-tabs>
        </aside>
        <span  v-if="currentTab !== 'onlyMute'">
          <i v-if="!isH5" class="icon icon-close" @click="toggleShow"></i>
        </span>
      </header>
      <main :class="['main']" style="background-color: #f4f5f9; height: 100%" v-if="!currentTab">
        <ManageName class="space-top" :isAuth="isAuth" :isH5="isH5" :data="conversation.groupProfile" @update="updateProfile" style="background-color: #fff" />
        <div class="userInfo space-top" style="background-color: #fff">
          <header class="userInfo-header" @click="setTab('member')">
            <label>{{ $t(`TUIChat.manage.群成员`) }}</label>
            <p>
              <span> {{ groupDetail.memberNum || 0 }}{{ $t(`TUIChat.manage.人`) }} </span>
              <i class="icon icon-right"></i>
            </p>
          </header>
          <ol>
            <!-- @click="handleMemberProfileShow(item)" -->
            <dl v-for="(item, index) in userInfo?.list?.slice(0, showUserNum)" :key="index">
              <dt>
                <img class="avatar" :src="item?.avatar || 'https://oss.dayaedu.com/news-info/07/1690787574969.png'" onerror="this.src='https://oss.dayaedu.com/news-info/07/1690787574969.png'" />
              </dt>
              <dd>{{ item?.nickname || item?.userID }}</dd>
            </dl>
            <!-- v-if="isShowAddMember" -->
            <dl v-if="currentUserDetail.groupRoleType === 'Owner'">
              <dt class="avatar" @click="toggleMask('add')">+</dt>
            </dl>
            <!-- <dl v-if="conversation.groupProfile.selfInfo.role === 'Owner'">
              <dt class="avatar" @click="toggleMask('remove')">-</dt>
            </dl> -->
          </ol>
        </div>
        <ul class="content space-top" @click="editLableName = ''" style="background-color: #fff">
          <li @click.stop="setTab('notification')">
            <aside>
              <label>{{ $t(`TUIChat.manage.群公告`) }}</label>
              <article>{{ conversation.groupProfile.notification }}</article>
            </aside>
            <i class="icon icon-right end"></i>
          </li>
          <!-- <li v-if="isAdmin && isSetMuteTime" @click.stop="setTab('admin')">
            <label>{{ $t(`TUIChat.manage.群管理`) }}</label>
            <i class="icon icon-right"></i>
          </li>
          <li>
            <label>{{ $t(`TUIChat.manage.群ID`) }}</label>
            <div class="groupID">
              <span>{{ conversation.groupProfile.groupID }}</span>
              <i
                class="icon icon-msg-copy"
                @click="handleGroupIDCopy"
                :title="$t('TUIChat.复制')"
              ></i>
            </div>
          </li>
          <li>
            <label>{{ $t(`TUIChat.manage.群头像`) }}</label>
            <img
              class="avatar"
              :src="
                conversation?.groupProfile?.avatar ||
                'https://oss.dayaedu.com/news-info/07/1690775328089.png'
              "
              onerror="this.src='https://oss.dayaedu.com/news-info/07/1690775328089.png'"
            />
          </li>
          <li>
            <label>{{ $t(`TUIChat.manage.群类型`) }}</label>
            <span>
              {{
                $t(`TUIChat.manage.${typeName[conversation.groupProfile.type]}`)
              }}
            </span>
          </li>
          <li>
            <label>{{ $t(`TUIChat.manage.加群方式`) }}</label>
            <span>
              {{
                $t(
                  `TUIChat.manage.${
                    typeName[conversation.groupProfile.joinOption]
                  }`
                )
              }}
            </span>
          </li> -->
        </ul>

        <div v-if="currentUserDetail.groupRoleType === 'Owner' || currentUserDetail.groupRoleType === 'Admin'" class="admin-content space-top" style="background-color: #fff; padding-top: 12px;border-top: 1Px solid #f4f5f9;">
          <aside>
            <label>学生禁言</label>
          </aside>
          <Slider :open="groupDetail.configJson.mute" @change="setAllMuteTime" />
        </div>
        <div v-if="currentUserDetail.groupRoleType === 'Owner' || currentUserDetail.groupRoleType === 'Admin'" class="admin-content space-top" style="background-color: #fff; padding-top: 12px;border-top: 1Px solid #f4f5f9;" @click.stop="() => {
          userInfo.muteList = []
          setTab('onlyMute')
        }">
          <aside>
            <label>禁言名单</label>
          </aside>
          <i class="icon icon-right end"></i>
        </div>
         <div v-if="currentUserDetail.groupRoleType === 'Owner' && userInfo?.list.length > 1" class="admin-content space-top" style="background-color: #fff;padding-top: 12px; border-top: 1Px solid #f4f5f9;"  @click.stop="toggleMask('changeOwner')">
          <aside>
            <label>移交群主</label>
          </aside>
          <i class="icon icon-right end"></i>
        </div>
        <ul class="footer space-top" style="overflow: hidden; background-color: #f4f5f9;">
          <!-- <li v-if="currentUserDetail.groupRoleType === 'Owner' && userInfo?.list.length > 1" @click.stop="toggleMask('changeOwner')">移交群主</li> -->
          <li v-if="currentUserDetail.groupRoleType === 'Owner'" @click.stop="dismiss(conversation.groupProfile)">解散群聊</li>
          <li v-else @click.stop="quit(conversation.groupProfile)">退出群组</li>
        </ul>
      </main>
      <ManageMember v-else-if="currentTab === 'member'" :self="conversation.groupProfile.selfInfo" :list="userInfo.list" :total="~~conversation.groupProfile.memberCount" @more="getMember('more')" @del="submit" @handleMemberProfileShow="handleMemberProfileShow" />
      <!-- :isShowDel="conversation.groupProfile.selfInfo.role === 'Owner'" -->
      <MemeberProfile v-else-if="currentTab === 'profile'" :userInfo="currentMember" />
      <ManageNotification ref="manageNotificationRef" v-else-if="currentTab === 'notification' || currentTab === 'notificationAdd' || currentTab === 'notificationUpdate'" :isAuth="isAuth" :data="conversation.groupProfile" @update="updateProfile" @changeStatus="onNotificationChangeStatus" />
      <ManageNotificationDetail ref="manageNotificationDetailRef" v-else-if="currentTab === 'notificationDetail' || currentTab === 'notificationAddDetail' || currentTab === 'notificationUpdateDetail'" :noticeId="noticeId" :isAuth="isAuth" :data="conversation.groupProfile" @changeStatus="onNotificationChangeStatus" />
      <main class="admin" v-else-if="currentTab === 'admin'">
        <div class="admin-list" v-if="isAdmin">
          <label>{{ $t(`TUIChat.manage.群管理员`) }}</label>
          <ol>
            <dl v-for="(item, index) in member.admin" :key="index">
              <dt>
                <img class="avatar" :src="item?.avatar || 'https://oss.dayaedu.com/news-info/07/1690787574969.png'" onerror="this.src='https://oss.dayaedu.com/news-info/07/1690787574969.png'" />
              </dt>
              <dd>{{ item?.nick || item?.userID }}</dd>
            </dl>
            <dl>
              <dt class="avatar" @click="toggleMask('addAdmin')">+</dt>
            </dl>
            <dl>
              <dt class="avatar" v-if="member.admin.length > 0" @click="toggleMask('removeAdmin')">-</dt>
            </dl>
          </ol>
        </div>
        <div class="admin-content space-top" v-if="isSetMuteTime">
          <aside>
            <label>{{ $t(`TUIChat.manage.学生禁言`) }}</label>
            <p>
              {{ $t(`TUIChat.manage.学生禁言开启后，只允许群主和管理员发言。`) }}
            </p>
          </aside>
          <Slider :open="conversation.groupProfile.muteAllMembers" @change="setAllMuteTime" />
        </div>
        <div class="admin-list last" v-if="isSetMuteTime">
          <label>{{ $t(`TUIChat.manage.单独禁言人员`) }}</label>
          <ol>
            <dl v-for="(item, index) in member.muteMember" :key="index">
              <dt>
                <img class="avatar" :src="item?.avatar || 'https://oss.dayaedu.com/news-info/07/1690787574969.png'" onerror="this.src='https://oss.dayaedu.com/news-info/07/1690787574969.png'" />
              </dt>
              <dd>{{ item?.nick || item?.userID }}</dd>
            </dl>
            <dl>
              <dt class="avatar" @click="toggleMask('addMute')">+</dt>
            </dl>
            <dl>
              <dt class="avatar" v-if="member.muteMember.length > 0" @click="toggleMask('removeMute')">-</dt>
            </dl>
          </ol>
        </div>
      </main>
      <ManageMute  v-else-if="currentTab === 'onlyMute'" :currentModel="currentModel" 
        :total="muteTotal" 
        :self="conversation.groupProfile.selfInfo" :list="userInfo.muteList" 
        :conversation="conversation" 
        :muteLoading="muteLoading"
        @more="getUserList('more')" 
        @del="submit" 
        @back="() => {  
          setTab(''); 
          currentModel = 'not_mute' 
        }" 
        @search="(keyword) => {
          mutePage = 1
          muteSearch = keyword
          userInfo.muteList = []
          getUserList()
        }" 
        @handleMemberProfileShow="handleMemberProfileShow" />
     
      <MaskTUI :show="mask" @update:show="(e) => (mask = e)">
        <Transfer :title="$t(`TUIChat.manage.${transferTitle}`)" :list="transferList" :isSearch="isSearch" :isRadio="isRadio" :selectedList="selectedList" @submit="submit" @cancel="cancel" @search="handleSearchMember" :isH5="isH5" />
      </MaskTUI>
      <DialogTUI :title="$t(`TUIChat.manage.删除成员`)" :show="delDialogShow" :isH5="isH5" :center="true" :isHeaderShow="!isH5" @submit="handleManage(userList, 'remove')" @update:show="(e) => (delDialogShow = e)">
        <p v-if="userList.length === 1" class="delDialog-title">
          {{ $t(`TUIChat.manage.确定从群聊中删除该成员？`) }}
        </p>
        <p v-if="userList.length > 1" class="delDialog-title">
          {{ $t(`TUIChat.manage.确定从群聊中删除所选成员？`) }}
        </p>
      </DialogTUI>

      <DialogTUI title="退出群聊" :show="quitDialogShow" :isH5="isH5" :center="true" :isHeaderShow="!isH5" @submit="handleManage([], 'quit')" @update:show="(e) => (quitDialogShow = e)">
        <p class="delDialog-title">是否退出群聊？</p>
      </DialogTUI>
      <DialogTUI title="解散群聊" :show="dimmisDialogShow" :isH5="isH5" :center="true" :isHeaderShow="!isH5" @submit="handleManage([], 'dismiss')" @update:show="(e) => (dimmisDialogShow = e)">
        <p class="delDialog-title">是否解散群聊？</p>
      </DialogTUI>
    </div>
  </div>
</template>

<script lang="ts">
import TUIMessage from "../../../components/messageTUI/index";
import { defineComponent, watchEffect, reactive, toRefs, computed, watch, ref, onMounted } from "vue";
import { onClickOutside } from "@vueuse/core";
import MaskTUI from "../../../components/maskTUI/mask.vue";
import Transfer from "../../../components/transferTUI/index.vue";
import Slider from "../../../components/sliderTUI/index.vue";
import ManageName from "./manage-name.vue";
import ManageNotification from "./manage-notification.vue";
import ManageNotificationDetail from "./manage-notification-detail.vue";
import ManageMember from "./manage-member.vue";
import MemeberProfile from "./member-profile.vue";
import ManageMute from './manage-mute.vue'
import DialogTUI from "../../../components/dialogTUi/index.vue";
import { imGroupChangeGroupOwner, imGroupDetail, imGroupDismiss, imGroupMemberPage, imGroupMemberSaveImAll, imGroupMemberUserDetail, imGroupMuteAll, imGroupQuit, imUserFriendPage } from "../../../../api";
import Vuex from "vuex";
import { handleErrorPrompts } from "../../utils";
import useClipboard from "vue-clipboard3";
import { eventGlobal } from "@/helpers";

const manage = defineComponent({
  components: {
    MaskTUI,
    Transfer,
    Slider,
    ManageName,
    ManageNotification,
    ManageNotificationDetail,
    ManageMember,
    MemeberProfile,
    ManageMute,
    DialogTUI,
  },
  props: {
    userInfo: {
      type: Object,
      default: () => ({
        isGroup: false,
        list: [],
      }),
    },
    conversation: {
      type: Object,
      default: () => ({}),
    },
    show: {
      type: Boolean,
      default: () => false,
    },
    isH5: {
      type: Boolean,
      default: () => false,
    },
  },
  setup(props: any, ctx: any) {
    const types: any = manage.TUIServer.TUICore.TIM.TYPES;

    const { GroupServer } = manage;
    const { t } = manage.TUIServer.TUICore.config.i18n.useI18n();
    const data: any = reactive({
      conversation: {},
      userInfo: {
        isGroup: false,
        list: [],
        muteList: []
      },
      isShowMuteTimeInput: false,
      editLableName: "",
      mask: false,
      currentTab: "",
      noticeId: "", // 查看公告详情时
      transferType: "",
      isSearch: false,
      isRadio: false,
      transferList: [],
      selectedList: [],
      isMuteTime: false,
      show: false,
      typeName: {
        [types.GRP_WORK]: "好友工作群",
        [types.GRP_PUBLIC]: "陌生人社交群",
        [types.GRP_MEETING]: "临时会议群",
        [types.GRP_AVCHATROOM]: "直播群",
        [types.JOIN_OPTIONS_FREE_ACCESS]: "自由加入",
        [types.JOIN_OPTIONS_NEED_PERMISSION]: "需要验证",
        [types.JOIN_OPTIONS_DISABLE_APPLY]: "禁止加群",
      },
      delDialogShow: false,
      quitDialogShow: false,
      dimmisDialogShow: false,
      userList: [],
      transferTitle: "",
      member: {
        admin: [],
        member: [],
        muteMember: [],
      },
      currentMember: {},
      classGroupDetail: {}, // 群详情
      page: 1, // 当前默认查询第一页数据
      currentUserDetail: {} as any, // 用户信息
      mutePage: 1,
      muteSearch: '',
      muteLoading: false,
      muteTotal: 0,
      groupDetail: {} as any,
      currentModel: 'not_mute'
    });

    const dialog: any = ref();
    const manageNotificationRef: any = ref()
    const manageNotificationDetailRef: any = ref()

    watchEffect(() => {
      data.conversation = props.conversation;
      data.userInfo = props.userInfo;
      data.show = props.show;
    });

    const VuexStore = ((window as any)?.TUIKitTUICore?.isOfficial && (Vuex as any)?.useStore()) || {};

    const TabName = computed(() => {
      let name = "";
      switch (data.currentTab) {
        case "notification":
          name = "群公告";
          break;
        case "notificationAdd":
          case "notificationAddDetail":
          name = '添加群公告';
          break;
        case "notificationUpdate":
        case "notificationUpdateDetail":
          name = '修改群公告';
          break;
        case "notificationDetail":
          name = "公告详情";
          break;
         case "member":
          name = "群成员";
          break;
        case "profile":
          name = "群成员";
          break;
        default:
          name = "群管理";
          break;
      }
      return name;
    });

    watch(
      () => data.userInfo.list,
      (newValue: any, oldValue: any) => {
        data.member = {
          admin: [],
          member: [],
          muteMember: [],
        };
        // TIM.TYPES.GRP_MBR_ROLE_ADMIN（群管理员）,
        // TIM.TYPES.GRP_MBR_ROLE_MEMBER（群普通成员）,
        // TIM.TYPES.GRP_MBR_ROLE_CUSTOM（自定义群成员角色，仅社群支持）
        newValue.map((item: any) => {
          switch (item?.groupRoleType) {
            case "Admin":
              data.member.admin.push(item);
              break;
            case "Member":
              data.member.member.push(item);
              break;
            default:
              break;
          }
          return item;
        });
        const time: number = new Date().getTime();
        data.member.muteMember = newValue.filter((item: any) => item?.muteUntil * 1000 - time > 0);
      },
      { deep: true }
    );

    const isDismissGroupAuth = computed(() => {
      const { conversation } = data;
      const userRole = conversation?.groupProfile?.selfInfo.role;
      const groupType = conversation?.groupProfile?.type;

      const isOwner = userRole === types.GRP_MBR_ROLE_OWNER;
      const isWork = groupType === types.GRP_WORK;

      return isOwner && !isWork;
    });

    const isShowAddMember = computed(() => {
      const { conversation } = data;
      const groupType = conversation?.groupProfile?.type;
      const isWork = groupType === types.GRP_WORK;

      if (isWork) {
        return true;
      }
      return false;
    });

    const showUserNum = computed(() => {
      let num = 3;
      if (!isShowAddMember.value) {
        num += 1;
      }
      if ((data.conversation as any).groupProfile.selfInfo.role !== "Owner") {
        num += 1;
      }
      return num;
    });

    const isAuth = computed(() => {
      const { conversation } = data;
      const userRole = conversation?.groupProfile?.selfInfo.role;

      const isOwner = userRole === types.GRP_MBR_ROLE_OWNER;
      const isAdmin = userRole === types.GRP_MBR_ROLE_ADMIN;

      return isOwner || isAdmin;
    });

    const isAdmin = computed(() => {
      const { conversation } = data;
      const groupType = conversation?.groupProfile?.type;
      const userRole = conversation?.groupProfile?.selfInfo.role;

      const isOwner = userRole === types.GRP_MBR_ROLE_OWNER;
      const isWork = groupType === types.GRP_WORK;
      const isAVChatRoom = groupType === types.GRP_AVCHATROOM;

      if (!isWork && !isAVChatRoom && isOwner) {
        return true;
      }
      return false;
    });

    const isSetMuteTime = computed(() => {
      const { conversation } = data;
      const groupType = conversation?.groupProfile?.type;
      const isWork = groupType === types.GRP_WORK;

      if (isWork || !isAuth.value) {
        return false;
      }
      return true;
    });

    const getMember = async (type?: string) => {
      try {
        const { conversation } = data;
        // console.log(conversation, "getMember -------");
        const options: any = {
          groupId: conversation?.groupProfile?.groupID,
          rows: 100,
          page: type && type === "more" ? data.page + 1 : data.page,
          // offset: type && type === "more" ? data.userInfo.list.length : 0,
        };
        await imGroupMemberPage(options).then((res: any) => {
          const rows = res.data.rows || [];
          rows.forEach((row: any) => {
            row.nick = row.nickname;
          });
          if (type && type === "more") {
            data.userInfo.list = [...data.userInfo.list, ...rows];
          } else {
            data.userInfo.list = rows;
          }
        });
        // GroupServer.getGroupMemberList(options)
      } catch {
        //
      }
    };

    // 禁言
    const getUserList = async (type?: string) => {
      data.muteLoading = true;
      try {
        const { conversation } = data;
        const options: any = {
          groupId: conversation?.groupProfile?.groupID,
          rows: 100,
          groupMute: data.currentModel === 'not_mute' ? false : true,
          groupRoleTypes: ['Member'],
          page: type && type === "more" ? data.mutePage + 1 : data.mutePage,
          keyword: data.muteSearch
        };
        await imGroupMemberPage(options).then((res: any) => {
          const rows = res.data.rows || [];
          rows.forEach((row: any) => {
            row.nick = row.nickname;
          });
          if (type && type === "more") {
            data.userInfo.muteList = [...data.userInfo.list, ...rows];
          } else {
            data.userInfo.muteList = rows;
          }
          data.muteTotal = res.data.total || 0;
        });
      } catch {
        //
      }
      data.muteLoading = false;
    };

    const addMember = async (userIDList: any) => {
      const { conversation } = data;
      // const options: any = {
      //   groupID: conversation.groupProfile.groupID,
      //   userIDList,
      // };
      // await GroupServer.addGroupMember(options);
      const params: any = [];
      userIDList.forEach((id: any) => {
        params.push({
          groupId: conversation.groupProfile.groupID,
          imUserId: id,
        });
      });
      // console.log(params, userIDList, "userIDList");
      // return;
      try {
        await imGroupMemberSaveImAll(params);

        getGroupDetail();
        getMember();
      } catch {
        //
      }
    };

    const deleteMember = (user: any) => {
      const { conversation } = data;
      const options: any = {
        groupID: conversation.groupProfile.groupID,
        userIDList: [user.userID],
      };
      GroupServer.deleteGroupMember(options);
    };

    const changeOwner = async (userID: any) => {
      // const options: any = {
      //   groupID: data.conversation.groupProfile.groupID,
      //   newOwnerID: userID,
      // };
      // const imResponse = await GroupServer.changeGroupOwner(options);

      // data.conversation.groupProfile = imResponse.data.group;
      console.log(data.conversation.groupProfile, userID);
      // 腾讯IM切换人之后
      await imGroupChangeGroupOwner({
        oldOwner: data.conversation.groupProfile.ownerID,
        groupId: data.conversation.groupProfile.groupID,
        newOwner: userID,
      });
      toggleShow();
      data.conversation.groupProfile = {};

      TUIMessage({
        message: "转交成功",
        isH5: false,
        type: "success",
      });
    };

    const quit = async (group: any) => {
      data.quitDialogShow = true;
    };

    const dismiss = async (group: any) => {
      data.dimmisDialogShow = true;
      // console.log(manage.TUIServer.deleteConversation, "manage.TUIServer");
      //       manage.TUIServer.deleteConversation(data.conversation.conversationID);
      //       manage.TUIServer.store.conversation = {};
      //       toggleShow();
      // await GroupServer.dismissGroup(group.groupID);
      // manage.TUIServer.store.conversation = {};
      // (window as any)?.TUIKitTUICore?.isOfficial && VuexStore?.commit && VuexStore?.commit("handleTask", 5);
    };

    const handleAdmin = async (user: any) => {
      const { conversation } = data;
      let role = "";
      switch (user.role) {
        case types.GRP_MBR_ROLE_ADMIN:
          role = types.GRP_MBR_ROLE_MEMBER;
          break;
        case types.GRP_MBR_ROLE_MEMBER:
          role = types.GRP_MBR_ROLE_ADMIN;
          break;
      }
      const options: any = {
        groupID: conversation.groupProfile.groupID,
        userID: user.userID,
        role,
      };
      await GroupServer.setGroupMemberRole(options);
      getMember();
    };

    const setMemberMuteTime = async (userID: string, type?: string) => {
      const { conversation } = data;
      const options: any = {
        groupID: conversation.groupProfile.groupID,
        userID,
        muteTime: type === "add" ? 60 * 60 * 24 * 30 : 0,
      };
      await GroupServer.setGroupMemberMuteTime(options);
      if (type === "add") {
        (window as any)?.TUIKitTUICore?.isOfficial && VuexStore?.commit && VuexStore?.commit("handleTask", 4);
      }
      getMember();
    };

    const kickedOut = async (userIDList: any) => {
      const { conversation } = data;
      const options: any = {
        groupID: conversation.groupProfile.groupID,
        userIDList,
        reason: "",
      };
      await GroupServer.deleteGroupMember(options);
      getMember();
    };

    const edit = (labelName: string) => {
      data.editLableName = labelName;
    };

    /** 群公告修改 */
    const onNotificationChangeStatus = (type: string) => {
      if(type === "add") {
        data.currentTab = 'notificationAdd'
      } else if(type === "edit") {
        data.currentTab = 'notificationUpdate'
      } else if(type === "submit") {
        data.currentTab = 'notification'
      } else if(type === "addDetail") {
        data.currentTab = 'notificationAddDetail'
      } else if(type === "editDetail") {
        data.currentTab = 'notificationUpdateDetail'
      } else if(type === "submitDetail") {
        data.currentTab = 'notificationDetail'
      } else if(type === "deleteDetail") {
        data.currentTab = ""
      }
    }

    const updateProfile = async (params: any) => {
      const { key, value } = params;
      const options: any = {
        groupID: data.conversation.groupProfile.groupID,
        [key]: value,
      };
      const res = await GroupServer.updateGroupProfile(options);
      const { conversation } = manage.TUIServer.store;
      conversation.groupProfile = res.data.group;
      manage.TUIServer.store.conversation = {};
      manage.TUIServer.store.conversation = conversation;
      data.editLableName = "";
    };

    const setTab = (tabName: string) => {
      if(data.currentTab === "notificationAdd" || data.currentTab === "notificationUpdate") {
        manageNotificationRef.value?.onCloseEdit()
        data.currentTab = 'notification'
        return
      }
      if(data.currentTab === "notificationAddDetail" || data.currentTab === "notificationUpdateDetail") {
        manageNotificationDetailRef.value?.onCloseEdit()
        data.currentTab = 'notificationDetail'
        return
      }

      if(tabName === 'onlyMute') {
        getUserList()
      }
      data.currentTab = tabName;
      data.editLableName = "";
      if (data.currentTab === "member") {
        data.transferType = "remove";
      }
      if (!data.currentTab) {
        data.transferType = "";
      }
      
    };

    const handleSearchMember = async (value: string) => {
      let imResponse: any = {};
      let imMemberResponse: any = {};
      const options: any = {
        groupID: data.conversation.groupProfile.groupID,
        userIDList: [value],
      };
      switch (data.transferType) {
        case "add":
          try {
            imMemberResponse = await GroupServer.getGroupMemberProfile(options);
            data.transferList = data.transferList.filter((item: any) => item.userID !== imResponse.data[0]?.userID);
            data.transferList = [...data.transferList, ...imResponse.data];
            if (imMemberResponse?.data?.memberList.length > 0) {
              data.transferList = data.transferList.map((item: any) => {
                if (item.userID === imMemberResponse?.data?.memberList[0].userID) {
                  item.isDisabled = true;
                }
                return item;
              });
            }
          } catch (error) {
            const message = t("TUIChat.manage.该用户不存在");
            handleErrorPrompts(message, props);
          }
          break;
        case "remove":
          try {
            imResponse = await GroupServer.getGroupMemberProfile(options);
            if (imResponse.data.memberList.length === 0) {
              const message = t("TUIChat.manage.该用户不在群组内");
              return handleErrorPrompts(message, props);
            }
            data.transferList = data.transferList.filter(
              (item: any) =>
                // eslint-disable-next-line no-unsafe-optional-chaining
                item.userID !== imResponse?.data?.memberList[0]?.userID
            );
            data.transferList = [
              ...data.transferList,
              // eslint-disable-next-line no-unsafe-optional-chaining
              ...imResponse?.data?.memberList,
            ];
          } catch (error) {
            const message = t("TUIChat.manage.该用户不存在");
            handleErrorPrompts(message, props);
          }
          break;
        default:
          break;
      }
    };

    const submit = (userList: any) => {
      console.log(userList, data.transferType, " data.transferType");
      if(userList.length <= 0) return
      
      if (data.transferType === "remove") {
        data.userList = userList;
        data.delDialogShow = !data.delDialogShow;
      } else {
        handleManage(userList, data.transferType);
      }
      data.mask = false;
    };

    const friendList = async () => {
      const list = await imUserFriendPage({ page: 1, rows: 999 });
      console.log(list, "lits");
      const fristList = list.data.rows || [];
      fristList.forEach((item: any) => {
        item.nick = item.friendNickname;
      });
      return fristList.filter((item: any) => !data.userInfo.list.some((infoItem: any) => infoItem.imUserId === item.imUserId));
    };

    const cancel = () => {
      toggleMask();
    };

    const toggleMask = async (type?: string) => {
      data.selectedList = [];
      switch (type) {
        case "add":
          data.isRadio = false;
          data.transferList = await friendList();
          data.transferTitle = "添加成员";
          break;
        case "remove":
          data.isRadio = false;
          data.transferList = data.userInfo.list.filter(
            (item: any) =>
              // eslint-disable-next-line no-unsafe-optional-chaining
              item.userID !== data.conversation?.groupProfile?.selfInfo.userID
          );
          data.transferTitle = "删除成员";
          break;
        case "addAdmin":
          data.isRadio = true;
          data.transferList = data.member.member;
          data.transferTitle = "新增管理员";
          break;
        case "removeAdmin":
          data.isRadio = true;
          data.transferList = data.member.admin;
          data.transferTitle = "移除管理员";
          break;
        case "changeOwner":
          data.isRadio = true;
          data.transferList = [...data.member.admin, ...data.member.member].filter(item => item.roleType !== "STUDENT");
          data.transferTitle = "转让群组";
          console.log(data.transferList, "data.transferList");
          break;
        case "addMute":
          data.isRadio = true;
          data.transferList = data.member.member;
          if (data.conversation.groupProfile.selfInfo.role === "Owner") {
            data.transferList = [...data.member.admin, ...data.member.member];
          }
          data.transferTitle = "新增禁言用户";
          break;
        case "removeMute":
          data.isRadio = true;
          data.transferList = data.member.muteMember;
          data.transferTitle = "移除禁言用户";
          break;
        default:
          break;
      }
      data.transferType = type;
      data.mask = !data.mask;
    };

    onClickOutside(dialog, () => {
      data.show = false;
    });

    const toggleShow = () => {
      if (!GroupServer) {
        const message = t("TUIChat.manage.请先注册 TUIGroup 模块");
        return handleErrorPrompts(message, props);
      }
      data.show = !data.show;
      if (!data.show) {
        data.currentTab = "";
      }
      if (data.show) {
        getMember();
      }
    };

    // 禁言
    const setAllMuteTime = async (value: boolean) => {
      // updateProfile({ key: "muteAllMembers", value });
      // (window as any)?.TUIKitTUICore?.isOfficial && VuexStore?.commit && VuexStore?.commit("handleTask", 4);
      try {
        await imGroupMuteAll({
          groupId: data.conversation.groupProfile.groupID,
          muteAll: value,
        });

        getGroupDetail();
      } catch {
        //
      }
    };

    const handleManage = (userList: any, type: any) => {
      const userIDList: any = [];
      userList.map((item: any) => {
        userIDList.push(item.imUserId);
        return item;
      });
      switch (type) {
        case "add":
          addMember(userIDList);
          break;
        case "remove":
          kickedOut(userIDList);
          break;
        case "addAdmin":
          handleAdmin(userList[0]);
          break;
        case "removeAdmin":
          handleAdmin(userList[0]);
          break;
        case "changeOwner":
          changeOwner(userIDList[0]);
          break;
        case "addMute":
          setMemberMuteTime(userIDList[0], "add");
          break;
        case "removeMute":
          setMemberMuteTime(userIDList[0], "remove");
          break;
        case "quit":
          // 退出群聊
          imGroupQuit({
            id: data.conversation.groupProfile.groupID,
          }).then(() => {
            eventGlobal.emit("removeGroup", data.conversation.groupProfile.groupID);
            manage.TUIServer.deleteConversation(data.conversation.conversationID);
            manage.TUIServer.store.conversation = {};
            toggleShow();
          });
          break;
        case "dismiss":
          // 解散群
          imGroupDismiss({
            id: data.conversation.groupProfile.groupID,
          })
            .then(() => {
              eventGlobal.emit("removeGroup", data.conversation.groupProfile.groupID);
              manage.TUIServer.deleteConversation(data.conversation.conversationID);
              manage.TUIServer.store.conversation = {};
              toggleShow();
            })
            .catch((err: any) => {
              TUIMessage({
                message: err.message,
                isH5: false,
                type: "error",
              });
            });
          break;
        default:
          break;
      }
    };

    const handleGroupIDCopy = async () => {
      try {
        const { toClipboard } = useClipboard();
        await toClipboard(data?.conversation?.groupProfile?.groupID);
      } catch (error) {
        handleErrorPrompts(error, data.env);
      }
    };

    const handleMemberProfileShow = (user: any) => {
      data.currentMember = user;
      setTab("profile");
    };

    const getGroupMemberUserDetail = async () => {
      try {
        const res = await imGroupMemberUserDetail({
          groupId: data?.conversation?.groupProfile?.groupID,
          imUserId: data?.conversation?.groupProfile?.selfInfo.userID,
        });

        data.currentUserDetail = res.data;

      } catch {
        //
      }
    };

    /** 获取群详情 */
    const getGroupDetail = async () => {
      try {
        const res = await imGroupDetail({ id: data?.conversation?.groupProfile?.groupID });
        const tdata = res.data;
        tdata.configJson = tdata.configJson ? JSON.parse(tdata.configJson) : {};
        data.groupDetail = tdata;
      } catch {
        //
      }
    };

    watch(
      () => data.show,
      () => {
        if (data.show) {
          try {
            getGroupDetail();
            getGroupMemberUserDetail();
          } catch {
            //
          }
        }
      }
    );

    onMounted(() => {
      eventGlobal.on('handleNotice', (id: any) => {
        data.show = !data.show;
        data.noticeId = id
        data.currentTab = "notificationDetail"
        if (data.show) {
          getMember();
        }
      })
      try {
        getGroupDetail();
        getGroupMemberUserDetail();
        // console.log(data?.conversation, "data?.conversation?");
        // console.log(data.userInfo.list, "data.userInfo.list");
      } catch {
        //
      }
    });

    return {
      ...toRefs(data),
      isDismissGroupAuth,
      isShowAddMember,
      isSetMuteTime,
      isAdmin,
      isAuth,
      addMember,
      deleteMember,
      changeOwner,
      quit,
      dismiss,
      handleAdmin,
      setMemberMuteTime,
      kickedOut,
      edit,
      onNotificationChangeStatus,
      updateProfile,
      setTab,
      TabName,
      getMember,
      getUserList,
      handleSearchMember,
      submit,
      cancel,
      toggleMask,
      toggleShow,
      setAllMuteTime,
      handleManage,
      showUserNum,
      dialog,
      manageNotificationRef,
      manageNotificationDetailRef,
      handleGroupIDCopy,
      handleMemberProfileShow,
    };
  },
});
export default manage;
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
