<template>
    <div class="main">
        <!-- <div class="customer">
            13241334761
        </div> -->
        <!-- 坐席辅助 -->
        <div style="display: none;" class="foldIcon2" v-if="foldIconTrue">
            <el-icon 
            color="#ffffff" 
            @click="foldshow"
            style="vertical-align: middle; margin-top: 6px;margin-left: -2px;">
                <ArrowRight />
            </el-icon>
        </div>
        <div style="display: none;" class="foldIcon" v-if="foldIconFlag">
            <el-icon 
            color="#ffffff" 
            @click="foldHide"
            style="vertical-align: middle; margin-top: 6px;margin-left: -2px;">
                <ArrowLeft />
            </el-icon>
        </div>
        <transition v-if="false" name="h1">
            <div v-if="foldFlag" class="chat" ref="chat" @mouseenter="chatMouse(0)" @mouseleave="chatMouse(1)">
            
                <!-- <div v-show="showAiButton" class="ai-button" @click="openAi">
                    <el-image :src="aiIcon" :fit="fit"></el-image>
                </div> -->
                <div class="ai-conversation">
                    <div v-for="(item, index) in chatData" :key="index">

                        <div class="conversation_item" v-if="item.direction === 1">
                            <div class="item_user">
                                <div class="aiHtml">{{ item.page_content }}</div>
                            </div>
                        </div>
                        <div class="conversation_item" v-if="item.direction === 2">
                            <div class="item_ai" v-loading="item.loadingFlag">
                                <div class="aiHtml">
                                    {{ item.page_content }}
                                </div>
                                <!-- <div class="tools-wrap">
                                    <div class="item-ai-tools">
                                        <div class="tools-left"></div>
                                        <div class="tools-right">
                                            <div class="pointer">
                                                <div class="text">信息检索</div>
                                            </div>
                                        </div>
                                    </div>
                                </div> -->
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </transition>
        <!-- 信息检索 -->
        <div class="middle"  @mouseenter="msgMouse()">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="档案" name="user">
                    <patient-info :descColumn="3" :patientCallNumber="telNumber" ></patient-info>
                </el-tab-pane>
                <el-tab-pane label="工单" name="workorder">
                    <workorder/>
                </el-tab-pane>
                <el-tab-pane label="通话记录" name="records">
                    <teleRecords />
                </el-tab-pane>
                <el-tab-pane label="知识库" name="zsk">
                    <knowledge-list></knowledge-list>
                </el-tab-pane>
                <!-- <el-tab-pane label="Task" name="fourth">Task</el-tab-pane> -->
            </el-tabs>

            <!-- <div class="latest">
                13241334761
            </div> -->
        </div>
        <!-- 工单创建 -->
        <div class="order">
            <div style="float: right;">
                <el-button :loading-icon="Eleme" type="primary" v-if="false" link @click="aiSubmit"
                    :loading="aiLoading">一键智能填单</el-button>
            </div>
            <el-form :model="form" :inline-message="true" :rules="rules" label-position="top">
                <el-form-item label="工单标题">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="来电人">
                    <el-input v-model="form.customerName"></el-input>
                </el-form-item>
                <el-form-item label="联系电话">
                    <el-input v-model="form.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="事件地址">
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
                <el-form-item label="问题描述">
                    <el-input type="textarea" :rows="5" v-model="form.description"></el-input>
                </el-form-item>
            </el-form>
            <div class="button-container">
                <el-button @click="onReset">重置</el-button>
                <el-button type="primary" @click="onSubmit">提交</el-button>
            </div>
        </div>

        <div class="aiDialog">
            <!-- title="Tips" -->
            <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false"
                :modal="false" width="30%"
                :style="{ 'background': 'url(' + base64data.aiBG + ') center center / 100% 100% no-repeat' }" draggable>
                <ai-dialog :text="selectedText"></ai-dialog>
            </el-dialog>
        </div>
    </div>
</template>

<script setup name="CallScreen">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import patientInfo from "@/views/main/patientFile/patientFileList/cpns//patientInfo/patientInfo";
import aiIcon from '@/assets/images/aiIcon.png' // 默认头像
import aiDialog from '@/components/main/Navbar/cpns/aiDialog/aiDialog.vue'
import { base64data } from '@/utils/baseUrlData'
import { Eleme } from '@element-plus/icons-vue'
import workorder from './cnps/workorder.vue';
import teleRecords from './cnps/teleRecords.vue';
import knowledgeList from "@/views/main/knowledgeBase/knowledgeList/knowledgeList";
import useTagsViewStore from '@/store/modules/tagsView';

let { proxy } = getCurrentInstance()


const chat = ref(null);
const isCanAutoScroll = ref(1); // 是否可自动滚动，鼠标移入不可，移出可自动滚动
const showAiButton = ref(false);
const text = ref(null);
const dialogVisible = ref(false);

const aiLoading = ref(false);
const telNumber = ref(proxy.$route.params.callNumber || '来电弹屏');
console.log(proxy.$route, 'proxy.$route.query');

proxy.$route.meta.title = telNumber.value.toString();
onMounted(() => {
    useTagsViewStore().addView(proxy.$route);
    useTagsViewStore().addIframeView(proxy.$route)
});

// direction 1：坐席 2：客户
const chatData = ref([
    {
        direction: 1,
        page_content: '你好，中国热线请假。',
    }, {
        direction: 2,
        page_content: '喂，你好，嗯，听这样哦，我是林州这个横岛岳湖人呃',
    }, {
        direction: 1,
        page_content: '什么问题啊？你确实是无法统一工作呃，按照说实体上头到现在都没有工作了',
    }, {
        direction: 2,
        page_content: '我来问违约金怎么事儿？嗯，他说他他说是月底工资，',
    }, {
        direction: 1,
        page_content: '这个麻问您一下，我这边给您登记反映，您是林州市哪里的？',
    }, {
        direction: 2,
        page_content: '林州恒大悦府，恒大悦府',
    }, {
        direction: 1,
        page_content: '嗯，乐府乐是那个舒心一个舒心，一个对那个乐是吧？',
    }, {
        direction: 2,
        page_content: '嗯，对嗯',
    }, {
        direction: 1,
        page_content: '恒大乐府分几七部分啊，',
    }, {
        direction: 2,
        page_content: '分级，你们一期二期分不分呃，一期同大月付一期几号楼几单元，十七号楼一单元幺九零一十七号楼一单元幺九零一',
    }, {
        direction: 1,
        page_content: '嗯，您怎么称呼先生啊？',
    }, {
        direction: 2,
        page_content: '免贵？我就我我姓李李松，你让李先生吧',
    }, {
        direction: 1,
        page_content: '给您单心恒大悦府在林州市的哪个路段。您说一下',
    }, {
        direction: 2,
        page_content: '在这个这个是河南一个湖，也就他就一个湖，河南一个湖，我也不知道这个是什么路段',
    }, {
        direction: 1,
        page_content: '那您没有路段的话，这个位置不明确，我这边就暂不给您反映啊',
    }, {
        direction: 2,
        page_content: '嗯，那个是可能是那个呃华城相府，',
    }, {
        direction: 1,
        page_content: '哪个路段？',
    }, {
        direction: 2,
        page_content: '不是那个那个是呃鲁八大道，',
    }, {
        direction: 1,
        page_content: '鲁八大道中段什么大道，',
    }, {
        direction: 2,
        page_content: '鲁班哪两个字卢班鲁班嗯，',
    }, {
        direction: 1,
        page_content: '鲁班大道与什么路交叉口？',
    }, {
        direction: 2,
        page_content: '嗯，鲁班大道一零米，',
    }, 
    {
        direction: 1,
        page_content: '你们是是什么路来的，',
    }, {
        direction: 2,
        page_content: '你就说恒大悦府就行了。',
    }, {
        direction: 1,
        page_content: '那个那个零六就你一个恒大悦府必须哪个路段，',
    }, {
        direction: 2,
        page_content: '我们这边也得清楚，鲁班大鲁班大道开元街道，',
    }, {
        direction: 1,
        page_content: '恒大悦府是吗？',
    }, {
        direction: 2,
        page_content: '哦，对，康阳街道的嗯，',
    }, {
        direction: 1,
        page_content: '行好的，这边给您登记一下啊。',
    }, {
        direction: 2,
        page_content: '嗯，好了，不歉。',
    }, {
        direction: 1,
        page_content: '喂，哎，可以了。',
    }, {
        direction: 2,
        page_content: '呃',
    }, {
        direction: 1,
        page_content: '刚才我给你他们啊嗯已经给您登记了，稍后反应呃。',
    }, {
        direction: 2,
        page_content: '登登记了，你登记的，我是你知道我反映的什么吗？',
    }, {
        direction: 1,
        page_content: '你不是家中暖气没热吗？不热吗？',
    }, {
        direction: 2,
        page_content: '这不是不热，是没充暖，我给物业，我给物业联系了，物业，说是呃，他们这里公司就两个人，一共十七栋楼，他问他说这个还能等待几天一栋一栋的开呢，我们的我我们的供暖费都交了。',
    }, {
        direction: 2,
        page_content: '看他几天，你看他几天',
    }, {
        direction: 1,
        page_content: '你给我说个定是不是嗯就是人员少，担心无法正常供暖，是不是啊？',
    }, {
        direction: 2,
        page_content: '他说还得几天，你现在十五号都是显示统一功能。你到现在就你你说排了几天，还得几天的。',
    }, {
        direction: 1,
        page_content: '嗯，好的，这边已经有您同小弟业主反映过了，跟您跟他同甘办理啊。',
    }, {
        direction: 2,
        page_content: '嗯嗯，行好的。',
    }
]);

const form = ref({
    phoneNumber: telNumber.value,
});

const activeName = ref('user');
const orderTab = ref('order');

const scrollToBottom = () => {
    if (chat.value) {
        console.log(chat.value.scrollTop, chat.value.scrollHeight, 'chat');
        // chat.value.scrollTo(0, chat.value.scrollHeight);
        chat.value.scrollTop = chat.value.scrollHeight;
    }
}
watch(chatData, () => {
    nextTick(() => {
        if (isCanAutoScroll.value) scrollToBottom();
    }, 100)
}, {
    deep: true
})

const foldIconFlag = ref(false)
const foldIconTrue = ref(false)
const foldFlag = ref(true)
function foldHide() {
    foldFlag.value = false
    foldIconTrue.value = true
}
function foldshow() {
    foldFlag.value = true
    foldIconTrue.value = false
}
const chatMouse = (type) => {
    console.log(type)
    if (type === 0) {
        foldIconFlag.value = true
    }
    isCanAutoScroll.value = type;
}
function msgMouse() {
    foldIconFlag.value = false
}
const handleClick = () => {

}

let selectedText = ref('');

window.addEventListener('AsrMessageEvent', (msg) => {
    console.log(msg.detail, '接收asr消息');
    if (!msg?.detail || !msg.detail.Result) return;
    const msgInfo = {
        direction: msg.detail.Number.toString().length > 4 ? 2 : 1,
        page_content: msg.detail.Speech || '',
    };
    console.log(msgInfo, 'msgInfo');

    chatData.value.push(msgInfo);
})


const handleMouseUp = () => {
    const selected = window.getSelection();
    // console.log(selected, 'selectedText');
    if (selected && selected.toString().trim().length > 2) {
        // selectedText.value = selected.toString().trim();
        const rect = window.getSelection().baseNode.parentElement.getBoundingClientRect();
        let left = rect.left - 10;
        let top = rect.top - 70;
        // 判断文字有几行
        const lineNum = Math.ceil(selected.focusOffset / 24);
        top += lineNum * 22; // 22是行高
        // 判断起始位置文字字数
        left += ((selected.anchorOffset - 1) % 22) * 14; // 14是每个字的宽度
        
        const button = document.querySelector('.ai-button');
        console.log(rect, 'button');
        button.style.left = `${left}px`;
        button.style.top = `${top}px`;
        button.style.display = 'block';
        showAiButton.value = true;
    } else {
        showAiButton.value = false;
    }
};

const openAi = () => {
    const text = window.getSelection().toString().trim();
    if (!text || text.length < 2) return;
    selectedText.value = text;
    dialogVisible.value = true;
}

const aiSubmit = async () => {
    aiLoading.value = true;
    let text = chatData.value.map((o) => o.page_content).join('');
    if (text?.length > 10) {
        // 调用AI接口生成对应数据
        text += ',请讲上述聊天内容总计一下，输出标题、概要、事件地址、手机号、姓名';
        const res = await getSearchDocs(text);
        res.split('\n').forEach((o) => {
            if (o.startsWith('【标题】')) form.value.title = o.replace('【标题】', '');
            if (o.startsWith('【概要】')) form.value.description = o.replace('【概要】', '');
            if (o.startsWith('【事件地址】')) form.value.address = o.replace('【事件地址】', '');
            if (o.startsWith('【姓名】')) form.value.customerName = o.replace('【姓名】', '');
            
        })
        console.log(res, 'res');
        aiLoading.value = false;
    } else {
        aiLoading.value = false;
    }
}

async function getSearchDocs (text) {
    const params = {
        query: text,
        mode: "local_kb",
        kb_name: "mszsk",
        top_k: 1,
        score_threshold: 0.5,
        stream: true,
        model: "glm-4",
        temperature: 0.7,
        max_tokens: 0,
        prompt_name: "default",
        return_direct: false
    }
    try {
        // 发送请求
        let response = await fetch("http://192.168.1.40:7861/chat/kb_chat",
            {
                method: "post",
                // responseType: "stream",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(params),
            }
        );

        let resultStr = '';

        // ok字段判断是否成功获取到数据流
        if (!response.ok) {
            throw new Error("Network response was not ok");
        }
        // 用来获取一个可读的流的读取器（Reader）以流的方式处理响应体数据
        const reader = response.body.getReader();
        // 将流中的字节数据解码为文本字符串
        const textDecoder = new TextDecoder();
        let result = true;
        let sqlValue = ''

        while (result) {
            // done表示流是否已经完成读取  value包含读取到的数据块
            const { done, value } = await reader.read();
            if (done) {
                result = false;
                // console.log(resultStr, 'resultStr');
                return resultStr;
                break;
            }
            // 拿到的value就是后端分段返回的数据，大多是以data:开头的字符串
            // 需要通过decode方法处理数据块，例如转换为文本或进行其他操作
            const chunkText = textDecoder.decode(value).split("\n").forEach((val) => {
                if (!val) return;
                try {
                    // 后端返回的流式数据一般都是以data:开头的字符，排除掉data:后就是需要的数据
                    // 具体返回结构可以跟后端约定
                    let text = val?.replace("data:", "") || ""
                    const resultData = JSON.parse(text)
                    let resultText = resultData.choices[0].delta.content
                    
                    resultStr += resultText
                } catch (err) {
                    // console.log(err)
                }
            });
        }

    } catch (err) {
        console.log(err)

        return err;
    }

}

onUnmounted(() => {
    document.removeEventListener('mouseup', handleMouseUp);
});

onMounted(() => {
    document.addEventListener('mouseup', handleMouseUp);

    
    // scrollToBottom();
    // setInterval(() => {
    //     chatData.value.push({
    //         direction: 1,
    //         page_content: '好的，请问你具体想了解哪方面的问题呢？',
    //     })
    // }, 5000)
});

</script>


<style scoped lang="scss">
    /* 1.过渡动画 */
@keyframes axisX {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0px);
  }
}

/* 2. 过渡类名 */
/* 开始 */
.h1-enter-active {
  animation: axisX 0.2s;
}
/* 结束 */
.h1-leave-active {
  animation: axisX 0.2s reverse;
}

.main {
    display: flex;
    padding: 10px;
    height: 90vh;
    position: relative;
}
.foldIcon{
    background-color: #3D8EFF;
    border-radius:0 30px 30px 0;
    position: absolute;
    left: 383px;
    top: 50%;
    width: 15px;
    height: 30px;
    margin-top: -20px;
}
.foldIcon2{
    background-color: #3D8EFF;
    border-radius:0 30px 30px 0;
    position: absolute;
    left: 0px;
    top: 50%;
    width: 15px;
    height: 30px;
    margin-top: -20px;
}
.customer {
    min-height: 100px;
    width: 370px;
    padding: 10px;
    margin: 0px 5px;
    position: absolute;
    top: 10px;
    background-color: #f0f0f0;
}

.latest {
    min-height: 100px;
    width: calc(100% - 370px - 400px - 70px);
    padding: 10px;
    margin: 0px 5px;
    position: absolute;
    bottom: 10px;
    background-color: #f0f0f0;
}

.chat {
    width: 370px;
    margin: 0px 5px;
    padding: 10px;
    overflow-y: scroll;
    /* background-color: #f0f0f0; */
    background: url(data:image/png;base64,[encoded data, 90304 characters]) center center / 100% 100% no-repeat;


    .ai-conversation {
        .conversation_item {
            display: flex;

            .item_user {
                display: inline-block;
                margin-left: auto;
                width: auto;
                max-width: 640px;
                background: linear-gradient(89deg, #3D8EFF 0%, #7835FF 100%);
                border-radius: 16px 2px 16px 16px;
                margin-bottom: 24px;
                overflow: visible;
                white-space: normal !important;
                word-break: break-all !important;

                .aiHtml {
                    white-space: pre-wrap;
                    font-size: 14px;
                    color: #FFFFFF;
                    line-height: 22px;
                    padding: 8px 12px;
                    overflow: visible;
                    white-space: normal !important;
                    word-break: break-all !important;
                    position: relative;
                }
            }

            .item_ai {
                margin-right: auto;
                width: atuo;
                max-width: 640px;
                background: #ffffff;
                border-radius: 2px 16px 16px 16px;
                margin-bottom: 24px;

                .aiHtml {
                    white-space: pre-wrap;
                    font-size: 14px;
                    color: #1D2129;
                    line-height: 22px;
                    padding: 8px 12px;
                    overflow: hidden;
                    /* white-space: normal !important;
                    word-break: break-all !important; */
                }

                .tools-wrap {
                    position: relative;

                    .item-ai-tools {
                        display: flex;
                        -ms-flex-align: center;
                        align-items: center;
                        -ms-flex-pack: justify;
                        justify-content: space-between;
                        height: 20px;
                        margin-bottom: 8px;
                        font-family: PingFang SC, PingFang SC;
                        font-weight: 400;
                        font-size: 12px;
                        color: #86909C;
                        padding: 0 12px;

                        .tools-left {
                            display: flex;
                            -ms-flex-align: center;
                            align-items: center;
                            -ms-flex-pack: center;
                            justify-content: center;

                            .tool {
                                display: flex;
                                padding: 0 4px;
                                height: 20px;
                            }
                        }

                        .tools-right {
                            margin-left: 12px;
                            display: flex;

                            .pointer {
                                position: relative;
                                border-radius: 4px;

                            }
                        }
                    }
                }
            }
        }
    }

}



.middle {
    flex: 1;
    /* background-color: #e0e0e0; */
    margin: 0px 5px;
    padding: 10px;
    overflow-y: scroll;
}

.order {
    width: 400px;
    margin: 0px 5px;
    padding: 10px;
    overflow-y: scroll;
    position: relative;

    .button-container {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        text-align: center;
        padding: 10px;
    }
}

.ai-button {
  position: absolute;
  width: 30px;
  height: 30px;
  color: white;
  border: none;
  z-index: 9999999;
  cursor: pointer;
  transition: background-color 0.3s;
}

// .ai-button:hover {
//   background-color: red;
// }

.aiDialog{
    z-index: 2033;
    pointer-events: none;
    :deep(.el-dialog) {
      position: absolute;
      height: 700px;
      top: 50px;
      right: 0;
      margin: 0;
      left: unset;
      pointer-events: auto;
    }
  }
</style>