<template>
    <div class="chat-page">
        <div class="left-panel">
            <UserCard @load="onLoadUserList" :cardlist="userList" height="calc(100vh - 120px)" @change="onSelectUser" />
        </div>
        <div class="right-panel">
            <div class="chat-body" ref="chatBody" @scroll="handleScroll">
                <ChatRecord :msgList="messages" :sendeInfo="sendeInfo" msgType="user" @retry="handleRetry" />
            </div>

            <div class="chat-footer">
                <div class="footer-left" style="">
                    <div class="upload-row" style="display:flex; align-items:center; gap:12px;margin-left: 6px;">
                        <el-icon style="font-size:24px;cursor:pointer" @click="triggerImageInput">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-tupian1"></use>
                            </svg>
                        </el-icon>
                        <input ref="imageInput" type="file" accept="image/*" style="display:none"
                            @change="handleImageChange" />
                        <V3Emoji @click-emoji="onEmojiSelect" :recent="true"></V3Emoji>
                    </div>
                    <el-input type="textarea" v-model="draft" placeholder="输入消息..." rows="2" style="flex:1"
                        @keydown="handleInputKeydown" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import ChatRecord from '@/components/ChatRecord/index.vue'
import UserCard from '@/components/UserCard/index.vue'
import UserMessage from '@/components/UserMessage/index.vue'
import mihoutai from '@/assets/images/mihoutai.png'
import V3Emoji from "vue3-emoji";
import { getUserList, send_message, get_messages } from '@/api/chat'
import { useRoute } from 'vue-router'
import { uploadFile } from '@/api/upload'
const route = useRoute()

// mock data for now — integrate with store/api as needed
const userList = ref([
    { user_id: 'u1', user_name: '张三', user_avatar: '' },
    { user_id: 'u2', user_name: '李四', user_avatar: '' },
    { user_id: 'u3', user_name: '王五', user_avatar: '' },
])

const activeUser = ref({})
const messages = ref([])
const draft = ref('')
const imageInput = ref(null)
const chatBody = ref(null)

const sendeInfo = reactive({
    userInfo: { user_id: '', user_name: '', user_avatar: '' },
    robotInfo: { wx_id: '', head_url: '' }
})

// 添加消息分页查询参数
const msgQuery = reactive({
    page: 1,
    page_size: 100,
    app_id: route.query.app_id,
    user_id: ''
})

// 添加加载状态
const loadingMore = ref(false)
const noMoreMessages = ref(false)

const onSelectUser = (id) => {
    // id may be user_id or array when multiple; handle only single selection here
    const u = userList.value.find((it) => it.user_id == id)
    if (u) {
        // mark selected and clear others
        userList.value.forEach((it) => (it.active = it.user_id === id))
        activeUser.value = u
        sendeInfo.userInfo = { user_id: u.user_id, user_name: u.user_name, user_avatar: u.user_avatar }
        // set robot identity used by ChatRecord to determine right-side messages
        sendeInfo.robotInfo = { wx_id: 'robot', head_url: mihoutai }
        // load messages for user (placeholder)
        messages.value = []
        // 重置分页参数
        msgQuery.page = 1
        msgQuery.user_id = u.user_id
        noMoreMessages.value = false
        // scroll after messages rendered
        scrollToBottom()
        getMessages()
    }
}

// 修改获取消息的方法
const getMessages = () => {
    if (loadingMore.value || noMoreMessages.value) return

    loadingMore.value = true
    get_messages({ ...msgQuery }).then(res => {
        if (res.list && res.list.length > 0) {
            // 解析消息内容
            const newMessages = res.list.map(item => {
                item.content = JSON.parse(item.content)
                return item
            })

            if (msgQuery.page === 1) {
                // 首次加载
                messages.value = newMessages
            } else {
                // 加载更多，将新消息添加到列表开头
                messages.value = [...newMessages, ...messages.value]
            }

            // 如果返回的消息少于请求的数量，说明没有更多消息了
            if (res.list.length < msgQuery.page_size) {
                noMoreMessages.value = true
            }
        } else {
            // 没有更多消息
            noMoreMessages.value = true
        }

        loadingMore.value = false
    }).catch(() => {
        loadingMore.value = false
    })
}

// 添加滚动事件处理函数
const handleScroll = (e) => {
    const { scrollTop } = e.target

    // 当滚动到顶部时加载更多消息
    if (scrollTop <= 0 && !loadingMore.value && !noMoreMessages.value) {
        loadMoreMessages()
    }
}

// 加载更多消息
const loadMoreMessages = () => {
    if (msgQuery.user_id) {
        msgQuery.page++
        getMessages()
    }
}

const send = () => {
    if (!activeUser.value.user_id) {
        ElMessage({ type: 'warning', message: '请先选择一个联系人' })
        return
    }
    if (!draft.value) return
    const content = draft.value
    const id = Date.now() + Math.random()
    const msg = {
        _id: id,
        _sending: true,
        _failed: false,
        sender_name: '机器人',
        msg_type: 0,
        content: { messages: content },
        send_time: '刚刚',
        "sender_id": "888888",
        "sender_name": "平台",
        "msg_type": 1
    }
    messages.value.push(msg)
    draft.value = ''
    // ensure scroll
    scrollToBottom()
    // send to server
    send_message({
        app_id: route.query.app_id,
        content: JSON.stringify({
            messages: content
        }),
        msg_type: 1,
        to_user_id: activeUser.value.user_id
    }).then(() => {
        msg._sending = false
        msg._failed = false
    }).catch(() => {
        msg._sending = false
        msg._failed = true
        ElMessage({ type: 'error', message: '消息发送失败' })
    })
}

const handleInputKeydown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault()
        send()
    }
}

const triggerImageInput = () => {
    imageInput.value && imageInput.value.click()
}

const handleImageChange = (e) => {
    const file = e.target.files[0]
    if (!file) return
    // 直接用本地URL预览和发送
    const url = URL.createObjectURL(file)
    const id = Date.now() + Math.random()
    const msg = {
        _id: id,
        _sending: true,
        _failed: false,
        sender_id: '888888',
        sender_name: '平台',
        msg_type: 2,
        content: { messages: url },
        send_time: '刚刚'
    }
    messages.value.push(msg)
    // 清空input，允许重复选择同一图片
    e.target.value = ''
    // 图片可能增加高度，延迟滚动以保证图片渲染
    setTimeout(() => scrollToBottom(), 100)
    // 上传 file to server using FormData
    const form = new FormData()
    form.append('file', file)
    form.append('app_id', route.query.app_id)
    form.append('msg_type', 2)
    form.append('to_user_id', activeUser.value.user_id)
    uploadFile(form, import.meta.env.VITE_APP_BASE_API + 'admin/upload/image').then((resp) => {
        send_message({
            app_id: route.query.app_id,
            content: JSON.stringify({ messages: import.meta.env.VITE_APP_BASE_API + resp.preview_image_url }),
            msg_type: 2,
            to_user_id: activeUser.value.user_id
        }).then(() => {
            msg._sending = false
            msg._failed = false
        }).catch(() => {
            msg._sending = false
            msg._failed = true
            ElMessage({ type: 'error', message: '图片发送失败' })
        })
    })


}

const handleRetry = (id) => {
    const msg = messages.value.find((m) => m._id === id)
    if (!msg) return
    msg._failed = false
    msg._sending = true
    if (msg.msg_type === 0) {
        send_message({ app_id: route.query.app_id, content: msg.content.content, msg_type: 1, to_user_id: activeUser.value.user_id })
            .then(() => { msg._sending = false })
            .catch(() => { msg._sending = false; msg._failed = true; ElMessage({ type: 'error', message: '重发失败' }) })
    } else if (msg.msg_type === 2) {
        const form = new FormData()
        form.append('file', msg.content.file)
        form.append('app_id', route.query.app_id)
        form.append('msg_type', 2)
        form.append('to_user_id', activeUser.value.user_id)
        send_message(form).then(() => { msg._sending = false }).catch(() => { msg._sending = false; msg._failed = true; ElMessage({ type: 'error', message: '重发失败' }) })
    }
}

const scrollToBottom = async () => {
    await nextTick()
    const el = chatBody.value
    if (!el) return
    try {
        el.scrollTop = el.scrollHeight
    } catch (e) {
        // ignore
    }
}

// 当 messages 变化时自动滚动（仅在首次加载或发送新消息时）
// 移除原来的watcher，因为现在需要更精确地控制滚动行为

const onEmojiSelect = (emoji) => {
    if (draft.value) {
        draft.value += emoji
    } else {
        draft.value = emoji
    }
}

const params = reactive({
    page: 1,
    page_size: 20,
    app_id: route.query.app_id
})

const getUsers = (append = false) => {
    getUserList(params).then((res) => {
        if (append) {
            // append new items
            userList.value = userList.value.concat(res.list || [])
        } else {
            userList.value = res.list || []
        }
        // if first load and no active user, select first
        if (!append && userList.value.length && !activeUser.value.user_id) {
            onSelectUser(userList.value[0].user_id)
        }
    })
}

// 当 UserCard 触发 load（分页）时调用，加载下一页并滚动列表到底部以显示新数据
const onLoadUserList = async () => {
    params.page = params.page + 1
    await getUsers(true)
    // 等待 DOM 更新后滚动
    await nextTick()
    const el = document.querySelector('.left-panel .infinite-list')
    if (el) {
        // 滚动到底部以展示新加载的用户
        el.scrollTop = el.scrollHeight
    }
}

const sendMessage = async (message) => {
    send_message(message).then((res) => {
    }).catch((err) => {
        ElMessage({ type: 'error', message: '消息发送失败' })
    })
}

onMounted(() => {
    getUsers()
})
</script>

<style scoped lang="scss">
.chat-page {
    display: flex;
    height: calc(100vh - 60px);
}

:deep(.el-textarea__inner) {
    background-color: transparent;
    padding-left: 8px !important;
}

.left-panel {
    width: 280px;
    border-right: 1px solid var(--el-border-color);
    background: var(--el-bg-color);
    display: flex;
    flex-direction: column;
}

.left-header {
    height: 60px;
    line-height: 60px;
    padding: 0 16px;
    font-weight: 600;
}

.right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.chat-header {
    height: 64px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    border-bottom: 1px solid var(--el-border-color);
}

.chat-header .avatar {
    width: 40px;
    height: 40px;
    margin-right: 12px;
}

.chat-body {
    flex: 1;
    padding: 16px;
    overflow: auto;
    background: #f5f7fa
}

.chat-footer {
    height: 96px;
    padding: 5px 5px;
    border-top: 1px solid var(--el-border-color);
}

.chat-footer .actions {
    display: flex;
    align-items: center
}
</style>