<template>
    <view class="chat-container">
        <view class="container-banner" :style="{ height: globalData.navBarHeight + 'px' }">
            <view class="container-banner-box" :style="{ height: globalData.statusBarHeight + 'px' }" @click="onKf">
                <img src="/static/serverImg/chat/msg.png" alt="" style="width: 34rpx;height: 34rpx;margin-top: 12rpx;">
                <view class="container-banner-btn">咨询客服</view>
            </view>
        </view>
        <scroll-view refresher-enabled :refresher-triggered="isRefreshing" @refresherrefresh="onCustomRefresh"
            class="scroll-view-class" @scrolltolower="scrolltolower" scroll-y>
            <view class="chat-main">
                <view class="chat-sys-box">
                    <view class="chat-sys-item">
                        <view class="chat-sys-title">
                            收到{{kf_count}}条客服对话
                            <view class="chat-num sys-ab" v-if="kf_count > 0">{{ kf_count }}</view>
                        </view>
                        <view class="chat-sys-btn" @click="onKf">去查看</view>
                    </view>
                    <view class="chat-sys-item">
                        <view class="chat-sys-title">收到{{xt_count}}条系统提醒
                            <view class="chat-num sys-ab" v-if="xt_count > 0">{{ xt_count }}</view>
                        </view>
                        <view class="chat-sys-btn" @click="goSys()">去查看</view>
                    </view>
                </view>
                <view v-if="list && list.length > 0" class="chat-list">
                    <uni-swipe-action>
                        <uni-swipe-action-item v-for="item in list" :key="item.code" :right-options="[
                            {
                                text: '删除',
                                style: {
                                    backgroundColor: '#ff4949',
                                    width: '80px'
                                }
                            }
                        ]" @click="handleDelete(item)">
                            <template #default>
                                <view class="chat-item" @click="onClick(item)">
                                    <img src="/static/serverImg/mine/system.png" alt="" class="chat-img" v-if="item.conversationType === '1'" />
                                    <img src="/static/serverImg/mine/customer.png" alt="" class="chat-img" v-else-if="item.conversationType === '3'" />

                                    <img v-else :src="item.conversationAvatar" alt=""
                                        class="chat-img" />
                                   
                                    <view class="chat-box">
                                        <view class="chat-top">
                                            <text class="chat-name">{{['1','3'].includes(item.conversationType) ? 
                                           item.conversationType ==='1'?'系统消息' :'客服消息'
                                            :
                                                type ? item.volunteerName : item.userName }}</text>
                                            <text class="chat-time">{{ handlerData(item.newestMsgTime ||
                                                item.createTime) }}</text>
                                        </view>
                                        <view class="chat-bottom">
                                            <text class="chat-text">
                                                {{ item.msgType === '2' ? '[图片]' : item.newestMsgContent || '[暂无消息]' }}
                                            </text>
                                            <view class="chat-num"
                                                v-if="item.msgUnreadCount && item.msgUnreadCount > 0">
                                                {{ item.msgUnreadCount }}
                                            </view>
                                        </view>
                                    </view>
                                </view>

                            </template>
                        </uni-swipe-action-item>
                    </uni-swipe-action>
                </view>
                <view v-else>
                    <NoneView value="暂无消息" icon="/static/serverImg/chat/null.png" />
                </view>
            </view>
        </scroll-view>



        <custom-tab-bar page="chat" />
    </view>

</template>

<script setup>
import CustomTabBar from '@/components/CustomTabBar/index.vue'
import { ref, computed,onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app';
import NoneView from '@/components/NoneView/index.vue'
import dayjs from 'dayjs/esm/index'
import { getList, conversationRemove } from '@/api/conversation.js';
import { getNavBarHeight } from '@/utils/index.js'

const userType = uni.getStorageSync('userType') || 1;//读取本地存储
const list = ref([])
const globalData = ref({
    statusBarHeight: 47,
    navBarHeight: 91,
})

const type = computed(() => {
    return userType === 1
})
const isRefreshing = ref(false)

// 客服数量
const kf_count = computed(() =>{
    const  count = list.value.filter(item => item.conversationType === '3')
    if(count && count.length >0){
        return count[0].msgUnreadCount
    }
    return 0
})
//系统消息数量
const xt_count = computed(() =>{
    const  count = list.value.filter(item => item.conversationType === '1')
    if(count && count.length >0){
        return count[0].msgUnreadCount
    }
    return 0
})

const goSys =()=>{
    const  count = list.value.filter(item => item.conversationType === '3')
    if(count && count.length >0){
        const data = count[0];
        onClick(data);
    }
}

const onKf = () => {
    uni.navigateTo({
                url: `/pages_orderuser/pages/talk/pages/index/index?customerService=true&conversationType=3`
    })
}

const loadmoreInfo = ref({
    status: 'loadmore',
    loadingText: '努力加载中...',
    loadmoreText: '点击加载更多~',
    nomoreText: '您没有更多消息～'
})
const pages = ref({
    current: 1,
    pageSize: 10,
    total: 0,
})
const isToday = (date) => {
    return dayjs(date).isSame(dayjs(), 'day');
};

const isYesterday = (date) => {
    return dayjs(date).isSame(dayjs().subtract(1, 'day'), 'day');
};
const handlerData = (dates) => {
    const date = dayjs(dates);
    if (isToday(dates)) {
        return date.format('HH:MM');;
    } else if (isYesterday(dates)) {
        return '昨天';
    } else {
        return date.format('YY/MM/DD'); // 或者其他格式如 'YYYY年MM月DD日'
    }
}

const onClick = (record) => {
    uni.navigateTo({
        url: `/pages_orderuser/pages/talk/pages/index/index?conversationRecordId=${record.conversationRecordId}&conversationType=${record.conversationType}`
    });
}
const scrolltolower = () => {
    init('bottom')
};

const onCustomRefresh = () => {
    isRefreshing.value = true;
    pages.value.current = 1;
    init('top')
};
const handleDelete = (item) => {
    uni.showModal({
        title: '提示',
        content: '确定要删除该聊天吗？',
        success: async (res) => {
            if (res.confirm) {
                // 调用删除接口
                try {
                    await conversationRemove({
                        conversationRecordId: item.conversationRecordId,
                        system: userType === 1 ? '1' : '2'
                    }); // 替换为实际接口
                    uni.showToast({ title: '删除成功' });
                    init('top'); // 刷新列表
                } catch (err) {
                    uni.showToast({ title: '删除失败', icon: 'none' });
                }
            }
        }
    });
};

const init = async (type) => {
    try {

        if (type === 'bottom') {
            if (list.value.length < pages.value.total) {
                loadmoreInfo.value.status = 'loading';
                pages.value.current++;
            } else {
                loadmoreInfo.value.status = 'nomore';
                return;
            }
        } else {
            uni.showLoading({
                title: '数据加载中...',
            })
        }

        const res = await getList({
            // pageNum: pages.value.current,
            // pageSize: pages.value.pageSize,
            system: userType === 1 ? '1' : '2'
        });
        list.value = type === 'top' ? res.rows : [...list.value, ...res.rows];
        pages.value.total = res.total;
    } catch (error) {
        console.log('error', error);
        uni.showToast({
            title: error.msg,
            icon: 'error',
        });
    } finally {
        if (type === 'top') {
            isRefreshing.value = false;
            uni.hideLoading();
        }

        if (list.value.length === pages.value.total) {
            loadmoreInfo.value.status = 'nomore';
        }
    }
}

const getNav = async () => {
    try {
        const res = await getNavBarHeight();
        globalData.value = res;
    } catch (error) {

    }
}

onShow(() => {
    init('top');
    // getNav()
})
onMounted(() =>{
    getNav()
})
</script>

<style lang="scss" scoped>
.chat-container {

    position: fixed;
    top: 0px;
    bottom: 0;
    left: 0px;
    right: 0px;
    padding-bottom: 150rpx;
    background: #FAF8F7;

    .scroll-view-class {
        height: 100%;
        padding-bottom: 200rpx;
    }

    .chat-main {
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    .chat-list {
        padding: 16rpx 0 16rpx 32rpx;
    }

    .chat-item {
        display: flex;

        flex: 1;

        .chat-img {
            width: 84rpx;
            height: 84rpx;
            border-radius: 84rpx;
            margin-right: 26rpx;
        }

        .chat-box {
            flex: 1;
            border-bottom: 1rpx solid rgba(216, 216, 216, 0.8);
            height: 100%;
            padding-bottom: 30rpx;
            padding-right: 53rpx;

            .chat-top {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .chat-name {
                    font-family: PingFang SC;
                    font-size: 32rpx;
                    font-weight: normal;
                    line-height: 40rpx;
                    letter-spacing: normal;
                    color: rgba(0, 0, 0, 0.8);

                }

                .chat-time {
                    font-family: PingFang SC;
                    font-size: 28rpx;
                    font-weight: normal;
                    line-height: 40rpx;
                    text-align: right;
                    letter-spacing: normal;
                    color: rgba(0, 0, 0, 0.5);
                }
            }

            .chat-bottom {
                display: flex;
                justify-content: space-between;

                .chat-text {
                    font-family: PingFang SC;
                    font-size: 28rpx;
                    font-weight: normal;
                    line-height: 40rpx;
                    letter-spacing: normal;
                    color: rgba(109, 121, 141, 0.8);
                    width: 250px;


                    white-space: nowrap;
                    /* 禁止换行 */
                    overflow: hidden;
                    /* 隐藏溢出内容 */
                    text-overflow: ellipsis;
                    /* 溢出部分显示省略号 */
                }

                // .chat-num {
                //     background: rgba(239, 68, 68, 1);
                //     color: #fff;
                //     display: flex;
                //     align-items: center;
                //     justify-content: center;

                //     width: 40rpx;
                //     height: 40rpx;
                //     border-radius: 40rpx;
                //     line-height: 40rpx;
                //     font-size: 24rpx;
                // }
            }


        }
        .chat-box:last-child {
            border-bottom:none; 
        }

    }
}

.chat-item {
    transition: transform 0.2s ease;
}

.container-banner {
    display: flex;
    align-items: flex-end;
    background: #fff;

    .container-banner-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 45rpx;

        .container-banner-btn {
            font-size: 30rpx;
            font-weight: 500;
            line-height: 44rpx;
            display: flex;
            align-items: center;
            color: #3D3D3D;
            margin-left: 13rpx;
        }
    }
}



.chat-sys-box {
    padding: 24rpx 32rpx 46rpx;
    display: flex;
    gap: 32rpx;

    .chat-sys-item {
        flex: 1;
        padding: 32rpx;
        border-radius: 18rpx;
        background: #FFFFFF;
        box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(0, 0, 0, 0.06);

        .chat-sys-title {
            font-size: 32rpx;
            font-weight: 600;
            color: rgba(0, 0, 0, 0.8);
            margin-bottom: 16rpx;
            position: relative;
        }

        .chat-sys-btn {
            border-radius: 24rpx;
            background: #F7F7F7;
            width: 128rpx;
            height: 48rpx;
            font-size: 26rpx;
            font-weight: 600;
            line-height: 40rpx;
            color: #757474;

            display: flex;
            align-items: center;
            justify-content: center;
        }

    }
}

.sys-ab {
    position: absolute;
    right: -14rpx;
    top: -22rpx;
}

.chat-num {
    width: 32rpx;
    height: 32rpx;
    border-radius: 32rpx;

    font-family: PingFang SC;
    font-size: 24rpx;
    font-weight: 600;
    line-height: 44rpx;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #FFFFFF;

    background: #FF1818;
}
</style>