<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <div class="min-h-screen-nav-height bg-gray-50" style="height: calc( 100vh - 84px );">
        <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>
                                    </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>
                                <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>

                                            </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>

                                        </div>
                                    </div>
                                </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="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>

                                            <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="结束日期" />
                            <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>
                                        <span class="text-xs text-gray-500">{{ item.createTime }}</span>
                                    </div>
                                    <div class="mt-2">
                                        <p class="text-sm text-gray-600 line-clamp-2">{{ item.content }}</p>
                                    </div>
                                    <div class="flex justify-between items-center mt-3">
                                        <div class="flex items-center">
                                            <el-tag size="small" :type="getStatusType(item.status)">
                                                {{ getStatusText(item.status) }}
                                            </el-tag>
                                        </div>
                                        <el-button type="primary" text size="small" @click="viewWorkOrder(item)">
                                            查看详情
                                        </el-button>
                                    </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-tabs>
            </div>
            <!-- 右侧工单区 -->
            <div class="w-[65%] space-y-6"
                style=" overflow-y: auto !important;height: calc(100vh - 133px); position: relative;">
                <!-- 来电信息 -->
                <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
                    <div class="card mb-1">
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-xl font-bold">工单信息</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-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>
                            <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>

                            <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-row>
                            <el-col :span="12" v-if="form.handlingMeasures.indexOf('weijiganyu')!== -1">
                                <el-form-item label="干预项" label-width="120px">
                                    <el-select v-model="form.crisisInterfere" placeholder="请选择干预项" clearable>
                                        <el-option v-for="item in order_weijiganyu" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12" v-if="form.crisisInterfere === 'jiuyuan'">
                                <el-form-item label="联动时间" label-width="120px">
                                    <el-date-picker style="width: 100%;" v-model="form.hmLinkageTime" type="datetime"
                                        placeholder="请选择联动时间" format="YYYY-MM-DD hh:mm:ss"
                                        value-format="YYYY-MM-DD hh:mm:ss" />
                                    <!-- <el-input v-model="form.hmLinkageTime" placeholder="请输入联动时间" /> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.crisisInterfere === 'jiuyuan'">
                                <el-form-item label="联动单位" label-width="120px">
                                    <el-input v-model="form.hmLinkageDept" placeholder="请输入联动单位" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.crisisInterfere === 'jiuyuan'">
                                <el-form-item label="联动电话" label-width="120px">
                                    <el-input v-model="form.hmLinkageTel" placeholder="请输入联动电话" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="12" v-if="form.crisisInterfere === 'lianxi'">
                                <el-form-item label="联系他人" label-width="120px">
                                    <el-select v-model="form.agreeLink" placeholder="请选择是否同意联系" clearable>
                                        <el-option label="未知" value="未知" />
                                        <el-option label="同意" value="同意" />
                                        <el-option label="拒绝" value="拒绝" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.agreeLink === '同意'">
                                <el-form-item label="联系电话" label-width="120px">
                                    <el-input v-model="form.aboutLinkTel" placeholder="请输入联系电话" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.agreeLink === '同意'">
                                <el-form-item label="与来电者关系" label-width="120px">
                                    <el-select v-model="form.relation" placeholder="请选择与来电者关系" clearable>
                                        <el-option label="家属" value="家属" />
                                        <el-option label="朋友" value="朋友" />
                                        <el-option label="其他" value="其他" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <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="labelsTree" filterable />
                        </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>
                    </div>
                    <div class="card mb-1">
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-xl font-bold">个人信息</h2>
                        </div>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="来电类型" label-width="120px">
                                    <el-select v-model="form.callType" placeholder="请选择性别" class="w-full" clearable>
                                        <el-option key="1" value="1" label="本人咨询" />
                                        <el-option key="2" value="2" label="替他人咨询" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="教育状况" label-width="120px">
                                    <el-select v-model="form.grade" placeholder="请选择教育状况" class="w-full" clearable>
                                        <el-option v-for="item in order_grade" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="婚姻状况" label-width="120px">
                                    <el-select v-model="form.maritalStatus" placeholder="请选择婚姻状况" class="w-full"
                                        clearable>
                                        <el-option v-for="item in order_marital_status" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="居住状态" label-width="120px">
                                    <el-select v-model="form.livingStatus" placeholder="请选择居住状态" class="w-full"
                                        clearable>
                                        <el-option v-for="item in order_living_status" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="从业状况" label-width="120px">
                                    <el-select v-model="form.career" placeholder="请选择从业状况" class="w-full" clearable>
                                        <el-option v-for="item in order_career" :key="item.value" :label="item.label"
                                            :value="item.value" />

                                    </el-select>
                                </el-form-item>
                            </el-col>

                        </el-row>
                    </div>
                    <div class="card mb-1">
                        <div class="card-header mb-4">
                            <h2 class="text-xl font-bold">业务信息</h2>
                        </div>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="主导情绪" label-width="120px">
                                    <el-select v-model="form.emotion" placeholder="请选择主导情绪" style="width: 42%;"
                                        clearable>
                                        <el-option v-for="item in order_emotion" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                    <el-input v-if="form.emotion === 'zdqxqita'" v-model="form.emotionOther"
                                        placeholder="请输入其他情绪" style="width: 45%; margin-left: 5%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="主导情绪方式" label-width="120px">
                                    <el-select v-model="form.replyMethod" placeholder="请选择主导情绪" style="width: 42%;"
                                        clearable>
                                        <el-option v-for="item in order_coping_style" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                    <el-input v-if="form.replyMethod === 'ydfsqita'" v-model="form.replyMethodOther"
                                        placeholder="请输入主导情绪应对方式" style="width: 45%; margin-left: 5%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="近期心境" label-width="120px">
                                    <el-select v-model="form.recentMood" placeholder="请选择近期心境" style="width: 42%;"
                                        clearable @change="handleRecentEmotion">
                                        <el-option v-for="item in order_emotion" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                    <el-input v-if="recentEmotionQiTa" v-model="form.recentMoodOther"
                                        placeholder="请输入近期心境" style="width: 45%; margin-left: 5%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <!-- 近期心境持续时间：______（天、月、年） -->

                                <el-form-item label="持续时间" label-width="120px">
                                    <div class="flex items-center" style="width: 100%;">
                                        <el-input-number v-model="form.recentMoodDuration" :min="1" :max="999" class="w-24" >
                                            <template #suffix>
                                                <span>天</span>
                                            </template>
                                        </el-input-number>
                                        <!-- <el-select v-model="form.durationUnit" style="width: 100px" class="ml-2 w-20">
                                            <el-option label="天" value="天" />
                                            <el-option label="月" value="月" />
                                            <el-option label="年" value="年" />
                                        </el-select> -->
                                    </div>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="近期心境方式" label-width="120px">
                                    <el-select v-model="form.copingStyle" placeholder="请选择主要应对方式" style="width: 42%;"
                                        clearable @change="handleRecentEmotionWay">
                                        <el-option v-for="item in order_coping_style" :key="item.value"
                                            :label="item.label" :value="item.value" />

                                    </el-select>
                                    <el-input v-if="recentEmotionWayQiTa" v-model="form.copingStyleOther"
                                        placeholder="请输入近期心境应对方式" style="width: 45%; margin-left: 5%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="社会支持情况" label-width="120px">
                                    <el-input v-model="form.socialSupport" type="textarea" placeholder="请输入社会支持情况" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="易感因素" label-width="120px">
                                    <el-select v-model="form.riskFactor" placeholder="请选择易感因素" style="width: 42%;"
                                        clearable @change="handleSusceptibleFactors">
                                        <el-option v-for="item in order_risk_factor" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                    <el-input v-if="susceptibleFactorsQiTa" v-model="form.riskFactorOther"
                                        placeholder="请输入其他易感因素" style="width: 45%; margin-left: 5%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="求助情况" label-width="120px">
                                    <el-select v-model="form.pastHelp" placeholder="请选择求助情况" class="w-full" clearable>
                                        <el-option v-for="item in order_past_help" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="治疗情况" label-width="120px">
                                    <el-select v-model="form.treatNow" placeholder="请选择治疗情况" class="w-full" clearable>
                                        <el-option v-for="item in order_treat_now" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.treatNow === 'outpatient'">
                                <el-form-item label="门诊治疗" label-width="120px">
                                    <el-select v-model="form.outpatient" placeholder="请选择治疗情况" class="w-full" clearable>
                                        <el-option v-for="item in order_outpatient" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.outpatient === 'yaowu'">
                                <el-form-item label="服用情况" label-width="120px">
                                    <el-select v-model="form.medicationStatus" placeholder="请选择服用情况" class="w-full"
                                        clearable>
                                        <el-option v-for="item in order_medication_status" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="是否青少年" label-width="120px">
                                    <el-select v-model="form.teenagerFlag" placeholder="请选择是否与青少年相关" class="w-full"
                                        clearable>
                                        <el-option label="不详" value="不详" />
                                        <el-option label="是" value="是" />
                                        <el-option label="否" value="否" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="自杀风险评估" label-width="120px">
                                    <el-select v-model="form.suicideRisk" placeholder="请选择自杀风险评估" class="w-full"
                                        clearable>
                                        <el-option v-for="item in order_suicide_risk" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="是否出现自杀" label-width="120px">
                                    <el-select v-model="form.suicide_occurrence" placeholder="请选择是否出现自杀"
                                        style="width: 42%;" clearable>
                                        <el-option label="是" value="是" />
                                        <el-option label="否" value="否" />
                                    </el-select>
                                    <el-input-number style="width:150px; margin-left: 5%;"
                                        v-if="form.suicide_occurrence === '是'" v-model="form.suicideCount" :min="1"
                                        :max="100">
                                        <template #suffix>
                                            <span>次</span>
                                        </template>
                                    </el-input-number>

                                    <!-- <el-input type="number" v-model="form.suicideCount" placeholder="请输入自杀次数" />  -->
                                </el-form-item>
                            </el-col>

                            <el-col :span="24">
                                <el-form-item label="是否出现自伤" label-width="120px">
                                    <el-select v-model="form.selfInjury" placeholder="请选择是否出现自伤" style="width: 42%;"
                                        clearable>
                                        <el-option v-for="item in order_self_injury" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="形式" label-width="120px"
                                    v-if="form.selfInjury && form.selfInjury !== 'fou'">
                                    <el-input v-model="form.selfInjuryOther" placeholder="请输入形式" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="危害他人风险" label-width="120px">
                                    <el-select v-model="form.harmOthers" placeholder="请选择危害他人风险评估" clearable>
                                        <el-option v-for="item in order_harm_others" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="是否出现过" label-width="120px">
                                    <el-select v-model="form.existHarmOthers" placeholder="请选择是否出现危害他人" clearable>
                                        <el-option label="是" value="是" />
                                        <el-option label="否" value="否" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="危害公共安全" label-width="120px">
                                    <el-select v-model="form.endangerPublicSafe" placeholder="请选择危害公共安全风险评估" clearable>
                                        <el-option v-for="item in order_harm_others" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="是否出现过" label-width="120px">
                                    <el-select v-model="form.existEndangerPublicSafe" placeholder="请选择是否出现危害公共安全"
                                        clearable>
                                        <el-option label="是" value="是" />
                                        <el-option label="否" value="否" />
                                    </el-select>
                                </el-form-item>
                            </el-col>


                        </el-row>

                    </div>
                    <div class="card mb-1">
                        <div class="card-header mb-4">
                            <h2 class="text-xl font-bold">来电处理</h2>
                        </div>
                        <el-row>

                            <el-col :span="12">
                                <el-form-item label="主要问题" label-width="120px">
                                    <el-cascader ref="typeCascaderRef" class="w-full" v-model="form.mainProblem"
                                        :props="{ value: 'id', }" placeholder="请选择工单类型" :options="ticketTypes"
                                        filterable clearable @change="handleTypeChange" />
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="12">
                            <el-form-item label="处理措施" label-width="120px">
                                <el-select v-model="form.handlingMeasures" placeholder="请选择处理措施" clearable> 
                                    <el-option v-for="item in order_handling_measures" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col> -->

                            <el-col :span="12">
                                <el-form-item label="随访预约" label-width="120px">
                                    <el-select v-model="form.appointment" placeholder="请选择是否预约随访" clearable>

                                        <el-option v-for="item in order_suifangyuyue" :key="item.value"
                                            :label="item.label" :value="item.value" />

                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.appointment === 'yuyue'">
                                <el-form-item label="随访联系人" label-width="120px" v-if="form.appointment === 'yuyue'">
                                    <el-select v-model="form.sfLinkman" placeholder="请选择随访联系人" clearable>
                                        <el-option label="本人" value="本人" />
                                        <el-option label="他人" value="他人" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.sfLinkman === '他人'">
                                <el-form-item label="联系电话" label-width="120px">
                                    <el-input v-model="form.sfLinkmanTel" placeholder="请输入联系电话" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" v-if="form.sfLinkman === '他人'">
                                <el-form-item label="预约时间" label-width="120px">
                                    <el-date-picker style="width: 100%;" v-model="form.sfPlanTime" type="datetime"
                                        placeholder="请选择预约时间" format="YYYY-MM-DD hh:mm:ss"
                                        value-format="YYYY-MM-DD hh:mm:ss" />

                                    <!-- <el-input v-model="form.sfPlanTime" placeholder="请输入预约时间" /> -->
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="24">
                                <el-form-item label="咨询记录" label-width="120px">
                                    <el-input v-model="form.content" placeholder="请输入咨询记录" type="textarea" :rows="4" />
                                </el-form-item>
                            </el-col> -->
                            <el-col :span="12">
                                <el-form-item label="自杀风险评估" label-width="120px">
                                    <el-select v-model="form.callEndSuicideRisk" placeholder="请选择自杀风险评估" clearable>
                                        <el-option v-for="item in order_call_end_suicide_risk" :key="item.value"
                                            :label="item.label" :value="item.value" />

                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="危害他人评估" label-width="120px">
                                    <el-select v-model="form.callEndHarmOthers" placeholder="请选择危害他人风险评估" clearable>
                                        <el-option v-for="item in order_call_end_harm_others" :key="item.value"
                                            :label="item.label" :value="item.value" />

                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="危害公共评估" label-width="120px">
                                    <el-select v-model="form.callEndEndangerPublicSafe" placeholder="请选择危害公共安全风险评估"
                                        clearable>

                                        <el-option v-for="item in order_call_end_harm_others" :key="item.value"
                                            :label="item.label" :value="item.value" />

                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="情绪舒缓评估" label-width="120px">
                                    <el-select v-model="form.callEndMoodRelax" placeholder="请选择情绪舒缓评估" clearable>
                                        <el-option v-for="item in order_call_end_mood_relax" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="信息咨询评估" label-width="120px">
                                    <el-select v-model="form.callEndInfoConsult" placeholder="请选择信息咨询类评估" clearable>
                                        <el-option v-for="item in order_call_end_info_consult" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>

                        </el-row>

                    </div>
                </el-form>
                <div class="bg-white" style="position: fixed; bottom: 50px;  right: 7%;">
                    <el-button type="primary" class="w-32 !rounded-button whitespace-nowrap"
                        @click="submit">提交工单</el-button>
                </div>
            </div>

        </div>

        <div class="aiDialog">
            <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">
            <div @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, 'cursor': 'pointer'
            }">
                {{ drawerOpen ? '关闭问卷调查' : '问卷调查' }}
            </div>

            <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 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,
    Location,
    Document,
    Service,
    Eleme,
    Edit,
    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 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()
// AI加载状态
const aiLoading = ref(false);
// 控制聊天记录是否自动滚动
const isCanAutoScroll = ref(1);
// 控制AI对话框显示
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'); // 是否显示AI搜索
// 获取电话号码
const telNumber = ref(proxy.$route.query.phone || proxy.$route.query.callNumber || proxy.$route.params.callNumber);
// 设置页面标题
proxy.$route.meta.title = telNumber.value || '来电弹屏';
// 获取通话ID
const callid = ref(proxy.$route.query.callid || 0);

/**
 * 创建操作日志
 * @param {string} content - 日志内容
 */
const createLog = (content = '') => {
    createPageData('/ai/aioperation', {
        operateType: 'ASR',
        operationContent: content,
    }).then(() => { }).catch(() => { })
}

// 如果有通话ID，记录日志
if (callid.value) createLog('callid');



// 工单搜索相关变量
const pageSize = ref(10);
const displayedActivities = ref([]);
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;
    const res = await getWorkOrders();
    if (res?.length === 0) {
        noMore.value = true;
    } else {
        pageIndex.value++;
    }
    loading.value = false;
};

/**
 * 处理滚动事件，实现滚动加载更多
 * @param {Event} event - 滚动事件
 */
const handleScroll = async (event) => {
    const target = event.target;
    const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
    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;
    const res = await getCalllog();
    if (res?.length === 0) {
        callNoMore.value = true;
    } else {
        callPageIndex.value++;
    }
    callLoading.value = false;
};

/**
 * 保存语音转写结果
 * @param {string|number} callid - 通话ID
 * @param {Array} translate - 转写结果
 */
const saveTranslate = (callid, translate) => {
    if (!translate || !translate.length || !callid || !showAsr) return;
    createPageData('/call/translate', {
        callid,
        translateJson: JSON.stringify(translate),
    }).then(() => { }).catch(() => { })
}

/**
 * 处理通话记录滚动事件
 * @param {Event} event - 滚动事件
 */
const handleCallScroll = async (event) => {
    const target = event.target;
    const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;
    if (scrollBottom < 50) {
        await loadMoreCallData();
    }
};

// 通话记录分页相关变量
const callPageSize = ref(10)
const callPageIndex = ref(1)
const callSearchQuery = ref()
const callAnswerTime = ref()
const callHangupTime = ref()

/**
 * 处理通话时间范围变更
 * @param {Array} e - 时间范围数组
 */
function callChange(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()
}

/**
 * 获取通话记录
 * @returns {Promise<Array>} 通话记录数组
 */
const getCalllog = async () => {
    if (!telNumber.value) return;
    const params = {
        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);
    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 [];
}

/**
 * 计算通话时长
 * @param {string} startTime - 开始时间
 * @param {string} endTime - 结束时间
 * @returns {string} 格式化后的时间差
 */
function getTimeLimit(startTime, endTime) {
    return proxy.getTimeDifference(startTime, endTime);
}
const setOrderVisitStatus = (val) => {
    form.value.isNeedVisit = val;
}
// 组件挂载时执行的操作
onMounted(() => {
    getLabelsTree(); // 获取标签树
    transcripts.value = []; // 初始化转写记录
    getUserInfo(); // 获取用户信息
    loadMoreData(); // 加载工单数据
    loadMoreCallData(); // 加载通话记录
    getLabels(); // 获取标签
    // 如果有通话ID，添加语音识别事件监听
    if (callid.value) window.addEventListener(`AsrMessageEvent-${callid.value}`, dealAsrMessage)
});

/**
 * 获取状态文本
 * @param {string} type - 状态类型
 * @returns {string} 状态文本
 */
const getStatusText = (type) => {
    const statusMap = {
        primary: '处理中',
        success: '已完成',
        warning: '待处理',
        info: '已完成',
        danger: '已取消'
    };
    return statusMap[type] || '';
};

/**
 * 根据状态码获取状态类型
 * @param {number} status - 状态码
 * @returns {string} 状态类型
 */
const getStatusType = (status) => {
    switch (status) {
        case 0: return 'warning';
        case 1: return 'primary';
        case 2: return 'success';
        case 3: return 'danger';
        default: return 'info';
    }
};

// 编辑状态控制
const isEditing = ref(false);
// 用户档案信息
const profile = ref({
    name: '-',
    sex: '0',
    registerDate: '',
    phone: '',
    tel: '',
    address: ''
});

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

};

const ageGroupOptions = [{
    value: '青少年',
    label: '青少年'
}, {
    value: '中年',
    label: '中年'
}, {
    value: '老年',
    label: '老年'
}, {
    value: '未知',
    label: '未知'
}];
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 recentEmotionQiTa = ref(false)
function handleRecentEmotion(val) {
    if (val === 'zdqxqita') {
        recentEmotionQiTa.value = true;
    } else {
        recentEmotionQiTa.value = false;
    }
}
const recentEmotionWayQiTa = ref(false)
function handleRecentEmotionWay(val) {
    if (val === 'ydfsqita') {
        recentEmotionWayQiTa.value = true;
    } else {
        recentEmotionWayQiTa.value = false;
    }
}
// 易感因素逻辑
const susceptibleFactorsQiTa = ref(false)
function handleSusceptibleFactors(val) {
    if (val === 'qita') {
        susceptibleFactorsQiTa.value = true;
    } else {
        susceptibleFactorsQiTa.value = false;
    }
}
// 表单引用
const formRef = ref(null);


// 表单数据
const form = ref({
    tag: [],
    ageGroup: '',
    age: '',
    area: '',
    address: '',
    suggest: '',
    sex: '0',
    isNeedVisit: false,
    name: '不详',
    phone: '',
    type: '',
    typeCode: '',
    description: '',
    handleMethod: '1',
    department: '',

    handlingMeasures: [], // 处理措施
    crisisInterfere: '', // 干预项目
    hmLinkageTime: '', // 联动时间
    hmLinkageDept: '', // 联动单位
    hmLinkageTel: '', // 联动电话
    agreeLink: '', // 联系他人
    aboutLinkTel: '', // 联系电话
    relation: '', // 与来电者关系

    callType: '1', // 来电类型
    grade: '',     // 教育状况
    maritalStatus: '', // 婚姻状况
    livingStatus: '', // 居住状态
    career: '', // 从业状况
    emotion: '', // 主导情绪
    emotionOther: '', // 自定义情绪其他的
    replyMethod: '', // 主导情绪的主要应对方式
    replyMethodOther: '', // 自定义应对方式其他的
    recentMood: '', // 近期心境
    recentMoodOther: '', // 近期心境其他
    recentMoodDuration: '', // 近期心境持续时间
    // durationUnit: '天', // 持续时间单位
    copingStyle: '', // 近期心境的主要应对方式
    copingStyleOther: '', // 请输入其他应对方式
    socialSupport: '', // 社会支持
    riskFactor: '', // 易感因素
    riskFactorOther: '', // 其他易感因素"
    pastHelp: '', // 求助情况
    treatNow: '', // 治疗情况
    outpatient: '', // 门诊治疗
    medicationStatus: '', // 服用情况
    teenagerFlag: '不详', // 是否与青少年相关
    suicideRisk: '', // 自杀风险评估
    suicide_occurrence: '', // 是否出现自杀
    suicideCount: '', // 自杀次数
    selfInjury: '', // 自身伤害
    selfInjuryOther: '', // 自定义自身伤害其他
    harmOthers: '', // 危害他人风险评估
    existHarmOthers: '', // 是否出现危害他人
    endangerPublicSafe: '', // 危害公共安全
    existEndangerPublicSafe: '', // 是否出现过
    mainProblem: '', // 主要问题

    appointment: '', // 随访预约
    sfLinkman: '', // 随访联系人
    sfLinkmanTel: '', // 预约电话
    sfPlanTime: '', // 预约时间
    content: '', // 咨询记录
    callEndSuicideRisk: '', // 来电结束前自杀风险评估  
    callEndHarmOthers: '', // 危害他人风险评估   
    callEndEndangerPublicSafe: '', // 危害公共安全风险评估 
    callEndMoodRelax: '', // 情绪舒缓评估
    callEndInfoConsult: '', // 信息咨询类评估

});

// 表单验证规则
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' }
    ],
};

// 从store获取下拉选项数据
const departments = useSelectStore().deptListData;
const ticketTypes = useSelectStore().dictOrderTypeList; // 工单类型列表
const areaTree = useSelectStore().areaTree; // 区域树
// 处理方式选项
const handleMethods = [
    { label: '立即完结', value: '1' },
    { label: '待交办', value: '0' },
];

/**
 * 获取用户信息
 */
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 });
    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 = ref(null);

/**
 * 处理工单类型变更
 * @param {Array} value - 选中的类型值
 */
const handleTypeChange = (value) => {
    if (typeCascaderRef.value) {
        const selectNode = typeCascaderRef.value.getCheckedNodes();
        form.value.typeCode = selectNode[selectNode.length - 1].data.code;
    }
}

// 部门级联选择器引用
const deptCascaderRef = ref(null);

/**
 * 重置表单
 */
const resetForm = () => {
    form.value = {
        ageGroup: '',
        age: '',
        area: '',
        address: '',
        suggest: '',
        isNeedVisit: false,
        name: '',
        phone: '',
        type: '',
        typeCode: '',
        description: '',
        handleMethod: '1',
        department: '',

        callType: '1', // 来电类型
        grade: '',     // 教育状况
        maritalStatus: '', // 婚姻状况
        livingStatus: '', // 居住状态
        career: '', // 从业状况
        emotion: '', // 主导情绪
        emotionOther: '', // 自定义情绪其他的
        replyMethod: '', // 主导情绪的主要应对方式
        replyMethodOther: '', // 自定义应对方式其他的
        recentMood: '', // 近期心境
        recentMoodOther: '', // 近期心境其他
        recentMoodDuration: '', // 近期心境持续时间
        copingStyle: '', // 近期心境的主要应对方式
        copingStyleOther: '', // 请输入其他应对方式
        socialSupport: '', // 社会支持
        riskFactor: '', // 易感因素
        riskFactorOther: '', // 其他易感因素"
        pastHelp: '', // 求助情况
        treatNow: '', // 治疗情况
        outpatient: '', // 门诊治疗
        medicationStatus: '', // 服用情况
        teenagerFlag: '不详', // 是否与青少年相关
        suicideRisk: '', // 自杀风险评估
        suicide_occurrence: '', // 是否出现自杀
        suicideCount: '', // 自杀次数
        selfInjury: '', // 自身伤害
        selfInjuryOther: '', // 自定义自身伤害其他
        harmOthers: '', // 危害他人风险评估
        existHarmOthers: '', // 是否出现危害他人
        endangerPublicSafe: '', // 危害公共安全
        existEndangerPublicSafe: '', // 是否出现过
        mainProblem: '', // 主要问题
        handlingMeasures: [], // 处理措施
        crisisInterfere: '', // 干预项目
        hmLinkageTime: '', // 联动时间
        hmLinkageDept: '', // 联动单位
        hmLinkageTel: '', // 联动电话
        agreeLink: '', // 联系他人
        aboutLinkTel: '', // 联系电话
        relation: '', // 与来电者关系
        appointment: '', // 随访预约
        sfLinkman: '', // 随访联系人
        sfLinkmanTel: '', // 预约电话
        sfPlanTime: '', // 预约时间
        content: '', // 咨询记录

        callEndSuicideRisk: '', // 来电结束前自杀风险评估  
        callEndHarmOthers: '', // 危害他人风险评估   
        callEndEndangerPublicSafe: '', // 危害公共安全风险评估 
        callEndMoodRelax: '', // 情绪舒缓评估
        callEndInfoConsult: '', // 信息咨询类评估
    };
    formRef.value.resetFields();
}

/**
 * 提交工单
 */
const submit = async () => {
    // 验证表单必填项
    formRef.value.validate(async (valid) => {
        if (valid) {
            const params = {
                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], 
                callType: form.value.callType,  // 来电类型
                sex: form.value.sex,  // 性别   
                age: form.value.age,  // 年龄
                grade: form.value.grade,     // 教育状况
                handling:{
                    aboutLinkTel: form.value.aboutLinkTel, // 联系电话
                    agreeLink: form.value.agreeLink, // 联系他人    
                    appointment: form.value.appointment, // 随访预约
                    crisisInterfere: form.value.crisisInterfere, // 干预项目
                    hmLinkageDept: form.value.hmLinkageDept, // 联动单位
                    hmLinkageTel: form.value.hmLinkageTel, // 联动电话
                    hmLinkageTime: form.value.hmLinkageTime, // 联动时间
                    mainProblem: form.value.mainProblem ? form.value.mainProblem[form.value.mainProblem.length - 1] : '', // 主要问题
                    relation: form.value.relation, // 与来电者关系
                    sfLinkman: form.value.sfLinkman, // 随访联系人
                    sfLinkmanTel: form.value.sfLinkmanTel, // 预约电话
                    sfPlanTime: form.value.sfPlanTime, // 预约时间
                },
                assessment:{
                    callEndEndangerPublicSafe: form.value.callEndEndangerPublicSafe, // 危害公共安全风险评估
                    callEndHarmOthers: form.value.callEndHarmOthers, // 危害他人风险评估
                    callEndInfoConsult: form.value.callEndInfoConsult, // 信息咨询类评估
                    callEndMoodRelax: form.value.callEndMoodRelax, // 情绪舒缓评估  
                    callEndSuicideRisk: form.value.callEndSuicideRisk, // 来电结束前自杀风险评估
                    copingStyle: form.value.copingStyle, // 近期心境的主要应对方式
                    copingStyleOther: form.value.copingStyleOther, // 请输入其他应对方式
                    emotion: form.value.emotion, // 主导情绪
                    emotionOther: form.value.emotionOther, // 自定义情绪其他的
                    endangerPublicSafe: form.value.endangerPublicSafe, // 危害公共安全
                    existEndangerPublicSafe: form.value.existEndangerPublicSafe, // 是否出现过
                    existHarmOthers: form.value.existHarmOthers, // 是否出现危害他人    
                    harmOthers: form.value.harmOthers, // 危害他人风险评估
                    medicationStatus: form.value.medicationStatus, // 服用情况
                    outpatient: form.value.outpatient, // 门诊治疗
                    pastHelp: form.value.pastHelp, // 求助情况
                    recentMood: form.value.recentMood, // 近期心境
                    recentMoodDuration: form.recentMoodDuration, // 近期心境持续时间  ? (form.value.recentMoodDuration + form.durationUnit) : ''
                    recentMoodOther: form.value.recentMoodOther, // 近期心境其他
                    replyMethod: form.value.replyMethod, // 主导情绪的主要应对方式
                    replyMethodOther: form.value.replyMethodOther, // 自定义应对方式其他的
                    riskFactor: form.value.riskFactor, // 易感因素
                    riskFactorOther: form.value.riskFactorOther, // 其他易感因素"
                    selfInjury: form.value.selfInjury, // 自身伤害
                    selfInjuryOther: form.value.selfInjuryOther, // 自定义自身伤害其他
                    socialSupport: form.value.socialSupport, // 社会支持
                    suicideCount: form.value.suicideCount, // 自杀次数
                    suicideRisk: form.value.suicideRisk, // 自杀风险评估
                    treatNow: form.value.treatNow, // 治疗情况  
                },
                
                maritalStatus: form.value.maritalStatus, // 婚姻状况
                livingStatus: form.value.livingStatus, // 居住状态  
                career: form.value.career, // 从业状况
                teenagerFlag: form.value.teenagerFlag, // 是否与青少年相关
                suicide_occurrence: form.value.suicide_occurrence, // 是否出现自杀  
                appointment: form.value.appointment, // 随访预约
               
            };
            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 = [];
                console.log(warnings, 'warnings');
                for (let index = 0; index < warnings.length; index++) {
                    const info = warnings[index];
                    console.log(info, 'info');
                    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;
                }
            }
            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');
            // 提交表单
            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('请填写完整信息');
        }

    });

    // formRef.value.validate(async (valid) => {
    //     if (valid) {

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

/**
 * 关闭当前页面
 */
function close() {
    const obj = { path: '/' }
    proxy.$tab.closeOpenPage(obj)
}

// 工单搜索相关变量
const orderSearchQuery = ref()
const createtime = ref()
const endtime = ref()

/**
 * 处理工单时间范围变更
 * @param {Array} e - 时间范围数组
 */
function orderChange(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()
}

/**
 * 获取工单列表
 * @returns {Promise<Array>} 工单数组
 */
const getWorkOrders = async () => {
    if (!telNumber.value) return;
    const params = {
        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);
    if (result.state === 'success') {
        displayedActivities.value = displayedActivities.value.concat(result.data)
        if (displayedActivities.value.length === 0) {
            noMore.value = true;
        } else {
            noMore.value = false;
        }
        return result.data;
    }
    return [];
}

/**
 * 处理标签页切换
 * @param {string} name - 标签页名称
 */
const tabChange = (name) => {
    if (name === '1') {
        pageIndex.value = 1
        callPageIndex.value = 1
        callData.value = []
        getCalllog();
    } else if (name === '2') {
        pageIndex.value = 1
        displayedActivities.value = []
        getWorkOrders();
    }
}

// 语音识别相关变量
const transcripts = ref([]) // 转写记录
const keywords = ref([]); // 关键词

const transcriptContainer = ref < HTMLElement | null > (null);

/**
 * 处理语音识别消息
 * @param {CustomEvent} msg - 语音识别事件消息
 */
const dealAsrMessage = (msg) => {
    if (!showAsr) return;
    if (!msg?.detail || !msg.detail.Result) return;
    // 构建消息对象
    const msgInfo = {
        direction: msg.detail.Number.toString().length > 4 ? 2 : 1, // 1-坐席，2-客户
        page_content: msg.detail.Speech || '', // 语音内容
        timestamp: '', // 时间戳
    };

    // 处理时间信息
    if (msg.detail.Time) {
        const times = JSON.parse(msg.detail.Time);
        if (times?.length) {
            const time = flatten(times)?.[0];
            if (time) msgInfo.timestamp = formatMilliseconds(time);
        }
    }

    // 检查关键词并添加到转写记录
    if (msgInfo.page_content.length > 2) checkKeys(msgInfo.page_content);
    transcripts.value.push(msgInfo);
}

/**
 * AI智能填单
 */
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) {
        // 获取AI分析结果
        let res = await getSearchDocs(text);
        // 移除思考过程
        res = res.replace(/<think>[\s\S]*?<\/think>/g, '');

        // 解析AI返回结果并填充表单
        res.split('\n').forEach((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;
                }
            }
            if (o.startsWith('【是否需要回访】')) {
                const result = o.replace('【是否需要回访】', '').replace('：', '');
                if (result === '是') form.value.isNeedVisit = true;
            }
        })
    }

    aiLoading.value = false;
}

/**
 * 移除事件监听
 */
const unListenerEvent = () => {
    if (callid.value) window.removeEventListener(`AsrMessageEvent-${callid.value}`, dealAsrMessage)
}

// 组件卸载时移除事件监听
onUnmounted(() => {
    unListenerEvent();
})

// 推荐知识相关变量
const recommendedKnowledge = ref([]);

/**
 * 获取知识库列表
 * @param {string} keyword - 搜索关键词
 */
const getKnowledgeBaseList = async (keyword) => {
    if (!keyword) return;
    const result = await getPageListData('/knowledge/knowledgebase', {
        pageSize: 5,
        pageNum: 1,
        title: keyword,
    });
    if (result.state === 'success') {
        recommendedKnowledge.value = result.data;
    }
}

/**
 * 打开知识AI对话框
 * @param {string|number} docId - 文档ID
 */
const openKnowledgeAi = (docId) => {
    dialogVisible.value = true;
}

/**
 * 处理聊天鼠标事件，控制自动滚动
 * @param {number} type - 类型：0-禁用自动滚动，1-启用自动滚动
 */
const chatMouse = (type) => {
    isCanAutoScroll.value = type;
}

/**
 * 检查文本中的关键词
 * @param {string} text - 要检查的文本
 */
const checkKeys = (text) => {
    if (!text) return;
    const keysStore = useKeysStore();
    const keys = keysStore.keys;
    if (!keys?.length) return;

    const keywordMap = findKeyword(text, keys);
    if (keywordMap?.length) {
        const newKeywords = [];
        keywordMap.forEach((item) => {
            const existingKeyword = keywords.value.find(k => k.text === item);
            if (existingKeyword) {
                existingKeyword.count += 1;
            } else {
                newKeywords.push({
                    text: item,
                    type: getRandomType(),
                    count: 1,
                });
            }
        });

        if (newKeywords.length) {
            keywords.value = [...keywords.value, ...newKeywords];
        }
    }
}

/**
 * 获取随机标签类型
 * @returns {string} 标签类型
 */
const getRandomType = () => {
    const types = ['primary', 'success', 'warning', 'danger', 'info'];
    return types[Math.floor(Math.random() * types.length)];
}

/**
 * 获取AI搜索文档结果
 * @param {string} text - 搜索文本
 * @returns {Promise<string>} 搜索结果
 */
const getSearchDocs = async (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 customerTags = ref([]);

const getLabels = () => {

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

// 标签树
const labelsTree = ref([]);
/**
 * 获取标签树
 */
const getLabelsTree = async () => {
    const result = await getPageListData('/patient/tag/getdata', {});
    if (result.state === 'success') {
        labelsTree.value = result.data || [];
    }
}




/**
 * 测试电话功能（仅用于测试）
 */
const testPhone = () => {
    // 测试用
    // return;
    router.push({
        path: '/inComming/callScreen/17737610413',
        query: {
            callNumber: '17737610413',
            callid: '123',
        }
    });
}

/**
 * 查看工单详情
 * @param {Object} item - 工单项
 */
const viewWorkOrder = (item) => {
    router.push({
        path: '/main/workOrder/detail',
        query: {
            id: item.id
        }
    })
}

// 必须导出，否则模板中无法使用
const {
    order_handling_measures,
    order_grade,
    order_marital_status,
    order_living_status,
    order_career,
    order_emotion,
    order_coping_style,
    order_risk_factor,
    order_past_help,
    order_treat_now,
    order_medication_status,
    order_suicide_risk,
    order_self_injury,
    order_harm_others,
    order_weijiganyu,
    order_suifangyuyue,
    order_call_end_suicide_risk,
    order_call_end_harm_others,
    order_call_end_info_consult,
    order_call_end_mood_relax,
    order_outpatient } =
    proxy.useDict('order_handling_measures',
        'order_grade',
        'order_marital_status',
        'order_living_status',
        'order_career',
        'order_emotion',
        'order_coping_style',
        'order_risk_factor',
        'order_past_help',
        'order_treat_now',
        'order_medication_status',
        'order_suicide_risk',
        'order_self_injury',
        'order_harm_others',
        'order_handling_measures',
        'order_weijiganyu',
        'order_suifangyuyue',
        'order_call_end_suicide_risk',
        'order_call_end_harm_others',
        'order_call_end_info_consult',
        'order_call_end_mood_relax',
        'order_outpatient');


</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>