<template>
    <div class="chat-container">
        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
            <div v-for="(msg, index) in messages" :key="index" class="message" :class="msg.sender">
                <!-- 对方消息 -->
                <template v-if="msg.sender === 'received'">
                    <!-- <div class="avatar">{{ msg.receiverName.charAt(0) }}</div> -->
                    <el-avatar
                        class="avatar"
                        :size="40"
                        :src="
                            msg.receiverIcon ||
                            'https://birdseye-img.sysuimars.com/dinggou-mini/defalut-icon.png'
                        "
                    />
                    <img src="" alt="" />
                    <div class="bubble" :class="{ 'no-bubble': msg.messageType === 'image' ,'card-bubble': msg.messageType === 'card'}">
                        <!-- 文本消息 -->
                        <div v-if="msg.messageType === 'text'" class="content">{{ msg.content }}</div>

                        <!-- 图片消息 -->
                        <div v-if="msg.messageType === 'image'" class="image-message">
                            <img
                                :src="msg.content + resize"
                                @click="showImagePreview(msg.content)"
                                @load="handleImageLoad"
                                alt="图片"
                            />
                        </div>

                        <!-- 语音消息 -->
                        <div v-if="msg.messageType === 'audio'" class="audio-message" @click="playAudio(msg.content)">
                            <span class="audio-icon">🎵</span>
                            <span class="duration">{{ msg.duration }}"</span>
                        </div>

                        <!-- 对话样式消息 -->
                        <div v-if="msg.messageType === 'dialog'" class="dialog-message">
                            <template v-if="msg.content.type === 'farm_report'">
                                <div class="report-title">{{ msg.content.title }}</div>
                                <div class="dialog-title">{{ msg.content.content }}</div>
                                <img src="@/assets/img/monitor/aaa.png" alt="" class="monitor-image" />
                            </template>
                            <template v-else>
                                <div class="dialog-title">{{ msg.content.title }}</div>
                                <img src="@/assets/img/monitor/image.png" alt="" class="monitor-image" />
                            </template>
                        </div>

                         <!-- 对话样式消息 -->
                        <div v-if="msg.messageType === 'card'" class="card-message" @click="handleCardClick(msg)">
                            <template v-if="(msg.cardType || msg.content.cardType) === 'quotation'">
                                <div class="card-title">向您发送了一张 服务报价单</div>
                                <img src="https://birdseye-img.sysuimars.com/temp/price.png" alt="" />
                            </template>
                            <template v-else>
                                <div class="card-title">{{ msg.title || msg.content.title }}</div>
                                <img :src="handleImgUrl(msg.coverUrl || msg.content.coverUrl)" alt="" />
                            </template>
                        </div>

                        <!-- <div class="time">{{ msg.time }}</div> -->
                    </div>
                </template>

                <!-- 我方消息 -->
                <template v-else>
                    <div class="bubble" :class="{ 'no-bubble': msg.messageType === 'image','card-bubble': msg.messageType === 'card'}">
                        <!-- 文本消息 -->
                        <div v-if="msg.messageType === 'text'" class="content">{{ msg.content }}</div>

                        <!-- 图片消息 -->
                        <div v-if="msg.messageType === 'image'" class="image-message">
                            <img
                                :src="msg.content + resize"
                                @click="showImagePreview(msg.content)"
                                @load="handleImageLoad"
                                alt="图片"
                            />
                        </div>

                        <!-- 语音消息 -->
                        <div v-if="msg.messageType === 'audio'" class="audio-message" @click="playAudio(msg.content)">
                            <span class="audio-icon">🎵</span>
                            <span class="duration">{{ msg.duration }}"</span>
                        </div>

                        <!-- 对话样式消息 -->
                        <div v-if="msg.messageType === 'dialog'" class="dialog-message">
                            <template v-if="msg.content.type === 'farm_report'">
                                <div class="report-title">{{ msg.content.title }}</div>
                                <div class="dialog-title">{{ msg.content.content }}</div>
                                <img src="@/assets/img/monitor/aaa.png" alt="" class="monitor-image" />
                            </template>
                            <template v-else>
                                <div class="dialog-title">{{ msg.content.title }}</div>
                                <img src="@/assets/img/monitor/image.png" alt="" class="monitor-image" />
                            </template>
                        </div>

                        <!-- 对话样式消息 -->
                        <div v-if="msg.messageType === 'card'" class="card-message" @click="handleCardClick(msg)">
                            <template v-if="(msg.cardType || msg.content.cardType) === 'quotation'">
                                <div class="card-title">向您发送了一张 服务报价单</div>
                                <img src="https://birdseye-img.sysuimars.com/temp/price.png" alt="" />
                            </template>
                            <template v-else>
                                <div class="card-title">{{ msg.title || msg.content.title }}</div>
                                <img :src="handleImgUrl(msg.coverUrl || msg.content.coverUrl)" alt="" />
                            </template>
                        </div>

                        <!-- <div class="time">{{ msg.time }}</div> -->
                    </div>
                    <!-- <div class="avatar avatar-r">{{ msg.senderName.charAt(0) }}</div> -->
                    <el-avatar
                        class="avatar avatar-r"
                        :size="40"
                        :src="
                            msg.senderIcon ||
                            'https://birdseye-img.sysuimars.com/dinggou-mini/defalut-icon.png'
                        "
                    />
                </template>
            </div>
        </div>

        <!-- 功能按钮区域 -->
        <div class="function-buttons">
            <el-select v-model="farmVal" size="large" @change="handleFarmChange()">
                <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
            </el-select>
            <!-- <div v-for="(btn, index) in functionButtons" :key="index" class="function-btn" @click="btn.handler">
                <span class="btn-text">{{ btn.text }}</span>
            </div> -->
        </div>

        <!-- 输入框区域 -->
        <div class="input-area">
            <div class="toolbar">
                <!-- <button @click="toggleEmojiPicker">😊</button> -->
                <!-- <button @click="startImageUpload">📷</button> -->
                <!-- <button
                    @mousedown="startRecording"
                    @mouseup="stopRecording"
                    @touchstart="startRecording"
                    @touchend="stopRecording"
                >
                    🎤
                </button> -->
                <el-icon class="link" @click="startImageUpload"><Link /></el-icon>
                <input type="file" ref="fileInput" accept="image/*" style="display: none" @change="handleImageUpload" />
            </div>

            <input type="text" v-model="inputMessage" placeholder="请输入你想说的话~" @keyup.enter="sendTextMessage" />
            <div class="send" @click="sendTextMessage">发送</div>

            <!-- 录音指示器 -->
            <div v-if="isRecording" class="recording-indicator">
                <div class="pulse"></div>
                录音中... {{ recordingDuration }}s
            </div>
        </div>

        <!-- Emoji 选择器 -->
        <div v-if="showEmojiPicker" class="emoji-picker">
            <span v-for="emoji in emojis" :key="emoji" @click="addEmoji(emoji)">{{ emoji }}</span>
        </div>

        <!-- 图片预览模态框 -->
        <div v-if="previewImage" class="image-preview" @click="previewImage = null">
            <img :src="previewImage" alt="预览" />
        </div>
    </div>
</template>

<script setup>
import { ref, onUnmounted, nextTick, watch, onActivated, onDeactivated } from "vue";
import { useRouter ,useRoute} from "vue-router";
import { base_img_url2 } from "@/api/config";
import { getFileExt } from "@/utils/util";
import UploadFile from "@/utils/upliadFile";
import MqttClient from "@/plugins/MqttClient";
import customHeader from "@/components/customHeader.vue";

const resize = "?x-oss-process=image/resize,p_120/format,webp/quality,q_100";
const router = useRouter();

const props = defineProps({
    text: {
        type: String,
        defalut: "",
    },
    img: {
        type: String,
        defalut: "",
    },
    userId: {
        type: [String, Number],
        defalut: "",
    },
});

const emit = defineEmits(['update:name']);

const defalutMsg = ref([
    {
        sender: "sent",
        senderIcon: "王",
        messageType: "text",
        content:
            "你好，我叫陈晓晓。有100亩荔枝，30亩桂味，70亩妃子笑，位置在广州市番禺区大学城110号，希望您可以来指导。",
        time: "上午10:32",
    },
]);

const curUserId = Number(localStorage.getItem("MINI_USER_ID"));
const senderIcon = ref("");
const receiverIcon = ref("");
const receiverIdVal = ref(null);

// 本地用户头像
const localUserInfoIcon = (() => {
    try {
        const info = JSON.parse(localStorage.getItem("localUserInfo") || "{}");
        return info?.icon || "";
    } catch (e) {
        return "";
    }
})();

// 初始化本地头像为默认发送者头像
senderIcon.value = localUserInfoIcon;
const nameVal = ref('');

// 监听 nameVal 变化，传递给父组件
watch(nameVal, (newVal) => {
    emit('update:name', newVal);
});

//聊天会话
const createSession = (targetUserId, callback) => {
    nameVal.value = '';
    VE_API.bbs.createSession({ farmId: farmVal.value, targetUserId }).then(({ data, code }) => {
        if (code === 0) {
            nameVal.value = data.session.targetUserName;
            senderIcon.value = localUserInfoIcon;
            receiverIcon.value = data.session.targetUserAvatar;
            receiverIdVal.value = data.session.targetUserId;
            messages.value = data.messages.map((item) => {
                let content = item.content;
                if (item.messageType === "image") {
                    // 优先读取后端的 image 字段，其次兼容旧的 content(JSON)
                    if (item.image && (item.image.url || item.image.originUrl)) {
                        content = item.image.url || item.image.originUrl;
                    } else if (item.content) {
                        try {
                            const imgObj = JSON.parse(item.content);
                            content = imgObj.url || imgObj.originUrl;
                        } catch (e) {
                            console.error(e, "e");
                        }
                    }
                }else if(item.messageType === 'card'){
                    content = JSON.parse(item.content);
                }
                return {
                    ...item,
                    content,
                    sender: item.senderId === curUserId ? "sent" : "received",
                    senderIcon: item.senderId === curUserId ? localUserInfoIcon : data.session.targetUserAvatar,
                    receiverIcon: data.session.targetUserAvatar,
                };
            });

            setTimeout(() => {
                scrollToBottom();
            }, 300);
            callback && callback();
        }
    });
};

const handleFarmChange = (e) => {
    createSession(userId.value);
    initMqtt();
};

//发送消息接口
//类型 text ，file，image
const sendMsg = (messageType = "text", content = "", obj = {}) => {
    const params = {
        farmId: farmVal.value,
        senderId: curUserId,
        receiverId: userId.value,
        content,
        [messageType]:obj,
        messageType,
    };
    VE_API.bbs.sendMsg(params);
};

const userId = ref(null);

const handleCardClick = (msg) => {
    router.push(msg.linkUrl || msg.content.linkUrl);
}

const handleImgUrl = (url) => {
    if (url && url.includes('https://')) {
        return url;
    } else {
        return base_img_url2 + url + resize;
    }
}
watch(
    () => props.userId,
    async (newValue) => {
        if (newValue) {
            await getFarmList();
            userId.value = newValue;
            createSession(newValue, () => {
                if(route.query.pageParams) {
                    const params = JSON.parse(route.query.pageParams);
                    const message = {
                        sender: "sent",
                        messageType: "card",
                        senderIcon: senderIcon.value,
                        title: params.farmWorkName + ' 农事已完成，请您确认',
                        cardType:'farm_work',
                        linkUrl:`/completed_work?json=${JSON.stringify({id:params.id})}`,
                        time: getCurrentTime(),
                    };
                    if(params.executeEvidence && params.executeEvidence.length > 5) {
                        const imgArr = JSON.parse(params.executeEvidence);
                        message.coverUrl = imgArr[imgArr.length - 1];
                    }

                    if(params.imageList && params.imageList.length) {
                        const img = params.imageList[params.imageList.length - 1];
                        if (img.cloudFilename) {
                            message.coverUrl = img.cloudFilename;
                        } else {
                            message.coverUrl = img;
                        }
                    }
                    
                    if(params.type === 'quotation') {
                        message.cardType = 'quotation';
                        message.title = '向您发送了一张服务报价单'
                        const jsonParams = {
                            id:params.id,
                            farmWorkOrderId:params.farmWorkOrderId,
                            isAssign: true
                        }
                        message.linkUrl = `/completed_work?json=${JSON.stringify(jsonParams)}`;
                    }

                    if(params.type === 'reviewWork') {
                        message.cardType = 'reviewWork';
                        message.title = '向您分享了农事执行成果'
                        message.linkUrl = `/review_work?json=${JSON.stringify({id: params.id,goBack: true})}`;
                    }

                    if(params.type === 'remindExecute' || params.type === 'remindUser') {
                        const jsonParams = {
                            id:params.id,
                            farmWorkOrderId:params.farmWorkOrderId
                        }
                        if(params.type === 'remindExecute') {
                            message.title = '请您尽快执行 ' + params.farmWorkName + ' 农事';
                            message.linkUrl = `/completed_work?json=${JSON.stringify(jsonParams)}`;
                        } else if(params.type === 'remindUser') {
                            message.title = '请您尽快完成复核';
                            message.linkUrl = `/review_work?json=${JSON.stringify({id:params.id,goBack: true})}`;
                        }
                        message.cardType = params.type
                    }

                    sendMessage(message);
                    
                    // 清除路由中的 pageParams 参数
                    const newQuery = { ...route.query };
                    delete newQuery.pageParams;
                    router.replace({
                        path: route.path,
                        query: newQuery
                    });
                }
                if (props.text) {
                    sendMsg("text", props.text);
                    messages.value.push({
                        sender: "sent",
                        senderIcon: senderIcon.value,
                        messageType: "text",
                        content: props.text,
                    });
                    if (props.img) {
                        const imgArr = JSON.parse(props.img);
                        if (imgArr.length) {
                            imgArr.forEach((item) => {
                                sendMsg("image", "", { url: item, thumbnailUrl: item + resize });
                                messages.value.push({
                                    sender: "sent",
                                    senderIcon: senderIcon.value,
                                    messageType: "image",
                                    content: item,
                                });
                            });
                        }
                    }
                }
            });
            initMqtt();
        }
    }
);

onDeactivated(() => {
    mqttClient.value && mqttClient.value.client.end(true);
});

// mqtt 连接
const mqttClient = ref(null);
const messagesContainer = ref(null);

// 消息数据
const messages = ref([]);

// 输入相关
const inputMessage = ref("");
const fileInput = ref(null);
const showEmojiPicker = ref(false);
const emojis = ["😀", "😂", "😍", "👍", "👋", "🎉", "❤️", "🙏"];

// 录音相关
const isRecording = ref(false);
const recordingDuration = ref(0);
const audioChunks = ref([]);
const mediaRecorder = ref(null);
const audioContext = ref(null);

function handleImageLoad() {
    scrollToBottom();
}

// 图片预览
const previewImage = ref(null);

// 初始化 mqtt
const initMqtt = () => {
    const topics = [`user/chat/message/${farmVal.value}/${curUserId}`]; // 订阅的主题数组
    mqttClient.value = new MqttClient(topics, (topic, message) => {
        if (message && message.length > 10) {
            const obj = JSON.parse(message);
            console.log("message有值", obj);
            if(obj.senderId === curUserId){
                return;
            }
            if (obj.senderId === receiverIdVal.value) {
                // 检查是否已存在相同 id 的消息，避免重复添加
                if (obj.id && messages.value.some(msg => msg.id === obj.id)) {
                    return;
                }
                if (obj.messageType === "image") {
                    if (obj.image && (obj.image.url || obj.image.originUrl)) {
                        obj.content = obj.image.url || obj.image.originUrl;
                    } else if (obj.content) {
                        try {
                            const img = JSON.parse(obj.content);
                            obj.content = img.url || img.originUrl;
                        } catch (e) {
                            console.error(e, "e");
                        }
                    }
                }else if(obj.messageType !== 'text'){
                    obj.content = JSON.parse(obj.content);
                }
                obj.receiverId = curUserId;
                (obj.sender = obj.senderId === curUserId ? "sent" : "received"), (obj.senderIcon = senderIcon.value);
                obj.receiverIcon = receiverIcon.value;
                messages.value.push(obj);

                scrollToBottom();
            }
        }
    });

    mqttClient.value.connect();
};

// 发送消息
const sendMessage = (message) => {
    if (message.messageType === "text") {
        sendMsg("text", message.content);
    } else if (message.messageType === "image") {
        // 按新协议：不传 content，传 image 对象
        sendMsg("image", "", { url: message.content, thumbnailUrl: message.content + resize });
    } else if (message.messageType === "dialog") {
        // 对话样式消息不发送到服务器，只显示在本地
        console.log("发送对话样式消息:", message.content);
    }else{
        sendMsg('card','',{
            title: message.title,
            coverUrl: message.coverUrl,
            cardType: message.cardType,
            linkUrl: message.linkUrl
        });
    }
    messages.value.push(message);
    scrollToBottom();
};

// 发送文本消息
const sendTextMessage = () => {
    if (inputMessage.value.trim()) {
        const message = {
            sender: "sent",
            messageType: "text",
            senderIcon: senderIcon.value,
            content: inputMessage.value,
            time: getCurrentTime(),
        };
        sendMessage(message);
        inputMessage.value = "";
    }
};

// 发送图片消息
const sendImageMessage = (imageUrl) => {
    const message = {
        sender: "sent",
        messageType: "image",
        senderIcon: senderIcon.value,
        content: imageUrl,
        time: getCurrentTime(),
    };
    sendMessage(message);
};

// 发送语音消息
const sendAudioMessage = (audioUrl, duration) => {
    const message = {
        sender: "sent",
        messageType: "audio",
        senderIcon: senderIcon.value,
        content: audioUrl,
        duration: duration,
        time: getCurrentTime(),
    };
    sendMessage(message);
};

// 图片处理
const startImageUpload = () => {
    fileInput.value.click();
};

const uploadFileObj = new UploadFile();

const handleImageUpload = (event) => {
    const file = event.target.files[0];
    if (file) {
        // 实际项目中应该上传到服务器，这里使用本地URL模拟
        const miniUserId = localStorage.getItem("MINI_USER_ID");
        let ext = getFileExt(file.name);
        let key = `birdseye-look-mini/${miniUserId}/${new Date().getTime()}.${ext}`;
        let imageUrl = "";
        uploadFileObj.put(key, file).then((resFilename) => {
            imageUrl = base_img_url2 + resFilename;
            sendImageMessage(imageUrl);
        });
        // const imageUrl = URL.createObjectURL(file);
    }
};

const showImagePreview = (imageUrl) => {
    previewImage.value = imageUrl;
};

// 语音处理
const startRecording = async () => {
    try {
        audioChunks.value = [];
        recordingDuration.value = 0;

        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        mediaRecorder.value = new MediaRecorder(stream);
        audioContext.value = new (window.AudioContext || window.webkitAudioContext)();

        mediaRecorder.value.ondataavailable = (event) => {
            if (event.data.size > 0) {
                audioChunks.value.push(event.data);
            }
        };

        mediaRecorder.value.onstop = async () => {
            const audioBlob = new Blob(audioChunks.value, { type: "audio/wav" });
            const audioUrl = URL.createObjectURL(audioBlob);

            // 计算录音时长
            const duration = Math.round(recordingDuration.value);

            // 实际项目中应该上传到服务器，这里使用本地URL模拟
            sendAudioMessage(audioUrl, duration);

            // 释放资源
            stream.getTracks().forEach((track) => track.stop());
        };

        mediaRecorder.value.start();
        isRecording.value = true;

        // 更新录音计时器
        const timer = setInterval(() => {
            recordingDuration.value += 0.1;
            if (!isRecording.value) {
                clearInterval(timer);
            }
        }, 100);
    } catch (error) {
        console.error("录音失败:", error);
        alert("无法访问麦克风，请检查权限设置");
    }
};

const stopRecording = () => {
    if (mediaRecorder.value && isRecording.value) {
        mediaRecorder.value.stop();
        isRecording.value = false;
    }
};

const playAudio = (audioUrl) => {
    const audio = new Audio(audioUrl);
    audio.play();
};

// Emoji 处理
const toggleEmojiPicker = () => {
    showEmojiPicker.value = !showEmojiPicker.value;
};

const addEmoji = (emoji) => {
    inputMessage.value += emoji;
    showEmojiPicker.value = false;
};

// 功能按钮配置
const functionButtons = ref([
    {
        text: "农场报告",
        handler: () => {
            console.log("点击农场报告，农场ID:", farmVal.value);
            // 发送农场报告对话框消息
            sendFarmReportDialog();
        },
    },
    {
        text: "农事卡片",
        handler: () => {
            // 跳转到农事卡片页面
            router.push(`/farm_card?farmId=${farmVal.value}`);
        },
    },
    // {
    //     text: '农场相册',
    //     handler: () => {
    //         // 跳转到农场相册页面
    //         router.push(`/farm_photo`);
    //     }
    // }
]);

// 辅助函数
const getCurrentTime = () => {
    return new Date().toLocaleTimeString("zh-CN", {
        hour: "2-digit",
        minute: "2-digit",
    });
};

const scrollToBottom = () => {
    nextTick(() => {
        setTimeout(() => {
            if (messagesContainer.value) {
                messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
            }
        }, 300);
    });
};

const farmVal = ref("");
const options = ref([]);
const route = useRoute();

// 获取农场列表
function getFarmList() {
    let params = {
        agriculturalQuery: false,
    }
    if(curRole.value == 2){
        params.userId = props.userId;
    }
    return VE_API.farm.userFarmSelectOption(params).then(({ data }) => {
        options.value = data || [];
        if (data && data.length > 0) {
            const defaultOption = data.find((item) => item.defaultOption === true);
            if(route.query.farmId) {
                farmVal.value = Number(route.query.farmId);
            }else{
                farmVal.value = defaultOption ? defaultOption.id : data[0].id;
            }
        }
    });
}

const curRole = ref(null);
onActivated(() => {
    curRole.value = localStorage.getItem("SET_USER_CUR_ROLE");
    if (props.userId) {
        scrollToBottom();
    }
    // 检查是否有选中的农事工作数据
    checkSelectedFarmWork();
});

// 检查选中的农事工作数据
const checkSelectedFarmWork = () => {
    const selectedFarmWork = localStorage.getItem("selectedFarmWork");
    if (selectedFarmWork) {
        const data = JSON.parse(selectedFarmWork);
        // 发送对话样式的消息
        sendDialogMessage(data.dialogMessage);
        // 清除localStorage中的数据
        localStorage.removeItem("selectedFarmWork");
    }
};

// 发送对话样式的消息
const sendDialogMessage = (dialogData) => {
    const message = {
        sender: "sent",
        messageType: "dialog",
        senderIcon: senderIcon.value,
        content: dialogData,
        time: getCurrentTime(),
    };
    sendMessage(message);
};

// 发送农场报告对话框
const sendFarmReportDialog = () => {
    const currentFarmName = options.value.find((opt) => opt.id === farmVal.value)?.name || "当前农场";

    const farmReportData = {
        type: "farm_report",
        title: currentFarmName,
        content: "这是我的果园情况，请查看~",
        reportDetails: {
            farmId: farmVal.value,
            farmName: currentFarmName,
            reportDate: new Date().toLocaleDateString("zh-CN"),
            reportType: "综合报告",
            status: "正常",
        },
    };

    const message = {
        sender: "sent",
        messageType: "dialog",
        senderIcon: senderIcon.value,
        title: currentFarmName,
        content: farmReportData,
        time: getCurrentTime(),
    };
    sendMessage(message);
};
</script>

<style scoped lang="scss">
/* 基础样式（保持之前的不变） */
.chat-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
    margin: 0 auto;
    border: 1px solid #e6e6e6;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    position: relative;
    box-sizing: border-box;
    .chat-messages {
        flex: 1;
        padding: 12px;
        overflow-y: auto;
        background-color: #f5f5f5;
        box-sizing: border-box;
        .message {
            display: flex;
            margin-bottom: 15px;
        }
        .received {
            justify-content: flex-start;
            .bubble {
                background-color: white;
                border-radius: 0 10px 10px 10px;
                padding: 10px 12px;
                box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
            }
        }
        .sent {
            justify-content: flex-end;
            .bubble {
                background-color: #07c160;
                border-radius: 10px 0 10px 10px;
                padding: 10px 15px;
                color: #fff;
                box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
            }
        }
        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #07c160;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-weight: bold;
        }

        .avatar-r {
            margin: 0 0 0 10px;
        }
        .bubble {
            max-width: 70%;
        }
    }
}

.content {
    font-size: 16px;
    line-height: 1.4;
}

.time {
    font-size: 12px;
    color: #fff;
    margin-top: 5px;
    text-align: right;
}

.input-area {
    display: flex;
    align-items: center;
    padding: 15px 10px;
    border-top: 1px solid #e6e6e6;
    background-color: white;
    position: relative;
    width: 100%;
    box-sizing: border-box;
    input {
        flex: 1;
        padding: 10px;
        border: 1px solid #e6e6e6;
        border-radius: 20px;
        outline: none;
    }
    .send {
        margin-left: 10px;
        padding: 8px 20px;
        background-color: #07c160;
        color: white;
        border: none;
        border-radius: 20px;
        cursor: pointer;
    }
}
// .input-area button:hover {
//     background-color: #06ad56;
// }

/* 新增的多媒体消息样式 */
.image-message {
    img {
        max-width: 200px;
        max-height: 200px;
        border-radius: 8px;
        cursor: pointer;
    }
}

/* 图片消息不使用对话气泡样式 */
.no-bubble {
    background: transparent !important;
    border-radius: 0 !important;
    padding: 0 !important;
    box-shadow: none !important;
    color: inherit !important;
}
.card-bubble{
    background: #fff !important;
}

.audio-message {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    background-color: #f0f0f0;
    border-radius: 20px;
    cursor: pointer;
}

.audio-message .audio-icon {
    margin-right: 8px;
    font-size: 20px;
}

.audio-message .duration {
    font-size: 14px;
    color: #666;
}

.message.sent .audio-message {
    background-color: #d8f1cb;
}

/* 工具栏样式 */
.toolbar {
    display: flex;
    align-items: center;
    button {
        background: none;
        border: none;
        font-size: 20px;
        margin-right: 10px;
        cursor: pointer;
        padding: 5px;
    }
    .link {
        font-size: 24px;
        margin-right: 10px;
    }
}

/* 录音指示器 */
.recording-indicator {
    position: absolute;
    top: -40px;
    left: 0;
    right: 0;
    background-color: #ff4d4f;
    color: white;
    padding: 8px;
    text-align: center;
    border-radius: 4px;
    font-size: 14px;
}

.recording-indicator .pulse {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: white;
    margin-right: 8px;
    animation: pulse 1.5s infinite;
}

@keyframes pulse {
    0% {
        transform: scale(0.95);
        opacity: 1;
    }
    50% {
        transform: scale(1.1);
        opacity: 0.7;
    }
    100% {
        transform: scale(0.95);
        opacity: 1;
    }
}

/* Emoji 选择器 */
.emoji-picker {
    position: absolute;
    bottom: 60px;
    right: 10px;
    background: white;
    border: 1px solid #e6e6e6;
    border-radius: 8px;
    padding: 10px;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 100;
}

.emoji-picker span {
    font-size: 24px;
    text-align: center;
}

.emoji-picker span:hover {
    transform: scale(1.2);
}

/* 功能按钮样式 */
.function-buttons {
    display: flex;
    gap: 5px;
    padding: 5px 10px;
    box-sizing: border-box;
    .function-btn {
        background-color: white;
        border-radius: 8px;
        padding: 10px 10px;
        min-width: 60px;
        text-align: center;
        .btn-text {
            font-size: 14px;
        }
    }
}

/* 图片预览 */
.image-preview {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.image-preview img {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
}

/* 对话样式消息 */
.dialog-message {
    max-width: 100%;
    background: #fff !important;
    padding: 10px;
    border-radius: 10px;
    .report-title {
        font-size: 16px;
        font-weight: 600;
        color: #000;
        margin-bottom: 5px;
    }

    .dialog-title {
        font-size: 12px;
        color: rgba(0, 0, 0, 0.6);
        margin-bottom: 10px;
    }
    .monitor-image {
        width: 222px;
        height: 180px;
        object-fit: cover;
    }

    .farm-report-content,
    .farm-work-content {
        .report-details,
        .work-details {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 12px;
            margin-top: 10px;

            .detail-item {
                display: flex;
                margin-bottom: 6px;
                font-size: 13px;

                &:last-child {
                    margin-bottom: 0;
                }

                .detail-label {
                    color: #666;
                    min-width: 80px;
                }

                .detail-value {
                    color: #333;
                    flex: 1;
                }
            }
        }
    }
}

.card-message{
    .card-title{
        font-size: 15px;
        font-weight: 600;
        color: #000;
        margin-bottom: 5px;
    }
    img{
        width: 222px;
        height: 180px;
        object-fit: cover;
    }
}

/* 我方消息中的对话样式 */
.message.sent .dialog-message {
    background: #e3f2fd;

    .work-details {
        background: #f0f8ff;
    }
}
</style>
