<template>
    <div class="page">
        <div class="back adfac" v-if="dialogList.length||idx" @click="handleBack">
            <img src="@/assets/images/agent/arrow_left.png">
            <span>返回</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" ref="scrollableDiv" 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="li_file adfac" v-if="item.askFile">
                            <img src="@/assets/images/agent/agent_file.png" v-if="idx===2">
                            <img src="@/assets/images/agent/agent_file.png" v-else-if="idx===3">
                            <div class="lif_info">
                                <p>{{ item.qfileName }}</p>
                                <p><span>{{ item.qfileType }}</span> <span>{{ item.qfileSize }}</span></p>
                            </div>
                        </div>
                        <div class="text" v-else>{{ 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" 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 popper-class="icon_pop" 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,item?.taskId)" class="f">
                                </template>
                            </el-popover>
                            <el-popover popper-class="icon_pop" 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 popper-class="icon_pop" 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 popper-class="icon_pop" 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>
                            <el-upload
                                :action="uploadUrl"
                                :headers="uploadHeaders"
                                :on-success="e=>uploadFileSuccess(e,'report')"
                                :before-upload="e=>beforeAvatarUpload(e,'report')"
                                :file-list="fileList"
                                :limit="1">
                                <div class="upload adfac">
                                    <img src="@/assets/images/agent/upload.png">
                                    <div class="span">上传报告</div>
                                </div>
                            </el-upload>
                        </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>
                            <el-upload
                                :action="uploadUrl"
                                :headers="uploadHeaders"
                                :on-success="e=>uploadFileSuccess(e,'file')"
                                :before-upload="e=>beforeAvatarUpload(e,'file')"
                                :file-list="fileList"
                                :limit="1">
                                <div class="upload adfac">
                                    <img src="@/assets/images/agent/upload.png">
                                    <div class="span">上传文档</div>
                                </div>
                            </el-upload> 
                        </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 active">
                        <img src="@/assets/images/agent/think2.png">
                        <span>创衡增强</span>
                    </div>
                    <div class="abl_pre adfac active">
                        <img src="@/assets/images/agent/intenet2.png">
                        <span>联网搜索</span>
                    </div>
                    <!-- <div class="abl_pre adfac" :class="{'active':isScwd}" @click="isScwd=!isScwd">
                        <el-upload
                            :action="uploadUrl"
                            :headers="uploadHeaders"
                            :on-success="uploadFileSuccess"
                            :before-upload="beforeAvatarUpload"
                            :limit="1">
                            <div>
                                <img src="@/assets/images/agent/upload.png" v-if="!isScwd">
                                <img src="@/assets/images/agent/upload2.png" v-else>
                                <span>上传文档</span>
                            </div>
                        </el-upload> 
                    </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, watch } from 'vue'
    import useClipboard from 'vue-clipboard3';
    import { sendChatMessageStream,stopChatMessage } from '@/api/agent'
    const { toClipboard } = useClipboard();
    const { proxy } = getCurrentInstance();
    const uploadUrl = `${window.SITE_CONFIG["apiURL"]}/sys/oss/uploadFile`
    const uploadHeaders = {token:Cookies.get("token")};
    
    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 fileList = ref([])
    const questionFile = ref('')
    const scrollableDiv = ref(null);
    const askParams = ref({
        query:'',
        identity:'教练',
    })
    const askFileName = ref('')
    const askFileType = ref('')
    const askFileSize = ref('')

    const currentTaskId = ref('');

    const handleBack = () => {
        dialogList.value = [];
        idx.value = '';
        placeholder.value = '有什么问题，可以向我提问！';
        questionFile.value = '';
        askParams.value = {
            query:'',
            identity:'教练',
        };
        askFileName.value = '';
        askFileType.value = '';
        askFileSize.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 uploadFileSuccess = (e,type) =>{
        questionFile.value = e.data;
        if(type==='report') askParams.value.report = e.data;
        else if(type==='file') askParams.value.file = e.data;
        proxy?.$modal.msgSuccess('上传成功');
        let fnc = JSON.parse(JSON.stringify(askFileName.value));
        let fnt = JSON.parse(JSON.stringify(askFileType.value));
        let fns = JSON.parse(JSON.stringify(askFileSize.value));
        dialogList.value.push({type:1,askFile:true,qfileName:fnc,qfileType:fnt,qfileSize:fns})
        fileList.value = [];
    }
    const beforeAvatarUpload = (e,t) => {
        let type = e.name.split('.')[e.name.split('.').length-1];
        let isTxt = e.type === 'text/plain';
        let isPdf = e.type === 'application/pdf';
        let isHtml = e.type === 'text/html';
        let isExcel = e.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        let isDocx = e.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        if((type.toLowerCase() === 'xlsx' || type.toLowerCase() === 'xls' && isExcel) 
            || (type.toLowerCase() === 'docx' && isDocx)
            || (type.toLowerCase() === 'txt' && isTxt)
            || (type.toLowerCase() === 'pdf' && isPdf)
            || (type.toLowerCase() === 'html' && isHtml)
            && e.size <= 1024*1024*15){
            askFileName.value = e.name;
            askFileType.value = type.toUpperCase();
            askFileSize.value = (e.size/1024/1024).toFixed(1)+'MB';
        }else{
            proxy?.$modal.msgError('请上传txt、pdf、html、xlsx、xls或docx格式的文件！且文件大小不超过15MB！');
            return false;
        }
    }

    const handleQuestion = () => {
        if(question.value.trim()=='') return proxy.$message.warning('请输入问题');
        if(idx.value===2&&!questionFile.value) return proxy.$message.warning('请上传报告')
        if(idx.value===3&&!questionFile.value) return proxy.$message.warning('请上传文档')
        let qc = JSON.parse(JSON.stringify(question.value.trim()));
        let obj1 = {
            question: question.value.trim(),
            type: 1
        }
        dialogList.value = [...dialogList.value,obj1]
        let obj2 = {
            answer: '',
            type: 2
        }
        dialogList.value = [...dialogList.value,obj2]
        question.value = '';
        askParams.value.query = qc;
        startStream();
    }

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

            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 });
                const events = buffer.split('\n\n');
                buffer = events.pop() || ''; 
                events.forEach(event => {
                    if (event.startsWith('data:')) {
                        try {
                            const jsonStr = event.slice(5).trim();
                            const jsonData = JSON.parse(jsonStr);
                            currentTaskId.value = jsonData?.task_id || '';
                            dialogList.value = [...dialogList.value].map((item, idx) => {
                                if (idx === dialogList.value.length - 1) {
                                    return { ...item, answer: item.answer + (jsonData?.answer.replace(/\n\n+/g, '<br><br>').replace(/\n+/g, '<br>') || ''),taskId: jsonData?.task_id || '' };
                                }
                                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,taskId) => {
        stopChatMessage(taskId).then((res) => {
            if(res.code!==0) return proxy.$modal.msgError(res.message);
            dialogList.value[index].answer = '';
            let query = dialogList.value[index-1].question;
            startStream(query)
        })
    }
    const handleFz = async (index) => {
        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;
    }

    watch(() => dialogList.value, (newVal) => {
        if(newVal.length>0) {
            if(scrollableDiv.value){
                setTimeout(() => {
                    scrollableDiv.value.scrollTop = 999999;
                }, 50);
            } 
        }
    })
</script>
<style>
.icon_pop{
    background:#000 !important;
    min-width: inherit !important;
    color: #FFFFFF !important;
    border-radius: 10px;
    padding: 10px !important;
}
.icon_pop .popper__arrow::after{
    border-bottom-color:#000 !important;
}
.el-upload-list{
    display: none !important;
}
</style>
<style scoped lang="scss">
    ::v-deep .el-textarea textarea{
        border: none !important;
        padding: 0 !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;
            flex: 1;
            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;
                                }
                            }
                        }
                        .li_file{
                            max-width: calc(100% - 60px);
                            padding: 14px 16px;
                            box-sizing: border-box;
                            background: #FFFFFF;
                            box-shadow: 0px 2px 12px 0px rgba(0,0,0,0.04);
                            border-radius: 8px;
                            &>img{
                                width: 30px;
                                height: 30px;
                            }
                            .lif_info{
                                margin-left: 16px;
                                p{
                                    font-family: PingFangSC, PingFang SC;
                                    font-weight: 400;
                                    font-size: 14px;
                                    color: #1D2129;
                                    line-height: 14px;
                                    &:last-child{
                                        margin-top: 8px;
                                        span{
                                            font-family: PingFangSC, PingFang SC;
                                            font-weight: 400;
                                            font-size: 12px;
                                            color: #A6A6A6;
                                            line-height: 12px;
                                        }
                                    }
                                }
                            }
                        }
                        .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>