<template>
    <div class="chat-page">
        <div class="chat-wrap">
            <div class="chat-title">飞鸟种植大脑</div>
            <div class="chat-box" ref="chatBox">
                <div v-for="(msg, index) in messages" :key="index" class="message" :class="msg.type">
                    <div v-if="msg.type === 'user'" class="bubble">{{ msg.text }}</div>
                    <div v-if="msg.type === 'system'" class="bubble answer">
                        <div class="think" v-if="!msg.text.name">
                            思考中<el-icon><ArrowDown /></el-icon>
                        </div>
                        <div class="header" v-html="msg.text.header"></div>
                        <div class="divider"></div>
                        <div class="content" v-html="msg.text.content"></div>
                        <div class="table-wrap" v-if="msg.text.name === '种植面积'">
                            <el-table :data="tableData" border style="width: 100%">
                                <el-table-column prop="city" label="市" width="100" />
                                <el-table-column prop="area" label="2024年水稻种植面积" width="320">
                                    <template #default="scope">
                                        {{ scope.row.area  }}亩
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <div v-if="msg.type === 'real'" class="bubble answer">
                        <div class="think" v-if="!msg.text.name">
                            思考中<el-icon><ArrowDown /></el-icon>
                        </div>
                        <div class="header" v-html="deepSeekAsk.markdownToHtml(msg.text.header)"></div>
                        <div class="divider"></div>
                        <div class="content" v-html="deepSeekAsk.markdownToHtml(msg.text.content)"></div>
                        <div class="table-wrap" v-if="msg.text.name === '种植面积'">
                            <el-table :data="tableData" border style="width: 100%">
                                <el-table-column prop="city" label="市" width="100" />
                                <el-table-column prop="area" label="2024年水稻种植面积" width="320">
                                    <template #default="scope">
                                        {{ scope.row.area  }}亩
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div v-if="msg.type === 'auto'" class="system auto">
                        <div class="bubble">
                            {{ msg.text.header }}
                            <div>
                                <div class="ask-title">你可以试着问我</div>
                                <div class="ask-list">
                                    <li
                                        class="ask-item cursor-pointer"
                                        @click="askText('2024年广东省各市的水稻种植面积')"
                                    >
                                    2024年广东省各市的水稻种植面积
                                    </li>
                                    <li
                                        class="ask-item cursor-pointer"
                                        @click="askText('2024年广东省各市的水稻种植面积排行')"
                                    >
                                    2024年广东省各市的水稻种植面积排行
                                    </li>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 猜你想问 -->
                    <div v-if="msg.type === 'ask'" class="system ask">
                        <div class="bubble">
                            <div class="ask-title">你可以试着问我</div>
                            <div class="ask-list">
                                <div class="to-map" v-for="(ask, askI) in msg.text.content" :key="askI" @click="toMapLayer(ask)">
                                    <li>
                                        {{ ask }}
                                    </li>
                                    <div class="go-icon"><el-icon><ArrowRight /></el-icon></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bottom-send">
                <div class="input-box">
                    <el-input
                        v-model="userInput"
                        :autosize="{ minRows: 2, maxRows: 8 }"
                        type="textarea"
                        placeholder="给 飞鸟种植大脑 提问吧~"
                        @keyup.enter="sendMessage"
                    />
                    <div class="bottom-group">
                        <div class="btn-l">
                            <div class="l-item">
                                <img src="@/assets/images/warningHome/chat/think.png" />
                                深度思考(R1)
                            </div>
                            <div class="l-item">
                                <img src="@/assets/images/warningHome/chat/net.png" />
                                联网搜索
                            </div>
                        </div>
                        <div class="btn-r">
                            <img class="file-icon" src="@/assets/images/warningHome/chat/file.png" />
                            <img class="send-icon" @click="sendMessage" src="@/assets/images/warningHome/chat/send.png" alt="send">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import chat from "./chat.json";
import DeepSeekAsk from "./deepSeekAsk";
import { useStore } from "vuex";
import eventBus from "@/api/eventBus";
const store = useStore();

let userId = 12321;
let deepSeekAsk = new DeepSeekAsk(userId);

const router = useRouter();

const userInput = ref("");
const messages = ref([]);

const isProcessing = ref(false); // 控制是否在处理消息

const tableData = ref([
    { city: '广州市', area: 10000 },
    { city: '佛山市', area: 900 },
    { city: '惠州市', area: 856 },
    { city: '茂名市', area: 789 },
])

const steps = [
    { type: "auto", text: { header: "您好，飞鸟智慧种植大脑是您的私人管家" } },
    {
        type: "ask",
        text: {
            askHeader: "猜您想问",
            askContent: ["2024年广东省各市的水稻种植面积", "2024年广东省各市的水稻种植面积变化"],
        },
    },
    {
        type: "ask",
        text: {
            askHeader: "猜您想问",
            askContent: ["荔枝出现花带叶怎么办？", "荔枝抽梢具体做什么农事呢？"],
        },
    },
];


const stepIndex = ref(0);
const triggerNextStep = () => {
    if (stepIndex.value < steps.length) {
        addSystemReply(
            steps[stepIndex.value].type,
            steps[stepIndex.value].text,
            () => {
                console.log("stepIndex.value === 76574", stepIndex.value);
                isProcessing.value = false;
            }
        );
        stepIndex.value++;
        saveState();
        scrollToBottom();
    }
};

const loadState = () => {
    const storedMessages = localStorage.getItem(STORAGE_KEY);
    const storedDate = localStorage.getItem(DATE_KEY);
    const storedStep = localStorage.getItem(STEP_KEY);
    const today = new Date().toISOString().split("T")[0];

    if (storedDate === today && storedMessages) {
        messages.value = JSON.parse(storedMessages);
        stepIndex.value = storedStep ? parseInt(storedStep, 10) : 0;
        nextTick(() => scrollToBottom());
    } else {
        localStorage.removeItem(STORAGE_KEY);
        localStorage.removeItem(DATE_KEY);
        localStorage.removeItem(STEP_KEY);
        stepIndex.value = 0;
    }
};

const toMapLayer = (name) => {
    eventBus.emit("chat:showMapLayer", name)
}

const askText = (val) => {
    userInput.value = val;
    sendMessage();
};

const sendMessage = () => {
    if (!userInput.value.trim()) return;

    // 先保存用户输入的内容
    const userText = userInput.value;
    // 添加用户消息
    messages.value.push({ text: userInput.value, type: "user" });

    saveMessages();
    scrollToBottom();

    // 模拟系统回复
    // setTimeout(() => {
    //     console.log("userInput", userText);
    //     messages.value.push({ text: "系统回复: " + userText, type: "system" });
    // }, 500);

    // 模拟 AI 逐字回复
    let isSearch = true;
    console.log("userText", userText);
    chat.map((item) => {
        if (userText.indexOf(item.name) !== -1) {
            addSystemReply('system', {header: item.header, content: item.content, name: item.name}, () => {
                console.log("sendMessage eeeeee",);
                setTimeout(triggerNextStep, 2000);
            });
            isSearch = false;
        }
    });

    if (isSearch) {
        messages.value.push({ type: "real", text: { header: "", content: "" } });
        deepSeekAsk.ask(userText, function (code) {
            if (code == 0) {
                let intervalId = setInterval(() => {
                    if (deepSeekAsk.end) {
                        clearInterval(intervalId);
                    }
                    for (let content of deepSeekAsk.contents) {
                        console.log(content.content);
                        messages.value[messages.value.length - 1].text.content = content.content;
                        messages.value[messages.value.length - 1].text.header = content.header;
                        scrollToBottom();
                        saveMessages();
                    }
                }, 1000);
            }
        });
    }
    // 清空输入框
    userInput.value = "";
};

const loadEnd = ref(false);

// **逐字显示系统回复（header 和 content）**
const addSystemReply = (type = "system", textObject, callback) => {
    isProcessing.value = true
    let currentHeader = "";
    let currentContent = "";
    console.log("stepIndex.value", type);
    if (type === "ask") {
        messages.value.push({ text: { header: textObject.askHeader, content: textObject.askContent }, type });
    } else {
        messages.value.push({ text: { header: currentHeader, content: currentContent, name: textObject.name }, type });
    }
    saveMessages();
    scrollToBottom();

    const content = textObject.content
    const header = textObject.header

    // **逐字显示 content**
    const showContent = () => {
        let contentIndex = 0;
        if (content && content.length > 0) {
            const contentInterval = setInterval(() => {
                if (contentIndex < content.length) {
                    currentContent += content[contentIndex];
                    if (type !== "ask") {
                        messages.value[messages.value.length - 1].text.content = currentContent;
                    }
                    saveMessages();
                    scrollToBottom();
                    contentIndex++;
                } else {
                    clearInterval(contentInterval);
                    console.log("ddddddddone", stepIndex.value);
                    // if (stepIndex.value === 2 || stepIndex.value === 6) {

                    //     nextTick(() => {
                    //                     setTimeout(triggerNextStep, 1000);
                    //                 });
                    // }
                    callback && callback(); // 回复完成后解锁输入
                }
            }, 50);
        } else {
            callback && callback(); // 如果 content 为空，直接解锁输入
        }
    };

    let headerIndex = 0;
    if (header && header.length > 0) {
        const headerInterval = setInterval(() => {
            if (headerIndex < header.length) {
                currentHeader += header[headerIndex];
                messages.value[messages.value.length - 1].text.header = currentHeader;
                saveMessages();
                scrollToBottom();
                headerIndex++;
            } else {
                clearInterval(headerInterval);
                showContent();
            }
        }, 5); // 50ms 逐字显示 header
    } else {
        showContent();
    }
};
const saveState = () => {
    const today = new Date().toISOString().split("T")[0];
    localStorage.setItem(STORAGE_KEY, JSON.stringify(messages.value));
    localStorage.setItem(DATE_KEY, today);
    localStorage.setItem(STEP_KEY, stepIndex.value);
};

// **存入缓存**
const STORAGE_KEY = "chatMessages";
const DATE_KEY = "chatDate";
const STEP_KEY = "chatStep";
const saveMessages = () => {
    const today = new Date().toISOString().split("T")[0]; // 仅保存 "YYYY-MM-DD"
    localStorage.setItem(STORAGE_KEY, JSON.stringify(messages.value));
    localStorage.setItem(DATE_KEY, today);
};

// **恢复缓存**
const loadMessages = () => {
    const storedMessages = localStorage.getItem(STORAGE_KEY);
    const storedDate = localStorage.getItem(DATE_KEY);
    const today = new Date().toISOString().split("T")[0]; // 获取今天的日期

    if (storedDate === today && storedMessages) {
        messages.value = JSON.parse(storedMessages);
    } else {
        // 清除过期数据
        localStorage.removeItem(STORAGE_KEY);
        localStorage.removeItem(DATE_KEY);
    }
};

// 路由跳转
const toOtherPage = (val) => {
    router.push(val);
};

const chatBox = ref();
onMounted(() => {
    // loadMessages()
    // scrollToBottom()
    loadState();
    nextTick(() => {
        setTimeout(triggerNextStep, 1000);
    });
    // setTimeout(() => {
    //     chatBox.value.scrollTo({top: chatBox.value.scrollHeight, behavior: 'smooth' }); // 滚动到页面顶部
    // }, 200)
});

// **滚动到底部**
const scrollToBottom = () => {
    nextTick(() => {
        if (chatBox.value) {
            chatBox.value.scrollTo({ top: chatBox.value.scrollHeight, behavior: "smooth" }); // 滚动到页面底部
        }
    });
};
</script>

<style lang="scss" scoped>
.chat-page {
    height: 100%;
    padding-top: 34px;
    box-sizing: border-box;
    .chat-wrap {
        height: 100%;
        background: #232323;
        border-radius: 8px;
        border: 1px solid #777777;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        box-sizing: border-box;
        .chat-title {
            border-radius: 8px 8px 0 0;
            background: #2F2F2F;
            text-align: center;
            padding: 10px 0;
        }
    }
}
.chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    justify-content: space-between;
    padding: 10px;
    box-sizing: border-box;
    background: #fff;
}
.chat-box {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    
}
.message {
    display: flex;
    margin: 10px 0;
    .avatar {
        width: 28px;
        height: 28px;
        margin-right: 8px;
    }
}
.table-wrap {
    ::v-deep {
        .el-table .el-table__header th.el-table__cell {
            background: #3B3B3B !important;
            border-bottom-color: #555555;
            border-right-color: #555555;
        }
        .el-table {
            color: #fff;
        }
        .el-table tr {
            background: #2F2F2F;
            pointer-events: none;
        }
        .el-table thead {
            color: #999999;
        }
        .el-table td.el-table__cell {
            border-color: #555555;
        }
        .el-table--border .el-table__inner-wrapper:after, .el-table--border:after, .el-table--border:before, .el-table__inner-wrapper:before,
        .el-table__border-bottom-patch, .el-table__border-left-patch{
            background-color: #555555;
        }
    }
}
.ask {
    width: 100%;
    display: flex;
    .bubble {
        width: 100%;
    }
}
.ask-title {
    color: #999999;
    padding-bottom: 10px;
}
.ask-list {
    color: #FFD489;
}
.to-map {
    display: flex;
    justify-content: space-between;
    background: #3C3C3C;
    padding: 6px 8px;
    border-radius: 6px;
    cursor: pointer;
}
.to-map + .to-map {
    margin-top: 8px;
}
.ask-item + .ask-item {
    padding-top: 2px;
}
.route-wrap {
    display: flex;
    .route-img {
        width: 100%;
        padding-top: 8px;
    }
}

.user {
    justify-content: flex-end;
}
.system {
    justify-content: flex-start;
}
.link {
    display: flex;
    .header-link {
        color: #FFD489;
        display: flex;
        align-items: baseline;
        text-decoration: underline;
        .icon {
            margin-right: 5px;
        }
    }
}
.bubble {
    padding: 16px 12px;
    border-radius: 8px;
    // max-width: 60%;
    background: rgba(255, 212, 137, 0.1);
    color: #FFD489;
    border-radius: 16px 2px 16px 16px;
    line-height: 24px;
    font-size: 14px;
    .header {
        color: #999999;
        // padding-bottom: 8px;
    }
    .content {
        color: #ffffff;
    }
    .divider {
        width: 100%;
        height: 1px;
        background: rgba(153, 153, 153, 0.2);
        margin: 12px 0;
    }
    .think {
        color: #999999;
    }
    .expert-img {
        margin-top: 12px;
        width: 100%;
    }
}
.system .bubble {
    background: #2F2F2F;
    color: #fff;
    border-radius: 2px 16px 16px 16px;
}
.uploader {
    width: 100%;
    display: flex;
    justify-content: center;
    img {
        width: 174px;
        height: 55px;
    }
}
.bottom-send {
    padding: 6px 16px 16px;
}
.input-box {
    display: flex;
    flex-direction: column;
    padding: 10px;
    background: #2F2F2F;
    border-radius: 16px;
    /* border-top: 1px solid #ddd; */
    ::v-deep {
        .el-textarea__inner {
            background: transparent;
            box-shadow: none;
            color: #fff;
        }
    }
    .bottom-group {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 6px;
        .btn-l {
            display: flex;
            .l-item {
                display: flex;
                align-items: center;
                border-radius: 20px;
                border: 1px solid #555555;
                padding: 6px 8px;
            }
            .l-item + .l-item {
                margin-left: 12px;
            }
            img {
                width: 16px;
                padding-right: 2px;
            }
        }
        .file-icon {
            width: 16px;
        }
        .send-icon {
            margin-left: 8px;
            width: 28px;
        }
    }
}
input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
}
button {
    margin-left: 10px;
    padding: 10px 15px;
    background: #007bff;
    color: white;
    border: none;
    cursor: pointer;
}
</style>
