<template>
    <div class="container">
        <div class="box-item">
            <div class="item-title" v-if="status == 2">
                <div class="text-lf">群聊成员</div>
                <div class="text-ri" @click="checkMember">
                    查看{{ groupMembersNum.length }}名群成员<svg-icon
                        class="item-icon"
                        name="right1"
                    />
                </div>
            </div>
            <div class="member-box">
                <!-- 单人 -->
                <div class="member-li" @click="goToPage" v-if="status == 1">
                    <van-image
                        class="member-img"
                        round
                        :src="IM_PATH + wsStore.toUserInfo.avatar"
                    />
                    <div>{{ wsStore.toUserInfo.nickname }}</div>
                </div>
                <!-- 群聊 -->
                <template v-if="status == 2">
                    <div
                        class="member-li"
                        @click="goToPage(item.uuid)"
                        v-for="(item, i) in groupMembers"
                        :key="i"
                    >
                        <van-image
                            class="member-img"
                            round
                            :src="IM_PATH + item.avatar"
                        />
                        <div>{{ item.nickname }}</div>
                    </div>
                </template>
                <div class="member-li" @click="addMember" v-if="status == 2">
                    <div class="add">
                        <van-icon class="add-icon" name="plus" />
                    </div>
                    <div>邀请</div>
                </div>
                <div
                    class="member-li"
                    @click="deleteMember"
                    v-if="status == 2 && isAdmin"
                >
                    <div class="add">
                        <van-icon class="add-icon" name="minus" />
                    </div>
                    <div>移出</div>
                </div>
            </div>
        </div>
        <van-cell-group class="user-bar-list" v-if="status == 2">
            <van-cell
                title="群聊名称"
                :value="information.name"
                is-link
                @click="changeUpdateName(1)"
            ></van-cell>
            <van-cell title="群二维码" is-link @click="goQrcode">
                <template #value>
                    <svg-icon class="qrcode-icon" name="qrcode" />
                </template>
            </van-cell>
            <van-cell
                title="群公告"
                :label="information.notice"
                @click="showNotice = true"
                is-link
            ></van-cell>
            <van-cell
                title="我在群里的昵称"
                class="user-bar-list-last"
                @click="changeUpdateName(2)"
                :value="information.nickname"
                is-link
            ></van-cell>
        </van-cell-group>
        <van-cell-group class="user-bar-list">
            <van-cell center title="消息免打扰">
                <template #right-icon>
                    <van-switch v-model="disturb" active-color="#4765DD" inactive-color="#D9D9D9" @click="changeDisturb"/>
                </template>
            </van-cell>
            <van-cell center title="置顶聊天" class="user-bar-list-last">
                <template #right-icon>
                    <van-switch v-model="topStory" active-color="#4765DD " inactive-color="#D9D9D9 " @click="changeStory"/>
                </template>
            </van-cell>
        </van-cell-group>
        <van-cell-group class="user-bar-list">
            <van-cell class="user-bar-list-last" title="查看聊天记录" is-link @click="goChatDetail"></van-cell>
        </van-cell-group>
        <div class="exit" @click="showExit = true" v-if="status == 2">
            {{ isAdmin ? '解散' : '退出' }}群聊
        </div>
        <!-- 修改信息弹框 -->
        <van-popup
            v-model:show="showUpdateName"
            :style="{ borderRadius: '25px' }"
        >
            <div class="pop-content-password">
                <div class="pop-title-password">
                    {{ type == 1 ? '修改群聊名称' : '修改昵称' }}
                </div>
                <van-field
                    v-model="newName"
                    class="pop-input"
                    placeholder="请输入名称"
                />
                <div class="pop-btn-password">
                    <van-button
                        type="default"
                        class="btn-password cancel"
                        @click="cancel"
                        >{{ $t('wallet.Cancel') }}</van-button
                    >
                    <van-button
                        type="default"
                        class="btn-password confirm"
                        @click="popConfirm"
                        :disabled="isDisabledConfirm"
                        >{{ $t('wallet.Sure') }}</van-button
                    >
                </div>
            </div>
        </van-popup>
        <!-- 公告弹框 -->
        <van-popup
            v-model:show="showNotice"
            position="bottom"
            round
            style="height: 280px"
        >
            <div class="pop-content">
                <div class="pop-title">
                    <div @click="showNotice = false">取消</div>
                    <div v-if="isAdmin" class="save" @click="changeUpdateNotice">保存</div>
                </div>
                <van-field
                    class="textarea-item"
                    v-model="newNotice"
                    rows="2"
                    autosize
                    type="textarea"
                    placeholder="请输入公告内容..."
                    show-word-limit :disabled="!isAdmin"
                />
            </div>
        </van-popup>
        <!-- 退出群聊弹框 -->
        <van-popup v-model:show="showExit" :style="{ borderRadius: '25px' }">
            <div class="pop-content-password">
                <div class="pop-title-password">
                    确定要{{ isAdmin ? '解散' : '退出' }}群聊吗？
                </div>
                <div class="pop-btn-password" style="margin-top: 50px">
                    <van-button
                        type="default"
                        class="btn-password cancel"
                        @click="showExit = false"
                        >{{ $t('wallet.Cancel') }}</van-button
                    >
                    <van-button
                        type="default"
                        class="btn-password confirm"
                        @click="popExit"
                        >{{ $t('wallet.Sure') }}</van-button
                    >
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup>
import { useWebSocketStore } from '@/stores/modules/webSocketStore.js';
import { useWalletStore } from '@/stores/modules/walletStore';
import {
    groupList,
    selectGroupName,
    selectEditnickname,
    quitGroup,
    dissolveGroup,
    setMessageDisturb,
    stickChat
} from '@/api/path/im.api';
import { useRouter, useRoute } from 'vue-router';
import { reactive } from 'vue';
import { showNotify, showToast } from 'vant';
import { useSystemStore } from '@/stores/modules/systemStore';
import * as MsgType from '@/common/constant/msgType';
const router = useRouter();
const route = useRoute();
const status = route.query.status;
const wsStore = useWebSocketStore();
const IM_PATH = import.meta.env.VITE_IM_PATH_FIlE;
const walletStore = useWalletStore();
const systemStore = useSystemStore();

const groupMembers = ref([]); //显示部分成员
const groupMembersNum = ref([]); //全部成员
const information = reactive({
    name: wsStore.toUserInfo.sessionName || '群聊',
    notice: wsStore.toUserInfo.notice,
    nickname: wsStore.toUserInfo.nickname
});
const type = ref(1); //1:修改群聊名称  2：修改我的群昵称
const disturb = ref(wsStore.toUserInfo?.slience === 1 || wsStore.toUserInfo?.slience === true)
const topStory = ref(wsStore.toUserInfo?.stick === 1 || wsStore.toUserInfo?.stick === true);
const showUpdateName = ref(false);
const isDisabledConfirm = ref(false);
const showNotice = ref(false);
const showExit = ref(false);
const newName = ref('');
const newNotice = ref(wsStore.toUserInfo.notice);
// 获取群成员信息
const fetchGroupMembers = async () => {
    try {
        const res = await groupList(wsStore.toUserInfo.uuid);
        groupMembers.value = (res.data || []).slice(0, 8);
        groupMembersNum.value = res.data || [];
        // const dataInfo = groupMembersNum.value.find(
        //     m => m.uuid === walletStore.account
        // );
        // if (dataInfo) {
        //     information.nickname = dataInfo.nickname || ''; // 群个人昵称
        // }
    } catch (e) {
        console.error('获取群成员失败', e);
    }
};
const isAdmin = computed(() => {
    const self = groupMembersNum.value.find(
        m => m.uuid === walletStore.account
    );
    return self?.userId === self?.guserId;
});
const changeUpdateName = val => {
    type.value = val;
    newName.value = val == 1 ? information.name : information.nickname;
    showUpdateName.value = true;
};
// 群聊名称取消
const cancel = () => {
    showUpdateName.value = false;
};
// 群聊名称确定
const popConfirm = () => {
    if (!newName.value) {
        showNotify({ type: 'warning', message: '请输入名称' });
        return;
    }
    isDisabledConfirm.value = true;
    setTimeout(() => {
        isDisabledConfirm.value = false;
        showUpdateName.value = false;
        if (type.value == 1) {
            information.name = newName.value;
            wsStore.toUserInfo.sessionName = newName.value;
            // 修改群聊名称接口
            funSelectGroupName({
                name: newName.value,
                uuid: wsStore.toUserInfo.uuid
            });
        } else {
            // 修改群个人昵称接口
            funSelectEditnickname({
                nickname: newName.value,
                groupId: wsStore.toUserInfo.groupId
            });
            information.nickname = newName.value;
            wsStore.toUserInfo.nickname = newName.value;;
            // 同步更新 groupMembers 和 groupMembersNum（因为你两个地方用到）
            const selfData = groupMembersNum.value.find(
                m => m.uuid === walletStore.account
            );
            if (selfData) {
                selfData.nickname = newName.value;
            }

            // 如果 groupMembers 是前 8 个成员的子集，也要更新
            const selfInMembers = groupMembers.value.find(
                m => m.uuid === walletStore.account
            );
            if (selfInMembers) {
                selfInMembers.nickname = newName.value;
            }
        }
    }, 1000);
};
// 修改群信息接口
const funSelectGroupName = async params => {
    try {
        const res = await selectGroupName(wsStore.uuid, params);
        if (res.code == 200) {
            showToast('修改成功');
            // 通知群公告
            wsStore.sendMessage({
                content: JSON.stringify(params),
                contentType: MsgType.MSG_TYPE.TEXT,
                messageType: MsgType.MESSAGE_NOTICE_GROUP,
            });
        } else {
            showToast('修改失败');
        }
    } catch (e) {
        showToast('修改失败');
    }
};
// 修改群个人昵称接口
const funSelectEditnickname = async params => {
    try {
        const res = await selectEditnickname(wsStore.uuid, params);
        if (res.code == 200) {
            showToast('修改成功');
            wsStore.sendMessage({
                content: JSON.stringify({
                    uuid:wsStore.uuid,
                    name:params.nickname
                }),
                contentType: MsgType.MSG_TYPE.TEXT,
                messageType: MsgType.MESSAGE_NICKNAME_GROUP,
            });

        } else {
            showToast('修改失败');
        }
    } catch (error) {
        showToast('修改失败');
    }
};
// 群公告
const changeUpdateNotice = () => {
    if (!newNotice.value) {
        showNotify({ type: 'warning', message: '请输入公告内容' });
        return;
    }
    // 修改群公告
    funSelectGroupName({
        uuid: wsStore.toUserInfo.uuid,
        notice: newNotice.value
    });
    setTimeout(() => {
        showNotice.value = false;
        information.notice = newNotice.value;
        wsStore.toUserInfo.notice = newNotice.value;
    }, 500);
};
//退出或者解散
const popExit = async () => {
    const action = isAdmin.value ? dissolveGroup : quitGroup;
    const successMsg = isAdmin.value ? '解散成功' : '退出成功';
    const failMsg = isAdmin.value ? '解散失败' : '退出失败';
    let message = '';

    if (isAdmin.value) {
        message = {
            content: `${information.nickname}解散了群聊`,
            contentType: MsgType.MSG_TYPE.TEXT,
            messageType: MsgType.DELETE_GROUP
        };
        wsStore.sendMessage(message);
    }
    try {
        const res = await action(walletStore.account, wsStore.toUserInfo.groupId);
        if (res.code === 200) {
            showToast(successMsg);
            if (!isAdmin.value) {
                message = {
                    content: JSON.stringify({
                        content: `${information.nickname}退出了群聊`,
                        users: [walletStore.account]
                    }),
                    contentType: MsgType.MSG_TYPE.TEXT,
                    messageType: MsgType.EXIT_GROUP
                };
                wsStore.sendMessage(message);
            }
            // systemStore.needRefreshIm = true;
            // await wsStore.fetchGroupMembers(true)
            router.push('im');
        } else {
            showToast(failMsg);
        }
    } catch (error) {
        showToast(failMsg);
    }
};
// 消息免打扰
const changeDisturb = async () => {
    try {
        const res = await setMessageDisturb(wsStore.toUserInfo.uuid,{
            friendUuid:walletStore.account,
            messageType:wsStore.toUserInfo.type == 'user'?1:2
        });
        if(res.code == 200){
            showToast('设置成功');
            wsStore.toUserInfo.slience = res.data;
            wsStore.updateSessionNewMessage({slience: res.data}, wsStore.toUserInfo.uuid);
        }else{
            showToast('设置失败');
        }
    } catch (error) {
        showToast('设置失败');
    }
}
// 置顶聊天
const changeStory = async () => {
    try {
        const res = await stickChat({
            friendUuid:walletStore.account,
            uuid:wsStore.toUserInfo.uuid,
            messageType:wsStore.toUserInfo.type == 'user'?1:2
        });
        if(res.code == 200){
            showToast('设置成功');
            wsStore.toUserInfo.stick = res.data;
            wsStore.updateSessionNewMessage({stick: res.data}, wsStore.toUserInfo.uuid);
        }else{
            showToast('设置失败');
        }
    } catch (error) {
        showToast('设置失败');
    }
}


// 跳转群二维码页面
const goQrcode = () => {
    router.push('qrcode');
};
// 跳转聊天记录
const goChatDetail = () => {
    router.push('chatLog');
};
// 跳转添加成员页面
const addMember = () => {
    router.push({
        path: 'addMember',
        query: {
            arr: JSON.stringify(groupMembersNum.value)
        }
    });
};
// 跳转移出成员页面
const deleteMember = () => {
    router.push({
        path: 'deleteMember'
    });
};
// 跳转查看成员页面
const checkMember = () => {
    router.push('checkMember');
};
// 跳转成员基本信息页面
const goToPage = uuid => {
    if(uuid == walletStore.account) return;
    router.push({
        path: 'personal',
        query: {
            uuid: route.query.status == 2 ? uuid : wsStore.toUserInfo.uuid,
            type: 2
        }
    });
};
// 页面生命周期
onMounted(() => {
    if (route.query.status == 2) {
        fetchGroupMembers();
    }
});
</script>

<style lang="less" scoped>
.container {
    margin: 16px;
    .box-item {
        background-color: #fff;
        border-radius: 12px;
        padding: 12px 16px 0;
        margin-bottom: 16px;
        .item-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-family:
                PingFang SC,
                PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #8d8d8d;
            .text-lf {
                font-weight: 500;
                font-size: 15px;
                color: #000000;
            }
            .text-ri {
                display: flex;
                align-items: center;
                .item-icon {
                    width: 20px;
                    height: 20px;
                    color: #969799;
                }
            }
        }
        .member-box {
            margin-top: 12px;
            flex-wrap: wrap;
            display: flex;
            .member-li {
                width: calc(100% / 5);
                display: flex;
                flex-direction: column;
                font-family:
                    PingFang SC,
                    PingFang SC;
                font-weight: 400;
                font-size: 10px;
                color: #000000;
                padding-bottom: 17px;
                align-items: center;
                .member-img {
                    width: 44px;
                    height: 44px;
                    margin-bottom: 4px;
                    flex-shrink: 0;
                }
                .add {
                    width: 44px;
                    height: 44px;
                    margin-bottom: 4px;
                    border-radius: 22px;
                    background: #f2f2f2;
                    position: relative;
                    .add-icon {
                        font-size: 20px;
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        color: #8d8d8d;
                        transform: translate(-50%, -50%);
                    }
                }
            }
        }
    }
    .user-bar-list {
        background-color: #fff;
        border-radius: 12px;
        overflow: hidden;
        margin-bottom: 16px;
        .van-cell {
            // height: 44px;
            background: @bg-color1;
            border-bottom: 1px solid @bg-color1;
            font-size: 15px;
            &::after {
                border-bottom: 1px solid #f2f2f2;
            }
        }
        :deep(.van-cell__title) {
            font-family:
                PingFang SC,
                PingFang SC;
            font-weight: 500;
            font-size: 15px;
            color: #000000;
        }
        :deep(.van-cell__value) {
            font-family:
                PingFang SC,
                PingFang SC;
            font-weight: 400;
            font-size: 15px;
            color: #8d8d8d;
        }
        :deep(.van-cell__label) {
            font-family:
                PingFang SC,
                PingFang SC;
            font-weight: 400;
            font-size: 15px;
            color: #8d8d8d;
        }
        .user-bar-list-last::after {
            border-bottom: 0;
        }
        .qrcode-icon {
            width: 24px;
            height: 24px;
        }
    }
    .exit {
        height: 44px;
        background-color: #fff;
        border-radius: 12px;
        font-family:
            PingFang SC,
            PingFang SC;
        font-weight: 500;
        font-size: 15px;
        color: #ff0000;
        text-align: center;
        line-height: 44px;
    }
    .pop-content-password {
        padding: 27px 35px 25px 34px;
        .pop-title-password {
            font-family:
                PingFang SC,
                PingFang SC;
            font-weight: 500;
            font-size: 17px;
            color: #000000;
            text-align: center;
        }
        .pop-input {
            background: #f2f2f2;
            border-radius: 8px;
            height: 40px;
            margin: 21px 0 31px;
        }
        .pop-btn-password {
            display: flex;
            justify-content: center;
            .btn-password {
                width: 83px;
                height: 29px;
                line-height: 29px;
                padding: 5px 0 !important;
                border-radius: 6px;
                font-family:
                    PingFang SC,
                    PingFang SC;
                font-weight: 400;
                font-size: 15px;
                box-sizing: border-box;
            }
            .cancel {
                margin-right: 17px !important;
                border: 1px solid #d8d8d8;
                color: #000 !important;
            }
            .confirm {
                background: @theme-color1;
                color: #fff;
                font-weight: 500;
                border: none !important;
            }
        }
    }
    :deep(.van-popup--center) {
        margin: 0 40px !important;
        width: auto !important;
    }
    .pop-content {
        background: #f7f8fa;
        height: 280px;
        .pop-title {
            background: #fff;
            padding: 0 20px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-sizing: border-box;
            font-family:
                PingFang SC,
                PingFang SC;
            font-weight: 400;
            font-size: 15px;
            color: #4f4f4f;
            .save {
                font-weight: 500;
                color: #4765dd;
            }
        }
        .textarea-item {
            background: #f7f8fa !important;
            :deep(.van-cell__value) {
                font-weight: 400 !important;
                font-size: 15px !important;
            }
        }
        .textarea-item :deep(textarea::placeholder) {
            font-family:
                PingFang SC,
                PingFang SC;
            font-weight: 400;
            font-size: 15px;
            color: #8d8d8d;
        }
    }
}
</style>
