<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <div class="min-h-screen-nav-height bg-gray-50">
        <div class="container mx-auto px-4 pt-4 pb-6 flex gap-6">
            <!-- 左侧信息区 -->
            <div class="w-[35%]">
                <el-tabs type="border-card" class="h-full" @tab-change="tabChange">
                    <!-- 客户档案 -->
                    <el-tab-pane>
                        <template #label>
                            <div class="flex items-center">
                                <el-icon class="mr-2">
                                    <UserFilled />
                                </el-icon>
                                客户档案
                            </div>
                        </template>

                        <div class="space-y-4">
                            <div class="bg-white rounded-lg p-4 shadow-sm">
                                <div class="flex justify-between items-center mb-4">
                                    <h3 class="text-lg font-medium" @click="testPhone">基本信息</h3>
                                    <el-button type="primary" text :icon="Edit" @click="isEditing = !isEditing">
                                        {{ isEditing ? '保存' : '编辑' }}
                                    </el-button>
                                </div>
                                <div class="grid grid-cols-2 gap-4">
                                    <div class="flex flex-col">
                                        <span class="text-gray-500 text-sm">来电姓名</span>
                                        <template v-if="!isEditing">
                                            <span class="font-medium">{{ profile.name }}</span>
                                        </template>
                                        <template v-else>
                                            <el-input v-model="profile.name" size="small" class="w-full" />
                                        </template>
                                    </div>
                                    <div class="flex flex-col">
                                        <span class="text-gray-500 text-sm">客户性别</span>
                                        <template v-if="!isEditing">
                                            <span class="text-yellow-600 font-medium">{{ profile.sex !== '0' ?
                                                profile.sex === '1' ? '男' : '女' : '未知' }}</span>
                                        </template>
                                        <template v-else>
                                            <el-select v-model="profile.sex" size="small" class="w-full"
                                                @change="sexChange">
                                                <el-option label="男" value="1" />
                                                <el-option label="女" value="2" />
                                                <el-option label="未知" value="0" />
                                            </el-select>
                                        </template>
                                    </div>
                                    <div class="flex flex-col">
                                        <span class="text-gray-500 text-sm">创建时间</span>
                                        <span>{{ profile.registerDate }}</span>

                                        <!-- <template v-if="!isEditing">
                                            <span>{{ profile.registerDate }}</span>
                                        </template>
                                        <template v-else>
                                            <el-date-picker v-model="profile.registerDate" type="date" size="small"
                                                style="width: 100%" value-format="YYYY-MM-DD" />
                                        </template> -->
                                    </div>
                                    <!-- <div class="flex flex-col">
                                        <span class="text-gray-500 text-sm">最近联系</span>
                                        <template v-if="!isEditing">
                                            <span>{{ profile.lastContact }}</span>
                                        </template>
                                        <template v-else>
                                            <el-date-picker v-model="profile.lastContact" type="date" size="small"
                                                style="width: 100%" value-format="YYYY-MM-DD" />
                                        </template>
                                    </div> -->
                                </div>
                            </div>

                            <!-- 患者标签 -->
                            <div class="bg-white rounded-lg p-4 shadow-sm">
                                <h3 class="text-lg font-medium mb-2">患者标签</h3>
                                <div class="flex flex-wrap gap-2">
                                    <el-tooltip v-for="(tag, index) in customerTags" :key="index"
                                        :content="`${tag.createTime}`" effect="light" placement="top">
                                        <el-tag :color="tag.color || 'white'" effect="dark" size="small"
                                            class="opacity-90 !rounded-full">
                                            {{ tag.labelName }}
                                        </el-tag>
                                    </el-tooltip>
                                </div>
                            </div>

                            <!-- 联系方式 -->
                            <div class="bg-white rounded-lg p-4 shadow-sm">
                                <h3 class="text-lg font-medium mb-4">联系方式</h3>
                                <div class="space-y-3">
                                    <div class="flex items-center">
                                        <el-icon class="mr-2">
                                            <Phone />
                                        </el-icon>
                                        <span>{{ profile.phone }}</span>
                                    </div>
                                    <div class="flex items-center">
                                        <el-icon class="mr-2">
                                            <Location />
                                        </el-icon>
                                        <template v-if="!isEditing">
                                            <span>{{ profile.address }}</span>
                                        </template>
                                        <template v-else>
                                            <el-input v-model="profile.address" size="small" class="w-full" />
                                        </template>
                                    </div>
                                </div>
                            </div>

                            
                        </div>
                    </el-tab-pane>

                    <!-- 坐席助手 -->
                    <el-tab-pane v-if="showAsr">
                        <template #label>
                            <div class="flex items-center">
                                <el-icon class="mr-2">
                                    <Service />
                                </el-icon>
                                坐席助手
                            </div>
                        </template>
                        <div class="space-y-4">
                            <!-- 实时语音识别区域 -->
                            <h3 class="text-lg font-medium">语音识别</h3>
                            <div class="bg-white rounded-lg p-4 shadow-sm overflow-y-auto max-h-96 min-h-96">
                                <div class="flex justify-between items-center mb-4">
                                    <!-- <div class="flex items-center space-x-2">
                                        <el-tag :type="voiceStatus === 'active' ? 'success' : 'info'" size="small">
                                            {{ voiceStatus === 'active' ? '识别中' : '未开始' }}
                                        </el-tag>
                                    </div> -->
                                </div>
                                <div class="relative mb-4">
                                    <div class="absolute left-0 top-0 w-full h-16 bg-gradient-to-b from
from-white to-transparent pointer-events-none z-10"></div>
                                    <div ref="transcriptContainer" class="h-[500px] overflow-y-auto pr-4 space-y-3"
                                        @mouseenter="chatMouse(0)" @mouseleave="chatMouse(1)">
                                        <div v-for="(item, index) in transcripts" :key="index" class="p-3 rounded-lg"
                                            :class="[item.direction === 2 ? 'bg-blue-50' : 'bg-gray-50']">
                                            <div class="flex items-center mb-1">
                                                <span class="text-xs text-gray-500">{{ item.timestamp }}</span>
                                                <span class="text-xs font-medium ml-2"
                                                    :class="[item.direction === 2 ? 'text-blue-600' : 'text-gray-600']">
                                                    {{ item.direction === 2 ? '客户' : '坐席' }}
                                                </span>
                                                <div class="flex-1"></div>
                                                <!-- <el-tag size="small" effect="plain" class="ml-2"
                                                    :type="item.emotion === 'positive' ? 'success' : item.emotion === 'negative' ? 'danger' : 'info'">
                                                    {{ item.emotion === 'positive' ? '积极' : item.emotion === 'negative'
                                                    ? '消极' : '中性' }}
                                                </el-tag> -->
                                            </div>
                                            <p class="text-sm text-gray-700">{{ item.page_content }}</p>
                                        </div>
                                    </div>
                                    <div
                                        class="absolute left-0 bottom-0 w-full h-16 bg-gradient-to-t from-white to-transparent pointer-events-none">
                                    </div>
                                </div>

                            </div>

                            <!-- 关键词提示 -->
                            <div class="space-y-2" v-if="keywords.length > 0">
                                <h4 class="font-medium text-sm text-gray-600">关键词提示</h4>
                                <div class="flex flex-wrap gap-2">
                                    <el-tag v-for="(keyword, idx) in keywords"
                                        class="relative transition-transform duration-300 ease-in-out hover:scale-105"
                                        :key="idx" :type="keyword.type" effect="plain" size="small"
                                        @click="getKnowledgeBaseList(keyword.text)">
                                        {{ keyword.text }}
                                        <span v-if="keyword.count > 1"
                                            class="absolute -top-1 -right-1 bg-blue-500 text-white text-[10px] rounded-full w-4 h-4 flex items-center justify-center">
                                            {{ keyword.count }}
                                        </span>
                                    </el-tag>
                                </div>
                            </div>
                            <!-- 推荐知识 -->
                            <div class="mt-4 space-y-4" v-if="recommendedKnowledge.length > 0">
                                <h4 class="font-medium text-sm text-gray-600">推荐知识</h4>
                                <div class="space-y-4">
                                    <div v-for="(item, idx) in recommendedKnowledge" :key="idx"
                                        class="p-4 bg-white rounded-lg shadow-sm hover:shadow-md transition-all cursor-pointer">
                                        <div class="flex items-center justify-between mb-2">
                                            <h5 class="font-medium" @click="openKnowledgeAi(item.docId)">{{ item.title
                                                }}</h5>
                                            <el-tag size="small" type="default">{{ item.directoryname }}</el-tag>
                                        </div>
                                        <p class="text-sm text-gray-600 line-clamp-2 mb-2">{{
                                            stripHtmlByRegex(item.content) }}</p>
                                        <div class="flex items-center justify-between text-xs text-gray-500">
                                            <span>发布时间：{{ item.createTime }}</span>
                                            <!-- <span>阅读：{{ item.reads }}</span> -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- 问卷 -->
                    <!-- <el-tab-pane>
                        <template #label>
                            <div class="flex items-center">
                                <el-icon class="mr-2">
                                    <DocumentAdd />
                                </el-icon>
                                问卷填报
                            </div>
                        </template>
                        <survey :callid="callid" :phone="telNumber" ref="surveyRef" @setVisit="setOrderVisitStatus"/>
                    </el-tab-pane> -->

                    <!-- 通话记录 -->
                    <el-tab-pane>
                        <template #label>
                            <div class="flex items-center">
                                <el-icon class="mr-2">
                                    <Document />
                                </el-icon>
                                通话记录
                            </div>
                        </template>
                        <div class="space-y-4">
                            <!-- <el-input v-model="workOrderSearchQuery" placeholder="搜索工单..." :prefix-icon="Search" /> -->
                            <el-date-picker v-model="callSearchQuery" type="datetimerange" @change="callChange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                            <div class="space-y-2 overflow-y-auto" style="height: 100%;" ref="callContainer"
                                @scroll="handleCallScroll">
                                <div v-for="(item, index) in callData" :key="index"
                                    class="bg-white p-3 rounded-lg shadow-sm hover:shadow-md transition-shadow mb-4 border border-gray-100">
                                    <div class="flex justify-between items-start">
                                        <div>
                                            <!-- <h4 class="font-medium">{{ getOfffixNuber(item.callType==1 ? item.caller : item.callee) }}</h4> -->
                                            <div class="flex items-center gap-2 mt-1">
                                                <span v-if="item.callerAgent || item.calleeAgent"
                                                    style="margin-right: 15px;">
                                                    坐席工号：{{ item.callType == 2 ? item.callerAgent : item.calleeAgent }}
                                                </span>
                                                <span v-if="item.caller || item.callee">
                                                    分机号：{{ item.callType == 2 ? item.caller : item.callee }}
                                                </span>

                                            </div>
                                        </div>
                                        <span class="text-xs text-gray-500">{{ getCallSate(item.callType, item.isAnswer)
                                            }}</span>
                                    </div>
                                    <div class="text-sm text-gray-600 my-2 cursor-pointer">
                                        <div v-if="item.answerTime">通话开始时间：{{ item.answerTime }}</div>
                                        <div v-if="item.hangupTime">通话结束时间：{{ item.hangupTime }}</div>
                                        <div v-if="item.answerTime && item.hangupTime">
                                            通话时长：{{ getTimeLimit(item.answerTime,
                                            item.hangupTime) }}</div>
                                    </div>
                                </div>
                                <div v-if="callLoading" class="flex justify-center items-center py-4">
                                    <el-icon class="animate-spin mr-2">
                                        <Loading />
                                    </el-icon>
                                    加载中...
                                </div>
                                <div v-if="callNoMore" class="text-center text-gray-500 py-4">没有更多数据了</div>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- 历史工单 -->
                    <el-tab-pane>
                        <template #label>
                            <div class="flex items-center">
                                <el-icon class="mr-2">
                                    <Document />
                                </el-icon>
                                历史工单
                            </div>
                        </template>
                        <div class="space-y-4">
                            <el-date-picker v-model="orderSearchQuery" type="datetimerange" @change="orderChange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                            <!-- <el-input v-model="workOrderSearchQuery" placeholder="搜索工单..." :prefix-icon="Search" /> -->
                            <div class="space-y-2 overflow-y-auto" style="height: 100%;" ref="workOrderContainer"
                                @scroll="handleScroll">
                                <div v-for="(item, index) in displayedActivities" :key="index"
                                    class="bg-white p-3 rounded-lg shadow-sm hover:shadow-md transition-shadow mb-4 border border-gray-100">
                                    <div class="flex justify-between items-start">
                                        <div>
                                            <h4 class="font-medium">{{ item.workordercatename ?
                                                item.workordercatename.substring(item.workordercatename.lastIndexOf('/')
                                                + 1) : '' }}</h4>
                                            <!-- <div class="flex items-center gap-2 mt-1">
                                                <el-tag size="small" type="info" class="!rounded-full">{{ item.workordercatename }}</el-tag>
                                            </div> -->
                                        </div>
                                        <span class="text-xs text-gray-500">{{ item.createtime }}</span>
                                    </div>
                                    <div class="text-sm text-gray-600 my-2 cursor-pointer" :class="{
                                        'line-clamp-2': !item.expanded || activeWorkOrder !== index
                                    }" @click="() => {
                                        activeWorkOrder = activeWorkOrder === index ? -1 : index;
                                        item.expanded = !item.expanded;
                                    }">{{ item.content }}</div>
                                    <template v-if="item.result">
                                        <div class="mt-2 border-t pt-2">
                                            <div class="flex items-center justify-between text-sm text-gray-600 mb-2">
                                                <div class="flex items-center">
                                                    <!-- <el-icon class="mr-1">
                                                        <Document />
                                                    </el-icon> -->
                                                    <span>办理结果</span>
                                                    <span class="text-gray-400 ml-2">{{ item.endtime ?
                                                        `[${item.endtime}]` : '' }}</span>
                                                </div>
                                                <!-- <div class="text-gray-400">处理部门：{{ item.department || '客服部' }}</div> -->
                                            </div>
                                            <div class="flex">
                                                <div class="w-1 bg-gray-200 mr-2"></div>
                                                <div class="flex flex-col space-y-2">
                                                    <div class="text-sm text-gray-500 cursor-pointer" :class="{
                                                        'line-clamp-2': !item.expanded || activeWorkOrder !== index
                                                    }" @click="() => {
                                                        activeWorkOrder = activeWorkOrder === index ? -1 : index;
                                                        item.expanded = !item.expanded;
                                                    }">{{ item.result }}</div>
                                                </div>
                                            </div>
                                        </div>
                                    </template>
                                    <!-- <div class="flex items-center mt-2">
                                        <el-tag :type="getTagType(item.type)" size="small">{{ getStatusText(item.type)
                                            }}</el-tag>
                                    </div> -->
                                </div>
                                <div v-if="loading" class="flex justify-center items-center py-4">
                                    <el-icon class="animate-spin mr-2">
                                        <Loading />
                                    </el-icon>
                                    加载中...
                                </div>
                                <div v-if="noMore" class="text-center text-gray-500 py-4">没有更多数据了</div>
                            </div>
                        </div>
                    </el-tab-pane>
                    <!-- 知识库 -->
                    <el-tab-pane>
                        <template #label>
                            <div class="flex items-center">
                                <el-icon class="mr-2">
                                    <Search />
                                </el-icon>
                                知识库
                            </div>
                        </template>
                        <div class="space-y-4">
                            <knowledge-list :toExamine="2" :isSreen="1"></knowledge-list>
                            <!-- <el-input v-model="searchQuery" placeholder="搜索解决方案..." :prefix-icon="Search" />
                            <div class="space-y-2">
                                <div v-for="(item, index) in knowledgeBase" :key="index"
                                    class="bg-white p-3 rounded-lg shadow-sm hover:shadow-md transition-shadow cursor-pointer">
                                    <h4 class="font-medium">{{ item.title }}</h4>
                                    <p class="text-sm text-gray-600 mt-1">{{ item.description }}</p>
                                </div>
                            </div> -->
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <!-- 右侧工单区 -->
            <div class="w-[65%] space-y-6">
                <div class="bg-white rounded-lg p-6 shadow-sm">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-medium">工单信息</h2>

                        <el-button :loading-icon="Eleme" v-if="showAI && showAsr" class="flex items-center gap-1"
                            type="primary" link @click="aiSubmit" :loading="aiLoading">智能填单</el-button>
                    </div>

                    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="来电姓名" required prop="name">
                                    <el-input v-model="form.name" placeholder="请输入来电姓名" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="联系电话" required prop="phone">
                                    <el-input v-model="form.phone" placeholder="请输入联系电话" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="年龄">
                                    <el-input v-model="form.age" type="number" placeholder="请输入年龄"
                                        @input="updateAgeGroup" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="年龄分段">
                                    <!-- <el-input v-model="form.ageGroup" /> -->
                                    <el-select v-model="form.ageGroup" placeholder="请选择年龄分段" class="w-full">
                                        <el-option v-for="item in ageGroupOptions" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>

                            </el-col>
                        </el-row>
                        <el-row :gutter="20">

                            <el-col :span="12">
                                <el-form-item label="性别">
                                    <el-select v-model="form.sex" placeholder="请选择性别" class="w-full" clearable
                                        @change="sexChange">
                                        <el-option key="0" value="0" label="未知" />
                                        <el-option key="1" value="1" label="男" />
                                        <el-option key="2" value="2" label="女" />
                                    </el-select>
                                </el-form-item>

                            </el-col>
                        </el-row>
                        <el-form-item label="所在地区">
                            <el-cascader v-model="form.area" :options="areaTree"
                                :props="{ value: 'id', checkStrictly: true, }" placeholder="请选择所在地区" filterable
                                clearable class="w-full" />
                        </el-form-item>
                        <el-form-item label="详细地址">
                            <el-input v-model="form.address" type="textarea" :rows="2" placeholder="请输入详细地址（如街道、门牌号等）"
                                class="w-full" />
                        </el-form-item>

                        <el-form-item label="工单类型" required prop="type">
                            <el-cascader ref="typeCascaderRef" class="w-full" v-model="form.type"
                                :props="{ value: 'id', }" placeholder="请选择工单类型" :options="ticketTypes" filterable
                                clearable @change="handleTypeChange" />
                        </el-form-item>
                        <el-form-item v-if="form.typeCode === 'complain'" label="投诉部门" required prop="department">
                            <!-- <el-select v-model="form.department" placeholder="请选择投诉部门" class="w-full">
                                <el-option v-for="item in departments" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select> -->
                            <el-cascader ref="deptCascaderRef" class="w-full" v-model="form.department"
                                :props="{ checkStrictly: true }" placeholder="请选择投诉科室" :options="departments" filterable
                                @change="deptChange" />
                        </el-form-item>
                        <el-form-item label="问题描述" required prop="description">
                            <el-input v-model="form.description" type="textarea" :rows="4" maxlength="2000"
                                placeholder="请详细描述问题（最多2000字）" show-word-limit />
                        </el-form-item>
                        <el-form-item label="干预建议" prop="suggest">
                            <el-input v-model="form.suggest" type="textarea" :rows="4" placeholder="请输入干预建议（最多2000字）"
                                maxlength="2000" show-word-limit />
                        </el-form-item>

                        <el-form-item label="处理措施" prop="handlingMeasures">
                            <el-select v-model="form.handlingMeasures" multiple filterable placeholder="请选择处理措施"
                                class="w-full">
                                <el-option v-for="item in order_handling_measures" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="是否需要回访">
                            <el-switch v-model="form.isNeedVisit" @change="handleNeedVisitChange" />
                        </el-form-item>
                        <!-- <el-form-item label="优先级">
                            <el-radio-group v-model="form.priority">
                                <el-radio-button label="high">高</el-radio-button>
                                <el-radio-button label="medium">中</el-radio-button>
                                <el-radio-button label="low">低</el-radio-button>
                            </el-radio-group>
                        </el-form-item> -->
                        <el-form-item label="标记">
                            <el-cascader ref="labelCascaderRef" class="w-full" v-model="form.tag"
                                :props="{ label: 'dictLabel', value: 'dictValue', multiple: true }" placeholder="请选择标签" :options="labels" filterable
                                @change="labelChange" />
                        </el-form-item>
                        <el-form-item label="处理方式" required prop="handleMethod">
                            <el-select v-model="form.handleMethod" placeholder="请选择处理方式"
                                :disabled="form.handleMethod === '2'" class="w-full" @change="handleMethodChange">
                                <el-option v-for="item in handleMethods" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="备注">
                            <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
                        </el-form-item> -->
                        <!-- 悬浮提交按钮 -->
                        <div class="bottom-0 left-0 right-0 p-4 bg-white border-t flex justify-end">
                            <el-button type="primary" class="w-32 !rounded-button whitespace-nowrap"
                                @click="submit">提交工单</el-button>
                        </div>
                    </el-form>

                </div>

            </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="400"
                :style="{ 'background': 'url(' + base64data.aiBG + ') center center / 100% 100% no-repeat' }" draggable>
                <ai-dialog :knowledgeId="selectKnowledgeId"></ai-dialog>
            </el-dialog>
        </div>

        <div class="container mx-auto px-4 py-8">
            <button @click="toggleDrawer" :class="[
                'fixed transition-all duration-300 py-4 bg-blue-600 text-white !rounded-button whitespace-nowrap writing-vertical-rl hover:bg-blue-700 hover:shadow-lg hover:-translate-x-1 top-1/2 -translate-y-1/2',
                'px-2 rounded-l-xl rounded-r-none'
            ]" :style="{
                right: drawerOpen ? '500px' : '0px',
                'z-index': 999
            }">
                <!-- <el-icon class="mb-2 transition-transform" :class="{ 'rotate-180': drawerOpen }">
                    <ArrowRight />
                </el-icon> -->
                {{ drawerOpen ? '关闭问卷调查' : '问卷调查' }}
            </button>

            <el-drawer v-model="drawerOpen" :z-index="998" :modal="false" direction="rtl" size="500px">
                <survey :callid="callid" :phone="telNumber" ref="surveyRef" @setVisit="setOrderVisitStatus"></survey>
            </el-drawer>
        </div>
    </div>
</template>
<script lang="ts" setup name="CallScreen">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import moment from 'moment';
import { findKeyword } from '@/utils/trie';
import { base64data } from '@/utils/baseUrlData'
import aiDialog from '@/components/main/Navbar/cpns/aiDialog/aiDialog.vue'
import { uniq } from 'lodash';

import {
    UserFilled,
    Phone,
    Message,
    Location,
    Document,
    Search,
    Timer,
    Switch,
    Service,
    CircleClose,
    Operation,
    Close,
    VideoCamera,
    Microphone,
    Connection,
    List,
    Notebook,
    Edit,
    Eleme,
    Loading
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import useSelectStore from '@/store/commonSelect/common';
import useKeysStore from '@/store/modules/keys'
import { getPageListData, createPageData } from '@/api/main/system/system';
import { userDecryptToAsterisk } from '@/utils/aes';
import knowledgeList from "@/views/main/knowledgeBase/knowledgeList/cpns/konwlegelist/konwlegelist";
import survey  from './cnps/survey';

import { flatten } from 'lodash';
import { getOfffixNuber, getCallSate } from '@/utils/index';
import { stripHtmlByRegex, formatMilliseconds } from '@/utils/tools';

const router = useRouter()
let { proxy } = getCurrentInstance()
const aiLoading = ref(false);
const isCanAutoScroll = ref(1);
const dialogVisible = ref(false);
const surveyRef = ref(null);

const showAsr = ref(import.meta.env.VITE_APP_AI_ASR === 'true');
const showAI = ref(import.meta.env.VITE_APP_AI_SEARCH === 'true');
const telNumber = ref(proxy.$route.query.phone || proxy.$route.query.callNumber || proxy.$route.params.callNumber);
proxy.$route.meta.title = telNumber.value || '来电弹屏';
const callid = ref(proxy.$route.query.callid || 0);

const createLog = (content = '') => {
    createPageData('/ai/aioperation', {
        operateType: 'ASR',
        operationContent: content,
    }).then(() => {

    }).catch(() => {

    })
}

if (callid.value) createLog('callid');

const workOrderSearchQuery = ref('');
const activeWorkOrder = ref(-1);
const currentPage = ref(1);
const pageSize = ref(10);
const displayedActivities = ref<any[]>([]);
const loading = ref(false);
const noMore = ref(false);
const pageIndex = ref(1);
const workOrderContainer = ref<HTMLElement | null>(null);
const callContainer = ref(null)
const loadMoreData = async () => {
    if (loading.value || noMore.value) return;
    loading.value = true;
    await new Promise(resolve => setTimeout(resolve, 500)); // 模拟加载延迟
    const res = await getWorkOrders();
    if (res?.length === 0) {
        noMore.value = true;
    } else {
        pageIndex.value++;
    }
    loading.value = false;
};
const handleScroll = async (event: Event) => {
    const target = event.target as HTMLElement;
    const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
    console.log(scrollBottom)
    if (scrollBottom < 50) {
        await loadMoreData();
    }
};
// 通话记录开始
const callData = ref([])
const callLoading = ref(false)
const callNoMore = ref(false);
const loadMoreCallData = async () => {
    if (callLoading.value || callNoMore.value) return;
    callLoading.value = true;
    // await new Promise(resolve => setTimeout(resolve, 500)); // 模拟加载延迟
    const res = await getCalllog();
    console.log(res, 'res')
    if (res?.length === 0) {
        callNoMore.value = true;
    } else {
        // displayedActivities.value.push(...newItems);
        callPageIndex.value++;
    }
    callLoading.value = false;
};

const updateAgeGroup = () => {
  const age = parseInt(form.value.age);
  if (!age || isNaN(age)) {
    form.value.ageGroup = '未知';
  } else if (age < 18) {
    form.value.ageGroup = '青少年';
  } else if (age < 55) {
    form.value.ageGroup = '中年';
  } else {
    form.value.ageGroup = '老年';
  }
};

const saveTranslate = (callid, translate) => {
    console.log(callid, translate, 'adsfasdf--1')
    if (!translate || !translate.length || !callid || !showAsr) return;
    createPageData('/call/translate', {
        callid,
        translateJson: JSON.stringify(translate),
    }).then(() => {

    }).catch(() => {

    })
}

const handleNeedVisitChange = (val) => {
    // if (val) form.value.handleMethod = '2';
    // else form.value.handleMethod = '1';
}

const handleMethodChange = (val) => {
    console.log(val, 'val')
    // if (val === '2') form.value.isNeedVisit = true;
    // else form.value.isNeedVisit = false;
}

const handleCallScroll = async (event: Event) => {
    const target = event.target as HTMLElement;
    const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
    console.log(scrollBottom)
    if (scrollBottom < 50) {
        await loadMoreCallData();
    }
};
const callPageSize = ref(10)
const callPageIndex = ref(1)
const callSearchQuery = ref()
const callAnswerTime = ref()
const callHangupTime = ref()
function callChange(e) {
    console.log(e)
    if (e.length > 0) {
        callAnswerTime.value = moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
        callHangupTime.value = moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
    }
    callPageIndex.value = 1
    callData.value = []
    getCalllog()

}
const getCalllog = async () => {
    if (!telNumber.value) return;
    const params: any = {
        phone: telNumber.value,
        pageSize: callPageSize.value,
        pageNum: callPageIndex.value,
    }
    if (callAnswerTime.value) {
        params.answerTime = callAnswerTime.value
    }
    if (callHangupTime) {
        params.hangupTime = callHangupTime.value
    }
    const result = await getPageListData('/call/calllog', params);
    console.log(result, 'callData');
    if (result.state === 'success') {
        callData.value = callData.value.concat(result.data)
        if (callData.value.length === 0) {
            callNoMore.value = true;
        } else {
            callNoMore.value = false;
        }
        return result.data;
    }
    return [];
}
function getTimeLimit(startTime, endTime) {
    return proxy.getTimeDifference(startTime, endTime);
}
// 通话记录结束
onMounted(() => {
    getLabelsTree();
    transcripts.value = [];
    getUserInfo();
    loadMoreData();
    loadMoreCallData();
    getLabels();
    if (callid.value) window.addEventListener(`AsrMessageEvent-${callid.value}`, dealAsrMessage)
});
const activities = ref([]);
const getTagType = (type: string) => {
    const typeMap: { [key: string]: string } = {
        primary: '',
        success: 'success',
        warning: 'warning',
        info: 'info',
        danger: 'danger'
    };
    return typeMap[type] || '';
};

const ageGroupOptions = [{
    value: '青少年',
    label: '青少年'
}, {
    value: '中年',
    label: '中年'
}, {
    value: '老年',
    label: '老年'
}, {
    value: '未知',
    label: '未知'
}];

const { order_handling_measures} = proxy.useDict(
    'order_handling_measures',
)


const getStatusText = (type: string) => {
    const statusMap: { [key: string]: string } = {
        primary: '处理中',
        success: '已完成',
        warning: '待处理',
        info: '已完成',
        danger: '已取消'
    };
    return statusMap[type] || '';
};
const knowledgeBase = [];
const isEditing = ref(false);
const profile = ref({
    name: '-',
    sex: '0',
    registerDate: '',
    // lastContact: '',
    phone: '',
    tel: '',
    // email: 'zhaomq@example.com',
    address: ''
});
const formRef: any = ref(null);
const form = ref({
    tag: [],
    ageGroup: '',
    age: '',
    area: '',
    address: '',
    suggest: '',
    sex: '0',
    isNeedVisit: false,
    name: '不详',
    phone: '',
    type: '',
    typeCode: '',
    description: '',
    // priority: 'medium',
    handleMethod: '1',
    // remarks: '',
    department: '',
    handlingMeasures: [],
});
const rules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        // { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择工单类型', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入问题描述', trigger: 'blur' },
        { min: 5, max: 2000, message: '问题描述5-2000个字符', trigger: 'blur' },
    ],
    suggest: [
        // { required: true, message: '请输入问题描述', trigger: 'blur' },
        { min: 5, max: 2000, message: '干预建议5-2000个字符', trigger: 'blur' },
    ],
    handleMethod: [
        { required: true, message: '请选择处理方式', trigger: 'change' }
    ],
};

const ticketTypes = useSelectStore().dictOrderTypeList;
const departments = useSelectStore().deptListData;
const areaTree = useSelectStore().areaTree;
const handleMethods = [
    { label: '立即完结', value: '1' },
    { label: '待交办', value: '0' },
    // { label: '待回访', value: '2' },
    // { label: '转专员处理', value: 'transfer' },
    // { label: '现场支持', value: 'onsite' }
];

const getUserInfo = async () => {
    if (!telNumber.value) {
        return;
    }
    telNumber.value = getOfffixNuber(telNumber.value)
    profile.value.phone = telNumber.value;
    form.value.phone = telNumber.value;
    

    const userResult = await getPageListData('/patient/patient', { phoneNumber: telNumber.value });
    console.log(userResult);
    if (userResult?.data?.length) {
        const userInfo = userResult.data[0];
        profile.value = {
            name: userInfo.name,
            registerDate: userInfo.createTime,
            phone: userDecryptToAsterisk(userInfo.phoneNumber),
            address: userInfo.address,
            sex: (userInfo.sex || 0) + '',
            tel: userDecryptToAsterisk(userInfo.tel),
        };

        form.value.sex = (userInfo.sex || 0) + '';

        form.value.name = userInfo.name;
    }
}

const typeCascaderRef: any = ref(null);

const handleTypeChange = (value) => {
    if (typeCascaderRef.value) {
        const selectNode = typeCascaderRef.value.getCheckedNodes();
        form.value.typeCode = selectNode[selectNode.length - 1].data.code;
    }
}

// 投诉部门切换
const deptCascaderRef: any = ref(null);
const deptChange = (value) => {
    // if (deptCascaderRef.value) {
    //     const selectNode = deptCascaderRef.value.getCheckedNodes()[0];
    //     form.value.department = selectNode.data.label;
    // }
}

const labelChange = (value) => {

}

const resetForm = () => {
    form.value = {
        ageGroup: '',
        age: '',
        area: '',
        address: '',
        suggest: '',
        isNeedVisit: false,
        name: '',
        phone: '',
        type: '',
        typeCode: '',
        description: '',
        handleMethod: '1',
        department: '',
    };
    formRef.value.resetFields();
}

const submit = async () => {
    // 验证表单必填项
    formRef.value.validate(async (valid) => {
        if (valid) {
            const params: any = {
                caller: form.value.name,
                callnum: form.value.phone,
                content: form.value.description,
                customerno: form.value.phone,
                firsttype: 1000,
                isend: +form.value.handleMethod,
                sex: form.value.sex || '0',
                workordercate: form.value.type[form.value.type.length - 1],
            };
            if (callid.value) params.callId = callid.value;

            if (keywords.value.length > 0 && callid.value && showAsr) {
                saveTranslate(callid.value, keywords.value);
            }

            if (form.value.area) {
                params.area = form.value.area ? form.value.area[form.value.area.length - 1] : '';
            }

            if (form.value.address) params.address = form.value.address;
            if (form.value.age) params.age = form.value.age;
            if (form.value.ageGroup) params.ageGroup = form.value.ageGroup;
            if (form.value.suggest) params.suggest = form.value.suggest;
            params.isNeedVisit = form.value.isNeedVisit ? 1 : 0;

            const tags = [];
            if (surveyRef.value) {
                const warnings = surveyRef.value.getWarnSurvey();
                const warnInfos = [];
                for (let index = 0; index < warnings.length; index++) {
                    const info = warnings[index];
                    if (info.callId === params.callId) {
                        warnInfos.push({
                            sheetId: info.sheetId,
                            surveyId: info.surveyId,
                            totalScore: info.totalScore,
                        });
                        console.log(info.tagSign, 'info.tagSign');
                        if (info.tagSign) {
                            tags.push(info.tagSign);
                        }
                        
                    }
                }

                if (warnInfos?.length) {
                    params.warnInfos = warnInfos;
                    // params.isNeedVisit = 1;
                    // params.isYj = 1;
                }
            }
            console.log(form.value.handlingMeasures, 'submit');
            if (form.value.handlingMeasures?.length) params.handlingMeasures = form.value.handlingMeasures.join(',');

            if ((form.value.tag && form.value.tag.length) || tags.length) {
                console.log(tags, form.value.tag, 'form.value.tag');
                // params.tag = form.value.tag.map((o) => o[o.length - 1]).join(',');
                const formTags = form.value.tag.map((o) => o[o.length - 1]) || [];
                params.tag = uniq(formTags.concat(tags)).join(',');
            }
            console.log(params,  form.value.tag,'submit');
            // return;
            // 提交表单
            createPageData('/order/workorder', params).then((data) => {
                console.log(data, 'submit');
                if (data.state === 'success') {
                    ElMessage.success('提交成功');
                    transcripts.value = []

                    unListenerEvent();

                    resetForm()
                    close()
                } else {
                    ElMessage.error(data.message || '提交失败');
                }

            })

        } else {
            ElMessage.error('请填写完整信息');
        }

    });
}
/** 关闭按钮 */
function close() {
    const obj = { path: '/' }
    proxy.$tab.closeOpenPage(obj)
}
const orderSearchQuery = ref()
const createtime = ref()
const endtime = ref()

function orderChange(e) {
    console.log(e)
    if (e.length > 0) {
        createtime.value = moment(e[0]).format('YYYY-MM-DD HH:mm:ss')
        endtime.value = moment(e[1]).format('YYYY-MM-DD HH:mm:ss')
    }
    pageIndex.value = 1
    displayedActivities.value = []
    getWorkOrders()
}
const getWorkOrders = async () => {
    if (!telNumber.value) return;
    const params: any = {
        listType: 0,
        callnum: telNumber.value,
        pageSize: pageSize.value,
        pageNum: pageIndex.value,
    }
    if (createtime.value) {
        params.createtime = createtime.value
    }
    if (endtime.value) {
        params.endtime = endtime.value
    }
    const result = await getPageListData('/order/workorder', params);
    console.log(result, 'getWorkOrders');
    if (result.state === 'success') {
        displayedActivities.value = displayedActivities.value.concat(result.data)
        console.log(displayedActivities.value, 'activities');
        if (displayedActivities.value.length === 0) {
            noMore.value = true;
        } else {
            noMore.value = false;
        }
        return result.data;
    }
    return [];
}

const tabChange = (name) => {
    console.log(name, 'tabChange');
    if (name === '1') {
        pageIndex.value = 1
        callPageIndex.value = 1
        callData.value = []
        getCalllog();
    } else if (name === '2') {
        pageIndex.value = 1
        displayedActivities.value = []
        getWorkOrders();
    }

}


// 语音识别状态
const voiceStatus = ref('active');
// 识别记录

const transcripts: any = ref([
    // {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '你好，中国热线请假。',
])
// 关键词提示
const keywords: any = ref([
    // {
    //     text: '强迫症',
    //     type: 'primary',
    //     count: 0,
    // },

]);
// 建议话术
const suggestions = ref([
    '很高兴能帮到您，如果还有其他问题随时询问',
    '这个功能确实很实用，您可以根据实际需求来调整配置',
    '感谢您的正面反馈，我们会继续努力提供更好的服务',
    '建议您也可以查看我们的帮助文档，里面有更详细的使用说明'
]);
const transcriptContainer = ref<HTMLElement | null>(null);
// 监听新消息，自动滚动到底部
// 监听新消息和内容变化，自动滚动到底部
// watch(
//     [
//         () => transcripts.value.length,
//         () => transcripts.value.map(t => t.page_content)
//     ],
//     () => {
//         nextTick(() => {
//             console.log(transcriptContainer.value, 'transcriptContainer');
//             if (transcriptContainer.value) {
//                 transcriptContainer.value.scrollTop = transcriptContainer.value.scrollHeight;
//             }
//         });
//     },
//     { deep: true }
// );
const dealAsrMessage = (msg: any) => {
    console.log(msg.detail, '接收asr消息');
    if (!showAsr) return;
    if (!msg?.detail || !msg.detail.Result) return;
    const msgInfo = {
        direction: msg.detail.Number.toString().length > 4 ? 2 : 1,
        page_content: msg.detail.Speech || '',
        timestamp: '',
    };
    console.log(msg.detail.Time, 'msgInfo');
    if (msg.detail.Time) {
        const times = JSON.parse(msg.detail.Time);

        console.log(times, 'msgInfo');
        if (times?.length) {
            const time = flatten(times)?.[0];
            if (time) msgInfo.timestamp = formatMilliseconds(time);
        }
    }

    console.log(msgInfo, 'msgInfo');
    if (msgInfo.page_content.length > 2) checkKeys(msgInfo.page_content);
    transcripts.value.push(msgInfo);
}



// function formatMilliseconds(milliseconds) {
//     const totalSeconds = Math.floor(milliseconds / 1000);
//     const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0');
//     const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0');
//     const seconds = (totalSeconds % 60).toString().padStart(2, '0');
//     return `${minutes}:${seconds}`;
// }

const aiSubmit = async () => {
    aiLoading.value = true;
    let text = transcripts.value.map((o) => {
        if (o.direction === 1) return `[坐席]` + o.page_content + '\n';
        return `[患者]` + o.page_content + '\n';

    }).join('');
    if (text?.length > 10) {
        let res = await getSearchDocs(text);
        console.log(res, 'res-1');
        res = res.replace(/<think>[\s\S]*?<\/think>/g, '');
        console.log(res, 'res-2');

        res.split('\n').forEach((o) => {
            console.log(o, 'o');
            if (o.startsWith('【内容总结】')) form.value.description = o.replace('【内容总结】', '').replace('：', '');
            if (o.startsWith('【详细地址】')) form.value.address = o.replace('【详细地址】', '').replace('：', '');
            if (o.startsWith('【姓名】')) form.value.name = o.replace('【姓名】', '').replace('：', '');
            if (o.startsWith('【干预建议】')) form.value.suggest = o.replace('【干预建议】', '').replace('：', '');
            if (o.startsWith('【年龄】')) {
                const age = o.replace('【年龄】', '').replace('：', ''); 
                if (age && !isNaN(age)) {
                    form.value.age = age;
                    updateAgeGroup();
                }
            }
            if (o.startsWith('【是否需要回访】')) {
                const result = o.replace('【是否需要回访】', '').replace('：', '');
                if (result === '是') form.value.isNeedVisit = true;
            }

        })

        aiLoading.value = false;

    } else {
        aiLoading.value = false;
    }
}

const unListenerEvent = () => {
    if (callid.value) window.removeEventListener(`AsrMessageEvent-${callid.value}`, dealAsrMessage)
}

onUnmounted(() => {
    console.log('onUnmounted-phone');
    unListenerEvent();
});
async function getSearchDocs(text) {
    const params = {
        "model": "deepseek-r1:32b",
        "messages": [
            {
                "role": "user",
                "content": `${text} 
                请从上述对话内容中提取关键信息按照示例输出格式生成结构化工单：
地理位置提取：识别来访者明确提到的居住地或当前位置
格式：[省/市/区/街道/楼栋号/房间号]（如未提及则标记"未知"）
详细地址提取：识别出来如果包含省市区的信息不管多少就直接显示，如果不够详细也显示，如果没提到则标记"未知"
注意模糊表述（如"北方城市""江浙地区"等需保留原话）
通话内容总结：
用第三人称概括核心问题（100字到1000字之间）
干预建议总结：用第三人称从咨询师说的话术中总结概况出给患者的建议（100字到1000字之间）
是否需要回访提取：如果提到"回访"两个字并且来访者同意进行回访则标记"是"，否则标记"否"，如果未提及就标记为"否"
保留以下关键要素：
• 主要症状描述（情绪/躯体/行为表现）
• 持续时间（使用"约X周/月/年"格式）
• 社会功能影响（工作/学习/人际关系）
• 既往病史（如提及）
过滤无关对话（寒暄、重复表述等）
【处理规范】
优先识别直接症状陈述（如"失眠三个月""不敢见人"）
注意隐喻表达（如"心里压着石头""像被困住"）
存在自伤/伤人表述时自动触发危机预警协议
多问题并存时按主诉优先级排序
示例对话：
[咨询师]：可以说说最近困扰您的事吗？
[来访者]：我是张三今年20岁了，在杭州工作两年了，最近三个月每天失眠，开会时手抖得厉害，上周在地铁里突然喘不过气...

示例输出：
【姓名】：张三
【年龄】：20
【地理位置】：浙江省杭州市
【详细地址】：浙江省杭州市西湖区文三路xxx号xxx室
【是否需要回访】：否
【干预建议】：建议您注意休息，避免过度劳累，可以尝试冥想或瑜伽等放松方法，同时保持良好的作息习惯，如有需要，可以寻求专业心理咨询师的帮助。
【内容总结】：来访者诉持续三个月失眠症状，伴有社交场合手抖等躯体化表现，提及近期出现惊恐发作经历（地铁喘不过气），社会功能受损（工作受影响）`
            }, 
            // {
            //     "role": "user",
            //     "content": text
            // }
        ],
        "stream": true,
        // "temporary-chat": true,
    };
    try {
        // 发送请求

        const url = import.meta.env.VITE_APP_AI_API || 'https://open.bigmodel.cn/api/paas/v4/chat/completions'
        let response = await fetch(url,

            {
                method: "post",
                responseType: "stream",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": `Bearer ${import.meta.env.VITE_APP_AI_API_KEY}`
                },
                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;
    }



}

// 推荐知识
const recommendedKnowledge: any = ref([]);


const keys = useKeysStore().knowledgeKeys;

console.log(keys, 'keys')

const getKnowledgeBaseList = (key) => {
    if (key.length < 2) {
        return
    }
    suggestions.value = []

    getPageListData('/km/doc', {
        keywords: key,
        pageNum: 1,
        pageSize: 5,
    }).then(({ data, total }) => {
        recommendedKnowledge.value = data;
    });

}

const checkKeys = (text: string) => {
    const list = findKeyword(text, keys);
    if (list?.length) {
        setKeys(list)
    }
}

const setKeys = (keys: Array<string>) => {
    const types = ['primary', 'success', 'warning', 'danger'];
    for (const key of keys) {
        const index = keywords.value.findIndex((item) => item.text === key);
        if (index > -1) {
            keywords.value[index].count++;
            keywords.value[index].type = types[keywords.value[index].count % types.length];
        } else {

            keywords.value.push({
                text: key,
                type: 'primary',
                count: 1,
            });
        }
    }

    keywords.value.sort((a, b) => b.count - a.count);

}

const selectKnowledgeId = ref(0);

const openKnowledgeAi = (id) => {
    selectKnowledgeId.value = id;
    dialogVisible.value = true;
}

const chatMouse = (type) => {
    isCanAutoScroll.value = type;
}

const scrollToBottom = () => {
    if (transcriptContainer.value) {
        transcriptContainer.value.scrollTop = transcriptContainer.value.scrollHeight;
    }
}

watch(transcripts, () => {
    nextTick(() => {
        if (isCanAutoScroll.value) scrollToBottom();
    })
}, {
    deep: true
})

const setOrderVisitStatus = (val) => {
    form.value.isNeedVisit = val;
}

const drawerOpen = ref(false);
const selectedSurvey = ref(null);
const toggleDrawer = () => {
    console.log('toggleDrawer', drawerOpen.value)
  drawerOpen.value = !drawerOpen.value;
  
};

const sexChange = (val) => {
    console.log(val, 'blur');
    form.value.sex = val;
    profile.value.sex = val;
}

const testPhone = () => {
    // return;
    router.push({
        path: '/inComming/callScreen/17737610413',
        query: {
            callNumber: '17737610413',
            callid: '123',
        }
    });
}

const customerTags = ref([]);

const getLabels = () => {
    
    if (!telNumber.value) return;
    getPageListData(`/common/getlabel/${telNumber.value}`).then(
        ({ data }) => {
            customerTags.value = data;
        }
    )
}

const labels = ref([]);
const labelCascaderRef: any = ref(null);
const getLabelsTree = () => {
    getPageListData('/patient/tag/getdata').then(({ data }) => {
        labels.value = data;
    });
}

</script>
<style scoped lang="scss">
.card {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-header {
    border-bottom: 1px solid #e5e7eb;
    padding-bottom: 16px;
}
* {
    transition: height 0.3s ease-out;
}

.scrollbar-hide {
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.scrollbar-hide::-webkit-scrollbar {
    display: none;
}

.slide-enter-active,
.slide-leave-active,
.container {
    transition: all 0.3s ease-out;
}.slide-enter-from,
.slide-leave-to {
    transform: translateX(-20px);
    opacity: 0;
}

:deep(.el-avatar) {
    background-color: #f0f2f5;
}

:deep(.el-input__wrapper) {
    /* box-shadow: none !important;
    border: none !important; */
}

:deep(.el-button.is-circle) {
    width: 3rem;
    height: 3rem;
}

.el-tabs {
    height: calc(100vh - 8rem);
    transition: height 0.3s ease-out;
}

.el-timeline {
    max-height: calc(100vh - 12rem);
    overflow-y: auto;
}

:deep(.el-tabs__content) {
    height: calc(100% - 40px);
    overflow-y: auto;
    transition: height 0.3s ease-out;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-button.is-circle) {
    width: 2.5rem;
    height: 2.5rem;
}

:deep(.el-icon) {
    font-size: 1.25rem;
}

.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;
    }
}

/* 隐藏所有滚动条 */
* {
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* Internet Explorer 10+ */
}

/* 针对Webkit浏览器（如Chrome和Safari） */
*::-webkit-scrollbar {
    display: none;
}

.drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.survey-list-container {
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
}

.survey-detail {
  background: #f9fafb;
}

:deep(.el-drawer__header) {
  display: none;
}

.writing-vertical-rl {
  writing-mode: vertical-rl;
  text-orientation: mixed;
}
</style>