<!-- 代码已包含 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">基本信息</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 }}</span>
                                        </template>
                                        <template v-else>
                                            <el-select v-model="profile.sex" size="small" class="w-full">
                                                <el-option label="男" value="男" />
                                                <el-option label="女" value="女" />
                                                <el-option label="未知" value="未知" />
                                            </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-4">联系方式</h3>
                                <div class="space-y-3">
                                    <div class="flex items-center">
                                        <el-icon class="mr-2">
                                            <Phone />
                                        </el-icon>
                                        <span>{{ profile.phone }}</span>
                                        <!-- <template v-if="!isEditing">
                                            <span>{{ profile.phone }}</span>
                                        </template>
                                        <template v-else>
                                            <el-input v-model="profile.phone" size="small" class="w-full" />
                                        </template> -->
                                    </div>
                                    <!-- <div class="flex items-center">
                                        <el-icon class="mr-2">
                                            <Message />
                                        </el-icon>
                                        <template v-if="!isEditing">
                                            <span>{{ profile.email }}</span>
                                        </template>
                                        <template v-else>
                                            <el-input v-model="profile.email" size="small" class="w-full" />
                                        </template>
                                    </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">
                            <!-- 实时语音识别区域 -->
                            <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">语音识别</h3>
                                    <!-- <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">
                                        <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 class="space-y-2">
                                    <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" :key="idx" :type="keyword.type"
                                            effect="plain" size="small">
                                            {{ keyword.text }}
                                        </el-tag>
                                    </div>
                                </div> -->
                                <!-- 建议话术 -->
                                <!-- <div class="mt-4 space-y-2">
                                    <h4 class="font-medium text-sm text-gray-600">建议话术</h4>
                                    <div class="space-y-2">
                                        <div v-for="(suggestion, idx) in suggestions" :key="idx"
                                            class="p-2 bg-gray-50 rounded text-sm text-gray-600 cursor-pointer hover:bg-gray-100">
                                            {{ suggestion }}
                                        </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-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" @click="toDetail(item)">
                                    <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="flex-1 overflow-y-auto workorder-card">
                <div class="workorder-container">
                    <!-- 来电信息 -->
                    <div class="card mb-1">
                        <div class="card-header mb-4">
                            <h2 class="text-xl font-bold">来电信息</h2>
                        </div>
                        <div class="grid grid-cols-2 gap-6">
                            <el-form-item label="电话" required>
                                <el-input v-model="form.phone" placeholder="请输入电话号码" :required="true" />
                            </el-form-item>
                            <el-form-item label="姓名">
                                <el-input v-model="form.name" placeholder="不详" />
                            </el-form-item>
                            <el-form-item label="学历">
                                <el-select v-model="form.grade" filterable placeholder="不详" class="w-full">
                                    <el-option v-for="item in order_grade" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="婚姻状况">
                                <el-select v-model="form.maritalStatus" filterable placeholder="不详" class="w-full">
                                    <el-option v-for="item in order_marital_status" :key="item.value"
                                        :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="年龄">
                                <el-input v-model="form.age" type="number" placeholder="请输入年龄"
                                        @input="updateAgeGroup" />
                            </el-form-item>
                            <el-form-item label="年龄阶段">
                                <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-form-item label="性别">
                                <el-select v-model="form.sex" filterable placeholder="不详" class="w-full">
                                    <el-option v-for="item in genderOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="职业">
                                <el-select v-model="form.career" filterable placeholder="不详" class="w-full">
                                    <el-option v-for="item in order_career" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            
                        </div>
                        <div class="grid gap-6 mt-6">
                            <el-form-item label="事发区域">
                                <el-cascader v-model="form.area" 
                                :props="{ value: 'id', }" :options="areaTree" filterable placeholder="请选择事发区域"
                                    class="w-full" />
                            </el-form-item>
                            <el-form-item label="详细地址">
                                <el-input type="text" v-model="form.address"
                                    placeholder="请输入详细地址" />
                            </el-form-item>
                        </div>
                    </div>
                    <!-- 求助信息 -->
                    <div class="card mb-1">
                        <div class="card-header mb-4">
                            <h2 class="text-xl font-bold">求助信息</h2>
                        </div>
                        <div class="grid grid-cols-2 gap-6">
                            <el-form-item label="用药">
                                <el-select v-model="form.useMedicine" filterable placeholder="不详" class="w-full">
                                    <el-option v-for="item in order_use_medicine" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="既往诊断">
                                <el-select v-model="form.previousDiagnosis" filterable placeholder="不详" class="w-full">
                                    <el-option v-for="item in order_previous_diagnosis" :key="item.value"
                                        :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="现在治疗">
                                <el-select v-model="form.treatNow" filterable placeholder="不详" class="w-full">
                                    <el-option v-for="item in order_treat_now" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="既往心理治疗">
                                <el-select v-model="form.previousPsychotherapy" filterable placeholder="不详"
                                    class="w-full">
                                    <el-option v-for="item in order_previous_psychotherapy" :key="item.value"
                                        :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="具体计划">
                                <el-select v-model="form.concretePlan" filterable placeholder="不详" class="w-full">
                                    <el-option v-for="item in order_concrete_plan" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </div>
                    </div>
                    <!-- 处理信息 -->
                    <div class="card">
                        <div class="card-header mb-4">
                            <h2 class="text-xl font-bold">处理信息</h2>
                        </div>
                        <div class="grid grid-cols-1 gap-6">
                            <!-- 工单类型 -->
                            <div class="mb-6">
                                <el-form-item label="工单类型" required>
                                    <el-cascader ref="typeCascaderRef" class="w-full" v-model="form.type"
                                        :props="{ value: 'id', }" placeholder="请选择工单类型" :options="ticketTypes"
                                        filterable clearable @change="handleTypeChange" />
                                </el-form-item>
                            </div>
                            <!-- 主要问题列表 -->
                            <div class="mb-6">
                                <el-form-item label="主要问题">
                                    <el-table :data="vars" style="width: 100%">
                                        <el-table-column fixed prop="key" label="问题">
                                            <template #default="scope">
                                                <el-cascader ref="typeCascaderRef" class="w-full"
                                                    v-model="scope.row.mainProblemId	" :props="{ value: 'id', }"
                                                    placeholder="请选择问题" :options="mainQuestions" filterable clearable
                                                    @change="changeVar($event,scope.$index, scope.row.key)" />

                                                <!-- <span v-else>{{ scope.row.name }}</span> -->
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="options" label="年限" width="120">
                                            <template #default="scope">
                                                <el-input-number v-model="scope.row.years" clearable
                                                    style="width: 80px"></el-input-number>
                                                <!-- <span v-else>{{ scope.row.value }}</span> -->
                                            </template>

                                        </el-table-column>
                                        <el-table-column fixed="right" label="操作" width="100">
                                            <template #default="scope">
                                                <el-button link type="danger" size="small"
                                                    @click.prevent="deleteRow(0, scope.$index)">
                                                    删除
                                                </el-button>

                                                <!-- <el-button v-if="scope.$index === clickRow" link type="primary"
                                                    size="small" @click.prevent="saveFilter(0, scope.$index)">
                                                    保存
                                                </el-button> -->
                                                <!-- <el-button v-if="scope.$index !== clickRow" link type="error"
                                                    size="small" @click.prevent="clickRow = scope.$index">
                                                    编辑
                                                </el-button> -->
                                            </template>
                                        </el-table-column>
                                    </el-table>

                                    <el-button class="mt-4" style="width: 100%" @click="onAddItem(index)">
                                        新增问题
                                    </el-button>
                                </el-form-item>
                            </div>
                            <!-- 问题描述 -->
                            <div class="mb-6">
                                <el-form-item label="问题描述" required>
                                    <el-input type="textarea" v-model="form.description" rows="4"
                                        placeholder="请输入问题描述" />
                                </el-form-item>
                            </div>
                        </div>
                        <!-- 处理措施 -->
                        <div class="grid grid-cols-1 gap-6 mb-6">
                            <el-form-item label="处理措施" required>
                                <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>

                        </div>
                        <!-- 处理措施 -->
                        <div class="grid grid-cols-1 gap-6">
                            <el-form-item label="处理方式" required>
                            <el-select v-model="form.handleMethod" placeholder="请选择处理方式" class="w-full">
                                <el-option v-for="item in handleMethods" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        </div>
                        
                    </div>
                </div>
            </div>
            <!-- 提交栏 -->
            <div class="submit-bar">
                <el-button type="primary" size="large" class="!rounded-button whitespace-nowrap w-40" @click="submit">提交工单</el-button>
                <el-button size="large" class="!rounded-button whitespace-nowrap w-40" @click="resetForm">重置</el-button>
            </div>
        </div>

    </div>
</template>
<script lang="ts" setup name="CallScreen">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import moment from 'moment';
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 { hidePhone } from '@/utils/tools';
import { ElMessage } from 'element-plus';
import useSelectStore from '@/store/commonSelect/common';
import { getPageListData, createPageData } from '@/api/main/system/system';
import { userDecryptToAsterisk } from '@/utils/aes';
import knowledgeList from "@/views/main/knowledgeBase/knowledgeList/cpns/konwlegelist/konwlegelist";

import { max, flatten } from 'lodash';
import { getOfffixNuber, getCallSate } from '@/utils/index';




const router = useRouter()
let { proxy } = getCurrentInstance()
const showCallPanel = ref(false);
const searchQuery = ref('');
const aiLoading = ref(false);
const isCanAutoScroll = ref(1);
console.log('proxy', proxy.$route);

const clickRow = ref(-1);

const saveFilter = (tagIndex, tableIndex) => {
  
  clickRow.value = -1;
}

let vars: any = ref([]);

const deleteRow = (tagIndex, tableIndex) => {
  vars.value = vars.value.filter((item, index) => index !== tableIndex);
}

const onAddItem = (index) => {
  
  vars.value.push({
    mainProblemId: '',
    years: '',
    name: '',
  })

  clickRow.value = vars.value.length - 1;
}

const changeVar = (item, index, key) => {
    console.log(item, index, key, 'asdfasdf');
//   const item = allVars.value.find((o) => { return o.key === key });
//   if (item) vars.value[index].value = item.value;
}

const { order_concrete_plan, order_handling_measures, order_previous_psychotherapy, order_treat_now, order_previous_diagnosis, order_use_medicine, order_career, order_marital_status, order_grade, cllx } = proxy.useDict(
    'order_concrete_plan',
    'order_handling_measures',
    'order_previous_psychotherapy',
    'order_treat_now',
    'order_previous_diagnosis',
    'order_use_medicine',
    'order_career', 'order_marital_status', 'order_grade'
)

console.log('order_concrete_plan', order_concrete_plan);

const showAsr = ref(import.meta.env.VITE_APP_AI_ASR === 'true');
const showAI = ref(import.meta.env.VITE_APP_AI_SEARCH === 'true');
// console.log(proxy.$route.query.callNumber)
const telNumber = ref(proxy.$route.query.phone || proxy.$route.query.callNumber || proxy.$route.params.callNumber);
console.log(telNumber.value)
proxy.$route.meta.title = telNumber.value || '来电弹屏';
const callid = ref(proxy.$route.query.callid || 0);
onMounted(() => {
    getUserInfo();
});
onUnmounted(() => {

});
const showDialpad = ref(false);

const showContacts = ref(false);

const handleRecords = () => {
    // 处理通话记录
};
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 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(() => {
    loadMoreData();
    loadMoreCallData()
});
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 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: '-',
    registerDate: '',
    // lastContact: '',
    phone: '',
    tel: '',
    // email: 'zhaomq@example.com',
    address: ''
});
const formRef: any = ref(null);
const form = ref({
    
    age: '',
    ageGroup: '',
    sex: '',
    name: '不详',
    area: 1821,
    address: '',
    career: '',
    concretePlan: '',
    grade: '',
    handlingMeasures: [],
    maritalStatus: '',
    orderProblems: [],
    previousDiagnosis: '',
    previousPsychotherapy: '',
    treatNow: '',
    useMedicine: '',
    phone: '',
    type: '',
    typeCode: '',
    description: '',
    // priority: 'medium',
    handleMethod: '1',
    // remarks: '',
    department: '',
});
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: 100, message: '问题描述5-100个字符', trigger: 'blur' },
    ],
    handleMethod: [
        { required: true, message: '请选择处理方式', trigger: 'change' }
    ],
};

const ticketTypes = useSelectStore().dictOrderTypeList;
const mainQuestions = useSelectStore().mainQuesTree;
const areaTree = useSelectStore().areaTree;
// const departments = useSelectStore().deptListData;
const handleMethods = [
    { label: '立即完结', value: '1' },
    { label: '待交办', value: '0' },
    // { label: '转专员处理', value: 'transfer' },
    // { label: '现场支持', value: 'onsite' }
];
const genderOptions = [
    { label: '男', value: '男' },
    { label: '女', value: '女' }
] 
const initOrder = (info: any) => {
    if (!info?.workorderId) return;
    const params = {
        // id: info.workorderId,

        name: info.caller || '',
        phone: info.callnum || '',
        // type: info.workordercate,
        typeCode: '',
        // description: info.content,
        handleMethod: info.isend.toString(),
        department: '',

        area: info.area || '',
        address: info.address || '',
        career: info.career || '',
        concretePlan: info.concretePlan || '',
        grade: info.grade || '',
        // handlingMeasures: info.handlingMeasures && info.handlingMeasures.length > 0 ? info.handlingMeasures.split(',') : [],
        maritalStatus: info.maritalStatus || '',
        orderProblems: info.orderProblems || [],
        previousDiagnosis: info.previousDiagnosis || '',
        previousPsychotherapy: info.previousPsychotherapy || '',
        treatNow: info.treatNow || '',
        useMedicine: info.useMedicine || '',
        age: info.age || '',
        ageGroup: info.ageGroup || '',
        sex: info.sex || '',
    }

    form.value = {
        ...form.value,
        ...params
    }

}

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

    getPageListData('/order/workorder', {
        pageNum: 1,
        pageSize: 1,
        callnum: telNumber.value,
        listType: 0,
    }).then(({ data }) => {
        console.log(data, 'data')
        if (data?.length) {
            initOrder(data[0]);
        }
    });
}

const getUserInfo = async () => {
    if (!telNumber.value) {
        return;
    }
    telNumber.value = getOfffixNuber(telNumber.value)
    profile.value.phone = telNumber.value;
    form.value.phone = telNumber.value;
    getLastOrder();
    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 === 1 ? '男' : userInfo.sex == 0 ? '女' : '-',
            tel: userDecryptToAsterisk(userInfo.tel),
        };

        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 resetForm = () => {
    form.value = {
        name: '不详',
        area: '',
        address: '',
        career: '',
        concretePlan: '',
        grade: '',
        handlingMeasures: [],
        maritalStatus: '',
        orderProblems: [],
        previousDiagnosis: '',
        previousPsychotherapy: '',
        treatNow: '',
        useMedicine: '',
        phone: '',
        type: '',
        typeCode: '',
        description: '',
        // priority: 'medium',
        handleMethod: '1',
        // remarks: '',
        department: '',
    };
    // formRef.value.resetFields();
}

const submit = async () => {
    // 验证表单必填项
    // formRef.value.validate(async (valid) => {
    //     if (valid) {
            

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

    // });

    // 增加判断
    
    if (!form.value.phone) {
        ElMessage.error('请填写手机号');
        return;
    }
    if (!form.value.type) {
        ElMessage.error('请选择工单类型');
        return;
    }
    if (!form.value.description) {
        ElMessage.error('请填写问题描述');
        return;
    }
    if (!form.value.handleMethod) {
        ElMessage.error('请选择处理方式');
        return;
    }

    // console.log(form.value.handlingMeasures, 'submit');
    // return;

    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,
        workordercate: form.value.type[form.value.type.length - 1],
        area: form.value.area ? form.value.area[form.value.area.length - 1] : '',
        address: form.value.address,
        career: form.value.career,
        concretePlan: form.value.concretePlan,
        grade: form.value.grade,
        handlingMeasures: form.value.handlingMeasures && form.value.handlingMeasures.length? form.value.handlingMeasures.join(',') : '',
        maritalStatus: form.value.maritalStatus,
        orderProblems: vars.value?.map((o) => {
            return {
                mainProblemId: (o.mainProblemId.length ? o.mainProblemId[o.mainProblemId.length - 1] : 0),
                years: o.years,
            }
        }),
        previousDiagnosis: form.value.previousDiagnosis,
        previousPsychotherapy: form.value.previousPsychotherapy,
        treatNow: form.value.treatNow,
        useMedicine: form.value.useMedicine,
    };
    if (callid.value) params.callId = callid.value;
    if (form.value.age) params.age = form.value.age;
    if (form.value.ageGroup) params.ageGroup = form.value.ageGroup;
    if (form.value.sex) params.sex = form.value.sex;
    
    // 提交表单
    createPageData('/order/workorder', params).then((data) => {
        console.log(data, 'submit');
        if (data.state === 'success') {
            ElMessage.success('提交成功');
            resetForm()
            close()
        } else {
            ElMessage.error(data.message || '提交失败');
        }
        
    })
}
/** 关闭按钮 */
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: '你好，中国热线请假。',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '喂，你好，嗯，听这样哦，我是林州这个横岛岳湖人呃',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '什么问题啊？你确实是无法统一工作呃，按照说实体上头到现在都没有工作了',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '我来问违约金怎么事儿？嗯，他说他他说是月底工资，',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '这个麻问您一下，我这边给您登记反映，您是林州市哪里的？',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '林州恒大悦府，恒大悦府',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '嗯，乐府乐是那个舒心一个舒心，一个对那个乐是吧？',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '嗯，对嗯',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '恒大乐府分几七部分啊，',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '分级，你们一期二期分不分呃，一期同大月付一期几号楼几单元，十七号楼一单元幺九零一十七号楼一单元幺九零一',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '嗯，您怎么称呼先生啊？',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '免贵？我就我我姓李李松，你让李先生吧',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '给您单心恒大悦府在林州市的哪个路段。您说一下',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '在这个这个是河南一个湖，也就他就一个湖，河南一个湖，我也不知道这个是什么路段',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '那您没有路段的话，这个位置不明确，我这边就暂不给您反映啊',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '嗯，那个是可能是那个呃华城相府，',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '哪个路段？',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '不是那个那个是呃鲁八大道，',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '鲁八大道中段什么大道，',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '鲁班哪两个字卢班鲁班嗯，',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '鲁班大道与什么路交叉口？',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '嗯，鲁班大道一零米，',
    // }, 
    // {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '你们是是什么路来的，',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '你就说恒大悦府就行了。',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '那个那个零六就你一个恒大悦府必须哪个路段，',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '我们这边也得清楚，鲁班大鲁班大道开元街道，',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '恒大悦府是吗？',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '哦，对，康阳街道的嗯，',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '行好的，这边给您登记一下啊。',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '嗯，好了，不歉。',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '喂，哎，可以了。',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '呃',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '刚才我给你他们啊嗯已经给您登记了，稍后反应呃。',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '登登记了，你登记的，我是你知道我反映的什么吗？',
    // }, {
    //     direction: 1,
    //     timestamp: '14:30:24',
    //     page_content: '你不是家中暖气没热吗？不热吗？',
    // }, {
    //     direction: 2,
    //     timestamp: '14:30:24',
    //     page_content: '这不是不热，是没充暖，我给物业，我给物业联系了，物业，说是呃，他们这里公司就两个人，一共十七栋楼，他问他说这个还能等待几天一栋一栋的开呢，我们的我我们的供暖费都交了。',
    // }, {
    //     direction: 2,
    //     page_content: '看他几天，你看他几天',
    // }, {
    //     direction: 1,
    //     page_content: '你给我说个定是不是嗯就是人员少，担心无法正常供暖，是不是啊？',
    // }, {
    //     direction: 2,
    //     page_content: '他说还得几天，你现在十五号都是显示统一功能。你到现在就你你说排了几天，还得几天的。',
    // }, {
    //     direction: 1,
    //     page_content: '嗯，好的，这边已经有您同小弟业主反映过了，跟您跟他同甘办理啊。',
    // }, {
    //     direction: 2,
    //     page_content: '嗯嗯，行好的。',
    // }
])
// 关键词提示
const keywords = ref([
    {
        text: '产品使用方法',
        type: 'primary'
    },
    {
        text: '操作流程',
        type: 'success'
    },
    {
        text: '正面反馈',
        type: 'success'
    },
    {
        text: '满意度高',
        type: 'success'
    }
]);
// 建议话术
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 }
);

window.addEventListener('AsrMessageEvent', (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');

    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) => o.page_content).join('');
    if (text?.length > 10) {
        const res = await getSearchDocs(text);
        console.log(res, 'res');

        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.customerName = o.replace('【姓名】', '').replace('：', '');

        })

        aiLoading.value = false;

    } else {
        aiLoading.value = false;
    }
}
async function getSearchDocs(text) {
    // const params = {
    //     query: text,
    //     mode: "local_kb",
    //     kb_name: "mszsk",
    //     top_k: 1,
    //     score_threshold: 0.5,
    //     stream: true,
    //     model: "glm-4",
    //     temperature: 0.7,
    //     max_tokens: 0,
    //     prompt_name: "default",
    //     return_direct: false
    // }
    const params = {
        "model": "deepseek-r1:32b",
        "messages": [
            {
                "role": "user",
                "content": `请从以下咨询对话中提取关键信息生成结构化工单：
地理位置提取：识别来访者明确提到的居住地或当前位置
格式：[省/市/区/街道/楼栋号/房间号]（如未提及则标记"未知"）
注意模糊表述（如"北方城市""江浙地区"等需保留原话）
通话内容总结：
用第三人称概括核心问题（100字内）
保留以下关键要素：
• 主要症状描述（情绪/躯体/行为表现）
• 持续时间（使用"约X周/月/年"格式）
• 社会功能影响（工作/学习/人际关系）
• 既往病史（如提及）
过滤无关对话（寒暄、重复表述等）
工单类型分类：
根据DSM-5标准匹配最相关分类（单选）：
[抑郁障碍] [焦虑障碍] [强迫症] [创伤应激] [人格障碍] [适应障碍] [人际关系] [发展性问题] [其他]
【处理规范】
优先识别直接症状陈述（如"失眠三个月""不敢见人"）
注意隐喻表达（如"心里压着石头""像被困住"）
存在自伤/伤人表述时自动触发危机预警协议
多问题并存时按主诉优先级排序
示例对话：
[咨询师]：可以说说最近困扰您的事吗？
[来访者]：我在杭州工作两年了，最近三个月每天失眠，开会时手抖得厉害，上周在地铁里突然喘不过气...

示例输出：
【地理位置】：浙江省杭州市
【内容总结】：来访者诉持续三个月失眠症状，伴有社交场合手抖等躯体化表现，提及近期出现惊恐发作经历（地铁喘不过气），社会功能受损（工作受影响）
【工单类型】： 焦虑障碍`
            }, {
                "role": "user",
                "content": text
            }
        ],
        "stream": true
    };
    try {
        // 发送请求
        // let response = await fetch("http://192.168.1.89:7861/chat/chat",
        //     {
        //         method: "post",
        //         // responseType: "stream",
        //         headers: {
        //             "Content-Type": "application/json",
        //         },
        //         body: JSON.stringify(params),
        //     }
        // );

        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 ageGroupOptions = [{
    value: '≤18岁',
    label: '≤18岁'
}, {
    value: '19-29岁',
    label: '19-29岁'
}, {
    value: '30-54岁',
    label: '30-54岁'
}, {
    value: '≥55',
    label: '≥55'
}];

const updateAgeGroup = () => {
  const age = parseInt(form.value.age);
  if (!age || isNaN(age)) {
    return;
  } else if (age < 18) {
    form.value.ageGroup = '≤18岁';
  } else if (age < 30) {
    form.value.ageGroup = '19-29岁';
  }  else if (age < 54) {
    form.value.ageGroup = '30-54岁';
  } else {
    form.value.ageGroup = '≥55岁';
  }
};

const toDetail = (order) => {
    console.log(order, 'order');
    let query = {
        workordercode: order.workordercode,
        // type: type
    }

    sessionStorage.setItem('workQuery', JSON.stringify(query))

    router.push({ path : '/workHandle' }) 
} 

</script>
<style scoped>
* {
    transition: height 0.3s ease-out;
}

.workorder-container {
    max-width: 1000px;
    margin: 0 auto;
    padding-bottom: 80px;
}

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

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

:deep(.el-form-item--default) {
    margin-bottom: 0;
}

:deep(.el-input-number .el-input__wrapper) {
    padding-left: 8px;
    padding-right: 8px;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
    display: none;
}

:deep(.el-cascader),
:deep(.el-select) {
    width: 100%;
}

:deep(.el-form-item) {
    /* margin-bottom: 18px; */
    display: flex;
    align-items: center;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    width: 100px;
    text-align: right;
    padding-right: 12px;
}

:deep(.el-form-item__content) {
    flex: 1;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover) {
    box-shadow: 0 0 0 1px #409eff inset;
}

.workorder-card {
    max-height: calc(100vh - 120px);
}

.submit-bar {
    position: fixed;
    bottom: 0;
    right: 0;
    width: 100%;
    padding: 16px 40px;
    background: white;
    box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.05);
    z-index: 10;
    display: flex;
    justify-content: center;
    gap: 16px;
}
</style>