<template>
    <div class="page">
        <div class="back adfac" v-if="dialogList.length">
            <img src="@/assets/images/agent/arrow_left.png">
            <span @click="handleBack">返回</span>
        </div>
        <div class="box adffcacjc" v-if="dialogList.length===0">
            <img src="@/assets/images/agent/dialog_logo2.gif">
            <div class="title">Hi，我是AI团队教练助手～</div>
            <div class="tip">任何关于团队、分析报告、教练的问题，你都可以向我提问，可以为你提供全方位多角度的PREILL团队分析，我正在快速学习和进化中，有新功能时，我一定第一时间告诉你～ </div>
            <div class="items">
                <template v-if="!idx">
                    <div class="item" :class="{'active':idx===1}" @click="handleChange(1)">
                        <div class="i_top adfac">
                            <img src="@/assets/images/agent/dialog_zndh.png">
                            <span>智能对话</span>
                        </div> 
                        <p>解答关于团队、分析报告、教练的问题</p>
                    </div>
                    <div class="item" :class="{'active':idx===2}" @click="handleChange(2)">
                        <div class="i_top adfac">
                            <img src="@/assets/images/agent/dialog_bgfx.png">
                            <span>报告分析</span>
                        </div> 
                        <p>智能解读报告，快速找到关键信息，提出教练重点</p>
                    </div>
                    <div class="item" :class="{'active':idx===3}" @click="handleChange(3)">
                        <div class="i_top adfac">
                            <img src="@/assets/images/agent/dialog_wdwd.png">
                            <span>文档问答</span>
                        </div> 
                        <p>提供全方位多角度的PREILL团队分析</p>
                    </div>
                </template>
            </div>
        </div>
        <div class="dialog" v-else>
            <div class="list">
                <div class="l_item" v-for="(item,index) in dialogList" :key="index">
                    <div class="li_pre my adfac" v-if="item.type===1">
                        <div class="text">{{ item.question }}</div>
                        <img class="img" src="@/assets/images/agent/dialog_avatar.png">
                    </div>
                    <div class="li_pre ai" v-else-if="item.type===2">
                        <div class="adfac">
                            <img class="img" src="@/assets/images/agent/dialog_logo3.png">
                            <!-- <div class="text" v-if="item.answer">{{ item.answer }}</div> -->
                            <div class="text" v-if="item.answer" v-html="sanitizeHtml(item.answer)"></div>
                            <div class="text" v-else>
                                <img src="@/assets/images/agent/dialog_loading.gif">
                                <span>正在思考中</span>
                            </div>
                        </div>
                        <div class="icons adfac" v-if="item.answer">
                            <el-popover  placement="bottom" trigger="hover" content="重新生成">
                                <template #reference>
                                    <img alt="重新生成" :src="isSx?require('@/assets/images/agent/dialog_sx2.png'):require('@/assets/images/agent/dialog_sx1.png')" @click="handleSx(index)" class="f">
                                </template>
                            </el-popover>
                            <el-popover  placement="bottom" trigger="hover" content="复制">
                                <template #reference>
                                    <img alt="复制" :src="isFz?require('@/assets/images/agent/dialog_fz2.png'):require('@/assets/images/agent/dialog_fz1.png')" @click="handleFz(index)">
                                </template>
                            </el-popover>
                            <el-popover  placement="bottom" trigger="hover" content="喜欢">
                                <template #reference>
                                    <img alt="喜欢" :src="isDz?require('@/assets/images/agent/dialog_dz2.png'):require('@/assets/images/agent/dialog_dz1.png')" @click="handleDz">
                                </template>
                            </el-popover>
                            <el-popover  placement="bottom" trigger="hover" content="评论">
                                <template #reference>
                                    <img alt="评论" :src="isPl?require('@/assets/images/agent/dialog_pl2.png'):require('@/assets/images/agent/dialog_pl1.png')" @click="handlePl">
                                </template>
                            </el-popover>
                        </div>
                    </div>
                    <div class="li_pre ai adfac" v-else-if="item.type===3">
                        <img class="img" src="@/assets/images/agent/dialog_logo3.png">
                        <div class="text">
                            <div class="title">报告分析</div>
                            <div class="tip">智能解读报告，快速找到关键信息，提出教练重点</div>
                            <div class="upload adfac">
                                <img src="@/assets/images/agent/upload.png">
                                <div class="span">上传报告</div>
                            </div>
                        </div>
                    </div>
                    <div class="li_pre ai adfac" v-else-if="item.type===4">
                        <img class="img" src="@/assets/images/agent/dialog_logo3.png">
                        <div class="text">
                            <div class="title">文档问答</div>
                            <div class="tip">提供全方位多角度的PREILL团队分析</div>
                            <div class="upload adfac">
                                <img src="@/assets/images/agent/upload.png">
                                <div class="span">上传文档</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="ask">
            <div class="a_top">
                <el-input type="textarea" :rows="3" :placeholder="placeholder" v-model="question" resize="none" @keyup.enter.native="handleQuestion"></el-input>
            </div>
            <div class="a_bottom adfacjb">
                <div class="ab_l adfac">
                    <div class="abl_pre adfac" :class="{'active':isChzq}" @click="isChzq=!isChzq">
                        <img src="@/assets/images/agent/think.png" v-if="!isChzq">
                        <img src="@/assets/images/agent/think2.png" v-else>
                        <span>创衡增强</span>
                    </div>
                    <div class="abl_pre adfac" :class="{'active':isLwss}" @click="isLwss=!isLwss">
                        <img src="@/assets/images/agent/intenet.png" v-if="!isLwss">
                        <img src="@/assets/images/agent/intenet2.png" v-else>
                        <span>联网搜索</span>
                    </div>
                    <div class="abl_pre adfac" :class="{'active':isScwd}" @click="isScwd=!isScwd">
                        <img src="@/assets/images/agent/upload.png" v-if="!isScwd">
                        <img src="@/assets/images/agent/upload2.png" v-else>
                        <span>上传文档</span>
                    </div>
                </div>
                <div class="ab_r">
                    <img src="@/assets/images/agent/input_hou.png" v-if="question" @click="handleQuestion" style="cursor: pointer;">
                    <img src="@/assets/images/agent/input_qian.png" v-else style="cursor: not-allowed;">
                </div>
            </div>
        </div>
    </div>
</template>

<script setup name="">
    import Cookies from "js-cookie";
    import DOMPurify from 'dompurify';
    import { ref, getCurrentInstance } from 'vue'
    import useClipboard from 'vue-clipboard3';
    const { toClipboard } = useClipboard();
    const { proxy } = getCurrentInstance();
    
    const idx = ref('')
    const placeholder = ref('有什么问题，可以向我提问！')
    const question = ref('')
    const isChzq = ref(false)
    const isLwss = ref(false)
    const isScwd = ref(false)
    const isSx = ref(false)
    const isFz = ref(false)
    const isDz = ref(false)
    const isPl = ref(false)
    const dialogList = ref([])

    const currentTaskId = ref('');

    const handleBack = () => {
        dialogList.value = [];
        idx.value = '';
        proxy.$router.push('/agent-dialog');
    }

    const handleChange = (val) => {
        idx.value = val;
        dialogList.value = []
        if(val===1) placeholder.value = '有什么问题，可以向我提问！';
        else if(val===2){
            placeholder.value = '上传报告并输入问题提问';
            let obj = {type:3}
            dialogList.value.unshift(obj)
        } 
        else if(val===3){
            placeholder.value = '上传文件并输入问题提问';
            let obj = {type:4}
            dialogList.value.unshift(obj)
        } 
    }

    const handleQuestion = () => {
        if(question.value.trim()=='') return proxy.$message.warning('请输入问题');
        let obj1 = {
            question: question.value.trim(),
            type: 1
        }
        dialogList.value = [...dialogList.value,obj1]
        let obj2 = {
            answer: '',
            type: 2
        }
        dialogList.value = [...dialogList.value,obj2]
        startStream(question.value.trim());
        question.value = '';
    }

    const startStream = async (query) => {
        try {
            const response = await fetch(`${window.SITE_CONFIG['apiURL']}/core/chat/messages`, {//streamingMessage messages
                method: 'POST',
                headers: {
                    'token':Cookies.get('token') || '',
                    'Content-Type': 'application/json',
                    // 'Accept': 'text/event-stream',
                },
                body: JSON.stringify({
                    query
                })
            });

            if (!response.ok || !response.body) {
                throw new Error(`请求失败: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');
            let buffer = ''; // 累积缓冲器

            while (true) {
                const { value, done } = await reader.read();
                if (done) break;

                buffer += decoder.decode(value, { stream: true });
                // console.log(buffer, 'buffer');
                const event = buffer;
                    if (event.startsWith('data:')) {
                        try {
                            const jsonStr = event.replaceAll('data:', '');
                            console.log(jsonStr, 'jsonStr');
                            dialogList.value = [...dialogList.value].map((item, idx) => {
                                if (idx === dialogList.value.length - 1) {
                                    return { ...item, answer: item.answer + (jsonStr || '') };
                                }
                                
                                return item;
                            });
                        } catch (e) {
                            console.error('SSE解析失败', e, '原始数据:', event);
                        }
                    }
            }
        } catch (err) {
            console.log(err,'err');
        }
    };

    const sanitizeHtml = (html) => {
      if (!html) return '';
      return DOMPurify.sanitize(html);
    }

    const handleSx = (index) => {
        // isSx.value = !isSx.value;
        dialogList.value[index].answer = '';
        let query = dialogList.value[index-1].question;
        startStream(query)
    }
    const handleFz = async (index) => {
        // isFz.value = !isFz.value;
        try {
            await toClipboard(dialogList.value[index].answer);
            proxy.$message.success('复制成功');
        } catch (e) {
            proxy.$message.error('复制失败');
        }
    }
    const handleDz = () => {
        isDz.value = !isDz.value;
    }
    const handlePl = () => {
        isPl.value = !isPl.value;
    }
</script>

<style scoped lang="scss">
    ::v-deep .el-textarea textarea{
        border: none !important;
        padding: 0 !important;
    }
    ::v-deep .el-popover{
        background:#000 !important;
        min-width: inherit !important;
        color: #FFFFFF !important;
        border-radius: 10px;
        padding: 10px !important;
    }
    ::v-deep .popper__arrow::after{
        border-bottom-color:#000 !important;
    }

    .page{
        width: 100%;
        padding: 40px 290px;
        box-sizing: border-box;
        position: relative;

        .back{
            position: absolute;
            left: 30px;
            top: 20px;
            cursor: pointer;
            img{
                width: 36px;
                height: 36px;
            }
            span{
                margin-left: 10px;
                font-family: PingFang-SC, PingFang-SC;
                font-weight: bold;
                font-size: 16px;
                color: #252525;
                line-height: 22px;
            }
        }

        .box{
            width: 100%;
            height: calc(100vh - 228px);
            &>img{
                width: 99px;
                height: 94px;
            }
            .title{
                font-family: PingFang-SC, PingFang-SC;
                font-weight: bold;
                font-size: 24px;
                color: #252525;
                line-height: 33px;
                text-align: center;
                margin-top: 30px;
            }
            .tip{
                max-width: 647px;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 14px;
                color: #646464;
                line-height: 20px;
                text-align: center;
                margin-top: 16px;
            }
            .items{
                width: 700px;
                min-height: 124px;
                margin-top: 40px;
                display: flex;
                justify-content: space-between;
                .item{
                    width: calc(100% / 3 - 13px);
                    padding: 17px 16px;
                    box-sizing: border-box;
                    background: #FFFFFF;
                    box-shadow: 0px 2px 12px 0px rgba(0,0,0,0.04);
                    border-radius: 10px;
                    cursor: pointer;
                    &.active,&:hover{
                        border: 1px solid #833478;
                        padding: 16px 15px;
                    }
                    .i_top{
                        img{
                            width: 32px;
                            height: 32px;
                        }
                        span{
                            font-family: PingFang-SC, PingFang-SC;
                            font-weight: bold;
                            font-size: 16px;
                            color: #252525;
                            line-height: 22px;
                            margin-left: 12px;
                        }
                    }
                    p{
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 400;
                        font-size: 14px;
                        color: #999999;
                        line-height: 20px;
                        margin-top: 18px;
                    }
                }
            }
        }

        .dialog{
            width: 100%;
            height: calc(100vh - 228px);
            padding: 24px 0;
            position: relative;
            overflow-y: auto;
            .list{
                .l_item{
                    margin-top: 36px;
                    &:first-child{
                        margin-top: 0;
                    }
                    .li_pre{
                        .text{
                            max-width: calc(100% - 60px);
                            padding: 14px 16px;
                            box-sizing: border-box;
                            border-radius: 8px;
                            font-family: PingFangSC, PingFang SC;
                            font-weight: 400;
                            font-size: 14px;
                            line-height: 20px;
                            .title{
                                font-family: PingFang-SC, PingFang-SC;
                                font-weight: bold;
                                font-size: 16px;
                                color: #393939;
                                line-height: 16px;
                            }
                            .tip{
                                font-family: PingFangSC, PingFang SC;
                                font-weight: 400;
                                font-size: 14px;
                                color: #999999;
                                line-height: 14px;
                                margin-top: 16px;
                            }
                            .upload{
                                width: 112px;
                                background: #FFFFFF;
                                border-radius: 18px;
                                border: 1px solid #E5E7EB;
                                margin-top: 24px;
                                padding: 8px 12px;
                                box-sizing: border-box;
                                cursor: pointer;
                                img{
                                    width: 14px;
                                    height: 14px;
                                    margin: 0;
                                }
                                .span{
                                    font-family: PingFangSC, PingFang SC;
                                    font-weight: 400;
                                    font-size: 14px;
                                    color: #252525;
                                    line-height: 20px;
                                    margin-left: 11px;
                                }
                            }
                        }
                        .icons{
                            width: 216px;
                            margin-top: 16px;
                            margin-left: 60px;
                            padding: 10px 20px 10px 0;
                            background: #FFFFFF;
                            border-radius: 8px;
                            border: 1px solid #EFEFEF;
                            img{
                                width: 24px;
                                height: 24px;
                                margin: 0;
                                margin-left: 20px;
                                cursor: pointer;
                                &.f{
                                    width: 44px;
                                    padding-right: 20px;
                                    border-right: 1px solid #E5E7EB;
                                }
                            }
                            .line{
                                width: 1px;
                                height: 20px;
                                background: #E5E7EB;
                            }
                        }
                        .img{
                            width: 36px;
                            height: 36px;
                        }
                        &.my{
                            justify-content: flex-end;
                            .text{
                                border: 1px solid #833478;
                                background: #833478;
                                color: #FFFFFF;
                            }
                            .img{
                                margin-left: 24px;
                            }
                        }
                        &.ai{
                            .text{
                                border: 1px solid #EFEFEF;
                                background: #FFFFFF;
                                color: #393939;
                                &>img{
                                    width: 24px;
                                    height: 24px;
                                }
                                span{
                                    font-family: PingFang-SC, PingFang-SC;
                                    font-weight: bold;
                                    font-size: 14px;
                                    color: #393939;
                                    line-height: 20px;
                                    margin-left: 5px;
                                }
                            }
                            .img{
                                width: 42px;
                                margin-right: 18px;
                            }
                        }
                    }
                }
            }
        }

        .ask{
            width: 100%;
            height: 148px;
            background: #FFFFFF;
            box-shadow: 0px 2px 12px 0px rgba(0,0,0,0.04);
            border-radius: 16px;
            padding: 20px 24px;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            position: relative;

            .a_top{
                flex: 1;
                padding-bottom: 10px;
            }

            .a_bottom{
                .ab_l{
                    .abl_pre{
                        background: #FFFFFF;
                        border-radius: 18px;
                        border: 1px solid #E0E0E0;
                        padding: 10px 13px;
                        margin-left: 16px;
                        cursor: pointer;
                        &:first-child{
                            margin-left: 0;
                        }
                        img{
                            width: 16px;
                            height: 16px;
                        }
                        span{
                            font-family: PingFangSC, PingFang SC;
                            font-weight: 400;
                            font-size: 15px;
                            color: #393939;
                            line-height: 15px;
                            margin-left: 7px;
                        }
                        &.active{
                            background: rgba(118,30,106,0.06);
                            span{
                                color: #761E6A;
                            }
                        }
                    }
                }
                .ab_r{
                    img{
                        width: 32px;
                        height: 32px;
                        border-radius: 7px;
                    }
                }
            }
        }
    }
</style>