<template>
    <div class="container">
      <!-- 加载中 -->
      <van-loading class="load-box" size="24px" v-if="loading">加载中...</van-loading>
  
      <template v-else>
        <van-index-bar class="list">
          <template v-for="(group, groupIndex) in memberGroups" :key="group.index">
            <van-index-anchor :index="group.index" />
            <van-checkbox-group v-model="checked">
              <van-cell-group inset>
                <van-cell
                  v-for="(item, index) in group.members"
                  :key="item.id"
                  clickable
                  @click="toggle(groupIndex, index, item)"
                >
                  <template #icon>
                    <van-checkbox
                      checked-color="#4765DD"
                      :name="item"
                      :disabled="item.disabled"
                      :ref="el => setCheckboxRef(groupIndex, index, el)"
                      @click.stop
                    />
                  </template>
                  <template #title>
                    <div class="cell-item">
                      <van-image class="img-icon" round :src="item.avatar" />
                      <div>{{ item.nickname }}</div>
                    </div>
                  </template>
                </van-cell>
              </van-cell-group>
            </van-checkbox-group>
          </template>
        </van-index-bar>
  
        <!-- 选择结果展示 -->
        <div class="footer-box">
          <div class="avatar-list">
            <van-image
              v-for="item in checked"
              :key="item.id"
              class="img-icon"
              round
              :src="item.avatar"
            />
          </div>
          <div class="btn" :class="checked.length == 0 ? '' : 'active-btn'" @click="submit">
            已选择({{ checked.length }})
          </div>
        </div>
      </template>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUpdate } from 'vue';
  import { groupList,groupDisjoin } from '@/api/path/im.api';
  import { useWalletStore } from '@/stores/modules/walletStore';
  import { useWebSocketStore } from "@/stores/modules/webSocketStore.js";
  import { MSG_TYPE,REMOVE_GROUP } from "@/common/constant/msgType";
  import { getFirstLetter } from '@/utils/utils';
  import { showToast } from "vant";
  import { useSystemStore } from "@/stores/modules/systemStore";
  
  const IM_PATH = import.meta.env.VITE_IM_PATH_FIlE;
  const walletStore = useWalletStore();
  const wsStore = useWebSocketStore();
  const router = useRouter();
  const systemStore = useSystemStore();
  
  const checked = ref([]);
  const memberGroups = ref([]);
  const loading = ref(false);
  const userName = ref('')
  
  const getUserList = async () => {
    loading.value = true;
    try {
      const res = await groupList(wsStore.toUserInfo.uuid);

      const groupedMap = {};
      res.data?.forEach(user => {
        const name = user.nickname || '';
        user.avatar = user.avatar ? IM_PATH + user.avatar : user.avatar;

        // 判断是否群主（guserId === userId）
        if (user.guserId === user.userId) {
          user.disabled = true; // 群主不可选
          userName.value = user.nickname
        }
        const firstLetter = getFirstLetter(name);
        if (!groupedMap[firstLetter]) groupedMap[firstLetter] = [];
        groupedMap[firstLetter].push({ ...user });
      });

      memberGroups.value = Object.keys(groupedMap)
        .sort()
        .map(letter => ({
          index: letter,
          members: groupedMap[letter]
        }));
    } finally {
      loading.value = false;
    }
  };

  
  // checkbox refs 用于点击切换
  const checkboxRefs = ref([]);
  onBeforeUpdate(() => {
    checkboxRefs.value = [];
  });
  
  const setCheckboxRef = (groupIndex, index, el) => {
    if (!checkboxRefs.value[groupIndex]) checkboxRefs.value[groupIndex] = [];
    checkboxRefs.value[groupIndex][index] = el;
  };
  
  const toggle = (groupIndex, index, item) => {
    if (item.disabled) return;
    const checkbox = checkboxRefs.value[`${groupIndex}-${memberIndex}`];
    if (checkbox) checkbox.toggle();
  };
  const submit = async () => {
    if(checked.value.length == 0) return;
    const uuids = checked.value.map(item => item.uuid);//移出成员需要uuid
    const uname = checked.value.map(item => item.nickname).join('、');
    const utext = walletStore.account == wsStore.uuid?'管理员':userName.value
     // 移出成员
    try {
      const res = await groupDisjoin(uuids,wsStore.toUserInfo.uuid,walletStore.account);
      if(res.code == 200){
          showToast('移出成功')
          const message = {
            content: JSON.stringify({
              content: `${utext}将${uname}移出了群聊`,
              users: uuids,
            }),
            contentType: MSG_TYPE.TEXT,
            messageType:REMOVE_GROUP
          };
          wsStore.sendMessage(message);
          // await wsStore.fetchGroupMembers(true)
          // systemStore.needRefreshIm = true;
          // router.push('im')
          // router.push({
          //   path: 'detail',
          //   query:{ status:wsStore.toUserInfo.type == 'user'?1:2 }
          // }) // 1:单聊  2：群聊
          router.push({
            path: 'chat',
            query:{ uuid:wsStore.toUserInfo.uuid }
          })
          
      }else{
          showToast('移出失败')
      }
    } catch (error) {
      showToast('移出失败')
    }
  }
  onMounted(() => {
    getUserList();
  });
  </script>
  
<style lang="less" scoped>
.load-box{
  text-align: center !important;
  margin-top: 50px !important;
}
.container{
    display: flex;
    flex-direction: column;
    height: 100%;
}
.list{
    flex: 1;
    overflow: auto;
    :deep(.van-cell-group--inset){
        border-radius:12px !important;
    }
    :deep(.van-cell){
        padding: 12px 16px !important;
    }
    :deep(.van-cell:after){
      left: 90px;
    }
    :deep(.van-index-anchor--sticky){
        background: #F7F8FA !important;
        color: #4765DD !important;
    }
    :deep(.van-index-bar__index){
        font-weight: 400 !important;
        font-size: 10px !important;
        color: #1D2129 !important;
        margin-bottom: 8px !important;
    }
    :deep(.van-index-bar__index--active){
        color: #4765DD !important;
    }
    .cell-item{
        display: flex;
        align-items: center;
        margin-left: 12px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 15px;
        color: #000000;
        .img-icon{
            width: 32px;
            height: 32px;
            flex-shrink: 0;
            margin-right: 12px;
        }
        .joined-tag {
          margin-left: 8px;
          font-size: 12px;
          color: #999;
        }
    }
}
.list::-webkit-scrollbar{
    width: 0;
}
.footer-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
    height: 54px;
    background: #ffffff;
    padding: 0 16px;
    box-sizing: border-box;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 15px;
    color: #8d8d8d;

    .avatar-list {
        display: flex;
        overflow-x: auto;
        flex: 1;
        .img-icon {
            width: 32px;
            height: 32px;
            flex-shrink: 0;
            margin-right: 4px;
        }
    }
    .avatar-list::-webkit-scrollbar{
        height: 0;
    }
    .btn{
      margin-left: 16px;
      height: 25px;
      line-height: 25px;
      padding: 0 6px;
      background: #F2F2F2;
      border-radius: 4px;
      box-sizing: border-box;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #8D8D8D;
    }
    .active-btn{
      background: #4765DD;
      color: #FFFFFF;
    }
}
</style>