<template>
    <Navbar :title="navBarTitle" :showBackIcon="false" />
    <div class="mx-5">
        <div
            v-for="(item, index) in cardList"
            :key="item.masterId"
            v-touch-hold:300="handleTouchHoldItem(index)"
            @click.capture="handleClickItem(index, item)"
        >
            <div @click.capture="stop">
                <van-popover @select="onSelect" :actions="actions" v-model:show="showList[index]">
                    <template #reference>
                        <ChatListItem
                            :unReadMsgNum="item.unreadMsgCount"
                            :id="item.targetId"
                            :displayName="item.displayName"
                            :latest_msg_content="item.content"
                            :userType="userType"
                            :datetime="item.datetime"
                            :isRobootCard="item.isRobootCard"
                            :isDeleted="item.isDeleted"
                        ></ChatListItem>
                    </template>
                </van-popover>
            </div>
        </div>
    </div>
    <div
        v-if="!cardListLoading && isChatListEmpty"
        class="empty text-center fixed w-full top-1/2 transform -translate-y-1/2 -mt-6"
    >
        <img src="@/assets/img/empty.png" class="mb-5" />
        <div class="no-chat mb-2.5">暂无聊天</div>
        <div v-if="userType === eRole.user" class="tip">咨询客户经理后，可以在这里快捷查看消息哦！</div>
        <div v-else-if="userType === eRole.staff" class="tip">客户咨询后，可以在这里快捷查看消息哦！</div>
    </div>
</template>
<script lang="ts" setup>
import Navbar from "@/components/NavBar/index.vue"
import ChatListItem from "@/components/ChatList/ChatListItem.vue"
import { computed, onMounted, ref, watch } from "@vue/runtime-core";
import { getFromId } from "@/store/appCallerStore";
import ChatListCardDB from "@/db/ChatListCardDB";
import { iChatListCard } from "@/db";
import { chatCardTimeStamp } from "@/store/chatCardStore";
import { getUserMsg } from "@/utils/userMsg";
import { eRole } from "@/types/roleType";
import ChatMessageDB from "@/db/ChatMessageDB";
import router from "@/router";
import { getDisplayNames } from "@/utils/displayName";


const cardList = ref<(iChatListCard & { displayName?: string })[]>([]);
const showList = ref<boolean[]>([]);
const selectedIndex = ref<number>()
const cardListLoading = ref(false);

const renderList = async () => {
    cardListLoading.value = true;
    const list = await ChatListCardDB.getInstance().getCardList(getFromId() as string)

    cardList.value = list;

    const reqlist = list.map(i => {
        if (i.isRobootCard) {
            return {
                outletId: Number(i.targetId),
            }
        } else {
            return {
                address: i.targetId,
            }
        }
    })

    const displayNames = await getDisplayNames(reqlist)

    cardList.value = list.map((item, index) => {
        return {
            ...item,
            displayName: displayNames[index],
            isDeleted: !!displayNames[index]?.match(/\(已停止营业\)$/)
        }
    })
    cardListLoading.value = false;
}

onMounted(async () => {
    await renderList();
})

watch(chatCardTimeStamp, async () => {
    await renderList();
})

const navBarTitle = computed(() => {
    if (getUserMsg()?.role === eRole.user) {
        return "我的客户经理"
    } else if (getUserMsg()?.role === eRole.staff) {
        return "我的客户"
    }
})

const userType = computed(() => {
    return getUserMsg()?.role
})

const actions = [
    {
        text: '删除对话', callback: async (item: iChatListCard) => {
            ChatMessageDB.getInstance().deleteMsgGroup(item.masterId, item.targetId);
            ChatListCardDB.getInstance().deleteCard(item.masterId, item.targetId);
            await renderList();
        }
    },
];

function stop(e: Event) {
    e.stopPropagation();
}

const isChatListEmpty = computed(() => {
    return cardList.value.length === 0
})

function handleTouchHoldItem(index: number) {
    return () => {
        showList.value[index] = true;
        selectedIndex.value = index;
    }
}

function handleClickItem(index: number, item: iChatListCard) {
    showList.value[index] = false;

    router.push({
        name: 'Chat',
        query: {
            targetId: item.targetId,
            outlet: item.isRobootCard ? 'true' : undefined
        }
    })
}

const onSelect = (action: typeof actions[0]) => {
    selectedIndex.value !== undefined && action && action.callback && action.callback(cardList.value[selectedIndex.value]);
}

</script>
<style lang="less" scoped>
/deep/ .van-popover__wrapper {
    width: 100%;
}
.empty {
    .no-chat {
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #474747;
    }
    .tip {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #858585;
    }
}
</style>