<template>
    <view class="container">
        <!-- 自定义tabbar -->
        <CustomTabBar :currentPage="2" />
        
        <!-- 微信授权登录弹窗 -->
        <WxAuthLogin ref="wxAuthLoginRef" @success="handleLoginSuccess"></WxAuthLogin>
        <!-- 抽屉遮罩层 -->
        <view v-if="isDrawerOpen" class="overlay" @click="toggleDrawer"></view>

        <!-- 抽屉窗口 -->
        <view class="drawer" :class="{ open: isDrawerOpen }">
            <view class="drawer-content">
                <view class="drawer-title">AI+</view>
                <view class="drawer-input-content">
                    <input
                        class="drawer-input"
                        type="text"
                        v-model="searchText"
                        placeholder-class="input-placeholder"
                        placeholder="请输入搜索历史对话"
                    />
                    <uni-icons class="input-search" type="search" size="20"></uni-icons>
                </view>
                <scroll-view scroll-y :show-scrollbar="false" class="chat-scroll">
                    <view
                        class="drawer-rows"
                        v-for="(item, index) in filteredList"
                        :key="item.id"
                    >
                        <view
                            v-if="!item.isTitle"
                            class="drawer-row-content"
                        >
                            <view
                                class="drawer-row-list"
                                :class="{ 'drawer-row-active': item.sessionId === chatSessionID }"
                                @click="changeDialogue(item)"
                            >
                                {{ item.title }}
                            </view>
                            <view class="drawer-row-delete" @click.stop="deleteSession(item)">
                                <uni-icons type="trash" size="24" color="#FF4444"></uni-icons>
                            </view>
                        </view>
                        <view class="drawer-row-title" v-else>
                            {{ item.title }}
                        </view>
                    </view>
                </scroll-view>
                <view class="drawer-user">
                    <image class="drawer-user-img" v-if="userInfo.age === '0'" src="/static/icon/boy.png"></image>
                    <image class="drawer-user-img" v-else src="/static/icon/girl.png"></image>
                    <text>{{ userInfo.name || '暂无用户名' }}</text>
                    <!--      <image
                        class="drawer-user-setting button-click"
                        src="/static/icon/setting.png"
                        @click="updateSetting"
                    ></image> -->
                </view>
            </view>
        </view>

        <!-- 主要内容，挤压效果 -->
        <view class="main-content" :class="{ shift: isDrawerOpen }">
            <!-- header -->
            <header class="head">
                <view class="main-header">
                    <image src="/static/icon/Hamburger-button.png" @click="toggleDrawer"></image>
                    <!-- <view class="title">{{ config.appInfo.areaName }}岗位推荐</view> -->
                    <!-- <view class="title">{{ config.appInfo.areaName }}岗位推荐</view> -->
                    <image src="/static/icon/Comment-one.png" @click="addNewDialogue"></image>
                </view>
            </header>
            <view class="chatmain-warpper">
                <ai-paging ref="paging"></ai-paging>
            </view>
            <!-- 自定义tabbar -->
            <view class="chatmain-footer" v-show="!isDrawerOpen">
                <!-- 统一使用系统tabBar -->
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, inject, nextTick, computed, onMounted, onUnmounted } from 'vue';
const { $api, navTo, insertSortData, config } = inject('globalFunction');
import { onLoad, onShow, onHide } from '@dcloudio/uni-app';
import useChatGroupDBStore from '@/stores/userChatGroupStore';
import useUserStore from '@/stores/useUserStore';
import { tabbarManager } from '@/utils/tabbarManager';
import aiPaging from './components/ai-paging.vue';
import { storeToRefs } from 'pinia';
import WxAuthLogin from '@/components/WxAuthLogin/WxAuthLogin.vue';
const { isTyping, tabeList, chatSessionID } = storeToRefs(useChatGroupDBStore());
const { userInfo } = storeToRefs(useUserStore());
const isDrawerOpen = ref(false);
const scrollIntoView = ref(false);

const searchText = ref('');
const paging = ref(null);
const wxAuthLoginRef = ref(null);

// 实时过滤
const filteredList = computed(() => {
    // console.log(tabeList.value);
    if (!searchText.value) return tabeList.value;
    const list = tabeList.value.filter((item) => !item.isTitle && item.title.includes(searchText.value));
    const [result, lastData] = $api.insertSortData(list);
    return result;
});

onLoad(() => {
    // useChatGroupDBStore().getHistory();
});

onShow(() => {
    nextTick(() => {
        paging.value?.closeFile();
    });
    // 更新自定义tabbar选中状态
    tabbarManager.updateSelected(2);
});

onMounted(() => {
    // 监听退出登录事件，显示微信登录弹窗
    uni.$on('showLoginModal', () => {
        wxAuthLoginRef.value?.open();
    });
});

onUnmounted(() => {
    uni.$off('showLoginModal');
});

// 登录成功回调
const handleLoginSuccess = () => {
    console.log('登录成功');
    // 可以在这里添加登录成功后的处理逻辑
};

onHide(() => {
    paging.value?.handleTouchCancel();
    if (isDrawerOpen.value) {
        isDrawerOpen.value = false;
        // uni.showTabBar();
    }
});

const toggleDrawer = () => {
    isDrawerOpen.value = !isDrawerOpen.value;
    if (isDrawerOpen.value) {
        // uni.hideTabBar();
    } else {
        // uni.showTabBar();
    }
};

const addNewDialogue = () => {
    $api.msg('新对话');
    paging.value?.changeQueries();
    useChatGroupDBStore().addNewDialogue();
};

const changeDialogue = (item) => {
    if (item.sessionId) {
        paging.value?.closeGuess();
        useChatGroupDBStore().changeDialogue(item);
        toggleDrawer();
        nextTick(() => {
            paging.value?.scrollToBottom();
        });
    }
};

const deleteSession = (item) => {
    if (item.sessionId) {
        uni.showModal({
            content: '确认删除该会话？',
            success: async (res) => {
                if (res.confirm) {
                    await useChatGroupDBStore().deleteSession(item.sessionId);
                    $api.msg('会话删除成功');
                }
            }
        });
    }
};

function updateSetting() {
    $api.msg('该功能正在开发中，敬请期待后续更新！');
}
</script>

<style lang="stylus" scoped>
header-height = 132rpx
footer-height = 147rpx

/* 页面容器 */
.container {
    position: fixed;
    z-index: 1;
    width: 100vw;
    height: calc(100% - var(--window-bottom));
    overflow: hidden;
}

/* 遮罩层 */
.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
    z-index: 999;
}

/* 抽屉窗口 */
.drawer {
    position: fixed;
    top: 0;
    left: 0; /* 如果要右侧弹出改为 right: 0; */
    width: 785rpx;
    height: 100%;
    background: #e7e7e6;
    transform: translateX(-100%);
    transition: transform 0.3s ease-in-out;
    z-index: 1000;
}

/* 抽屉展开 */
.drawer.open {
    box-shadow: 6rpx 0 30rpx rgba(0, 0, 0, 0.2);
    transform: translateX(0);

}

.drawer-input-content
    margin: 0 42rpx
    padding: 0 36rpx
    height: 108rpx;
    background: #F6F6F6;
    border-radius: 24rpx 24rpx 24rpx 24rpx;
    display: flex
    align-items: center
    justify-content: center
    .drawer-input
        font-size: 42rpx
        width: 100%
    .input-placeholder
        font-weight: 500;
        font-size: 42rpx;
        color: #A6A6A6;
    .input-search
        margin-left: 30rpx
/* 抽屉内容 */
.drawer-content
    height: 100%
    background: #FFFFFF;
    display: flex
    flex-direction: column
    .drawer-user
        border-top: 2rpx solid rgba(0,0,0,.1);
        padding: 30rpx 42rpx
        display: flex
        font-weight: 500;
        align-items: center
        position: relative
        margin-bottom: calc( 48rpx + var(--window-bottom)); /*兼容 IOS<11.2*/
        margin-bottom: calc( 48rpx +var(--window-bottom)); /*兼容 IOS>11.2*/
        color: #000000
        .drawer-user-img
            width: 57.2rpx;
            height: 57.2rpx
            margin-right: 30rpx
        .drawer-user-setting
            width: 72rpx
            height: 72rpx
            position: absolute
            top: 50%
            right: 42rpx
            transform: translate(0,-50%)
    .drawer-title
        height: header-height;
        line-height: header-height;
        padding: 0 78rpx;
        color: #333333;
        font-size: 48rpx
        font-weight: bold
    .chat-scroll
        flex: 1
        overflow: hidden
    .drawer-rows
        padding: 0 42rpx;
        // border-bottom: 3rpx dashed #e8e8e8
        overflow:hidden; //超出的文本隐藏
        text-overflow:ellipsis; //溢出用省略号显示
        white-space:nowrap; //溢出不换行
        .drawer-row-content
            display: flex
            align-items: center
            justify-content: space-between
            width: 100%
        .drawer-row-title
            color: #A6A6A6;
            font-weight: 500;
            font-weight: bold;
            font-size: 42rpx
            padding: 0 36rpx
            margin-top: 75rpx
            margin-bottom: 24rpx
        .drawer-row-list
            flex: 1
            height: 99rpx;
            line-height: 99rpx
            font-size: 42rpx
            overflow: hidden
            text-overflow: ellipsis
            font-weight: 500;
            color: #595959;
            padding: 0 36rpx
        .drawer-row-delete
            padding: 0 18rpx
            height: 99rpx
            display: flex
            align-items: center
            justify-content: center
        .drawer-row-active
        .drawer-row-list:active
            color: #333333;
            background: #F6F6F6;
            border-radius: 24rpx 24rpx 24rpx 24rpx;


/* 主要内容区域 */
.main-content
    width: 100%;
    height: 100%;
    transition: margin-left 0.3s ease-in-out;
    position: relative
    background: #FFFFFF
    display: flex
    flex-direction: column
    .head
        display: block;
        box-sizing: border-box;
        height: header-height;
        user-select: none;
    .main-header
        position: fixed;
        left: var(--window-left);
        right: var(--window-right);
        height:header-height;
        padding-top: calc(14rpx);
        background: #FFFFFF
        z-index: 1;
        transition-property: all;
        display: flex;
        align-items: center;
        justify-content: space-between
        font-size: 48rpx
        color: #000000
        padding: 0 45rpx;
        font-weight: bold
        text-align: center
        image
            width: 54rpx;
            height: 56rpx;

.chatmain-warpper
    height: 'calc(100% - %s)' %( header-height + footer-height)
    position: relative;
    display: block;
    box-sizing: border-box;
    width: 100%;
    border-top: 3rpx solid #F4F4F4;
    flex: 1

/* 页面被挤压时向右移动 */
.main-content.shift {
    margin-left: 750rpx;
}

.chatmain-footer{
    height: footer-height;
}
</style>
