<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"
                                        :ref="el => setCheckboxRef(groupIndex, index, el)"
                                        :disabled="joinedIds.has(item.uuid)"
                                        @click.stop
                                    />
                                </template>
                                <template #title>
                                    <div class="cell-item">
                                        <van-image class="img-icon" round :src="item.avatar" />
                                        <div>{{ item.nickname }}</div>
                                        <span v-if="joinedIds.has(item.uuid)" class="joined-tag">已在群</span>
                                    </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 { userFriendList,createSetGroup,groupJoin } from "@/api/path/im.api";
import {getFirstLetter} from "@/utils/utils";
import { useWalletStore } from "@/stores/modules/walletStore";
import { useWebSocketStore } from "@/stores/modules/webSocketStore.js";
import { showToast } from "vant";
import * as MsgType from "@/common/constant/msgType";
import { useSystemStore } from "@/stores/modules/systemStore";
const IM_PATH = import.meta.env.VITE_IM_PATH_FIlE;
const router = useRouter();
const route = useRoute();
const walletStore = useWalletStore();
const wsStore = useWebSocketStore();
const systemStore = useSystemStore();


const checked = ref([]);
const memberGroups = ref([]);
const loading = ref(false);

// 已加入群的成员数组
const dataArr = route.query.arr ? JSON.parse(route.query.arr) : []; 
// 转成 Set，快速判断
const joinedIds = new Set(dataArr.map(m => m.uuid));

const getuserList = async () => {
    loading.value = true;
    try {
        const res = await userFriendList({ uuid: walletStore.account });
        const groupedMap = {};

        res.data?.forEach(user => {
            const name = user.nickname || '';
            user.avatar = user.avatar ? IM_PATH + user.avatar : user.avatar
            const firstLetter = getFirstLetter(name); // 获取首字母

            if (!groupedMap[firstLetter]) {
            groupedMap[firstLetter] = [];
            }

            groupedMap[firstLetter].push({...user});
        });

        // 转为数组并按 index 排序
        const groupedList = Object.keys(groupedMap)
            .sort()
            .map(letter => ({
            index: letter,
            members: groupedMap[letter]
            }));

        memberGroups.value = groupedList;
    } finally {
        loading.value = false;
    }
};

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 (joinedIds.has(item.uuid)) {
    return; // 已在群的不触发切换
  }
  checkboxRefs.value[groupIndex]?.[index]?.toggle();
};

const submit = async () => {
    if(checked.value.length == 0) return;
    const ids = checked.value.map(item => item.id);//创建群需要id
    const uname = checked.value.map(item => item.nickname).join('、');
    const uuids = checked.value.map(item => item.uuid);//添加成员需要uuid
    if(route.name == 'addMember'){
        // 邀请添加成员加入群组
        try {
            const res = await groupJoin(uuids,wsStore.toUserInfo.uuid);
            if(res.code == 200){
                showToast('加入成功');
                const message = {
                    content: `${uname}加入了群聊`,
                    contentType: MsgType.MSG_TYPE.TEXT,
                    messageType: MsgType.INVITATION_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('加入失败')
        }
    }else{
        // 创建群
        try {
            const res = await createSetGroup({
                uuid:walletStore.account,
                userIds:ids
            });
            wsStore.toUserInfo = res.data;
            const message = {
                content: `${uname}加入了群聊`,
                contentType: MsgType.MSG_TYPE.TEXT,
                messageType: MsgType.CREATE_GROUP
            };
            wsStore.sendMessage(message);
            if(res.code == 200){
                showToast('创建成功')
                // systemStore.needRefreshIm = true;
                router.push('im')
            }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>
