<!-- 呼叫中心客户信息页面：使用 TailwindCSS 构建界面 -->
<template>
    <div class="min-h-screen-nav-height bg-gray-50">
        <div class="container mx-auto px-4 pt-4 pb-6 flex gap-6">
            <!-- 左侧信息区 -->
            <div class="w-[35%]">
                <el-tabs type="border-card" class="h-full" @tab-change="tabChange">
                    <!-- 客户档案 -->
                    <el-tab-pane>
                        <template #label>
                            <div class="flex items-center">
                                <el-icon class="mr-2"><UserFilled /></el-icon>客户档案
                            </div>
                        </template>

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


        </div>
    </div>
</template>

<script setup>
// 引入组件和工具
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
    Document, 
    UserFilled, 
    Phone, 
    Location, 
    Edit, 
    Service, 
    Loading,
    // 删除未使用的图标引入
} from '@element-plus/icons-vue';

// 引入API和工具函数
import { getPageListData, createPageData, editPageData } from '@/api/main/system/system';


// 状态变量定义
const route = useRoute();
const router = useRouter();
const isEditing = ref(false);
const profile = ref({
    name: '',
    sex: '0',
    phone: '',
    address: '',
    registerDate: '',
});
const customerTags = ref([]);
const showAsr = ref(true);
const transcripts = ref([]);
const keywords = ref([]);
const recommendedKnowledge = ref([]);
const callSearchQuery = ref([]);
const callData = ref([]);
const callLoading = ref(false);
const callNoMore = ref(false);
const orderSearchQuery = ref([]);
const displayedActivities = ref([]);

// DOM引用
const transcriptContainer = ref(null);
const callContainer = ref(null);
const workOrderContainer = ref(null);

/**
 * 初始化页面数据
 * 加载客户信息、标签等
 */
onMounted(async () => {
    // 获取路由参数
    const telNumber = route.query.phone || '';
    if (telNumber) {
        await loadCustomerProfile(telNumber);
        await loadCustomerTags(telNumber);
    }
    
    // 初始化其他数据
    initializeData();
});

/**
 * 加载客户档案信息
 * @param {string} phone - 客户电话号码
 */
async function loadCustomerProfile(phone) {
    try {
        const response = await getPageListData('/customer/profile', { phone });
        if (response.data && response.data.length > 0) {
            profile.value = response.data[0];
        }
    } catch (error) {
        ElMessage.error('获取客户信息失败');
    }
}

/**
 * 加载客户标签
 * @param {string} phone - 客户电话号码
 */
async function loadCustomerTags(phone) {
    try {
        const response = await getPageListData('/customer/tags', { phone });
        if (response.data) {
            customerTags.value = response.data;
        }
    } catch (error) {
        ElMessage.error('获取客户标签失败');
    }
}

/**
 * 初始化页面其他数据
 */
function initializeData() {
    // 初始化通话记录查询时间范围
    const now = new Date();
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(now.getDate() - 30);
    callSearchQuery.value = [thirtyDaysAgo, now];
    orderSearchQuery.value = [thirtyDaysAgo, now];
    
    // 加载初始数据
    loadCallRecords();
    loadWorkOrders();
}

/**
 * 标签页切换处理
 * @param {string} tab - 标签页名称
 */
function tabChange(tab) {
    // 根据标签页加载不同数据
    if (tab === '2') { // 通话记录标签
        loadCallRecords();
    } else if (tab === '3') { // 工单记录标签
        loadWorkOrders();
    }
}

/**
 * 加载通话记录
 */
async function loadCallRecords() {
    if (callLoading.value) return;
    callLoading.value = true;
    
    try {
        // 构建查询参数
        const params = {
            phone: profile.value.phone,
            startTime: formatDateTime(callSearchQuery.value[0]),
            endTime: formatDateTime(callSearchQuery.value[1]),
            page: 1,
            limit: 20
        };
        
        const response = await getPageListData('/call/records', params);
        callData.value = response.data || [];
        callNoMore.value = callData.value.length < 20;
    } catch (error) {
        ElMessage.error('获取通话记录失败');
    } finally {
        callLoading.value = false;
    }
}

/**
 * 加载工单记录
 */
async function loadWorkOrders() {
    // 实现工单记录加载逻辑
    // ... existing code ...
}

/**
 * 通话记录日期范围变更处理
 */
function callChange() {
    callData.value = [];
    callNoMore.value = false;
    loadCallRecords();
}

/**
 * 工单记录日期范围变更处理
 */
function orderChange() {
    displayedActivities.value = [];
    loadWorkOrders();
}

/**
 * 获取通话状态文本
 * @param {number} callType - 呼叫类型：1-呼入，2-呼出
 * @param {number} isAnswer - 是否接听：0-未接听，1-已接听
 * @returns {string} 状态文本
 */
function getCallSate(callType, isAnswer) {
    if (callType === 1) {
        return isAnswer === 1 ? '呼入-已接听' : '呼入-未接听';
    } else {
        return isAnswer === 1 ? '呼出-已接听' : '呼出-未接听';
    }
}

/**
 * 计算通话时长
 * @param {string} startTime - 开始时间
 * @param {string} endTime - 结束时间
 * @returns {string} 格式化的时长
 */
function getTimeLimit(startTime, endTime) {
    // 计算时间差并格式化
    // ... existing code ...
    return '00:00:00'; // 示例返回值
}

/**
 * 移除HTML标签
 * @param {string} html - 包含HTML标签的文本
 * @returns {string} 纯文本
 */
function stripHtmlByRegex(html) {
    if (!html) return '';
    return html.replace(/<[^>]*>/g, '');
}

/**
 * 聊天区域鼠标事件处理
 * @param {number} type - 事件类型：0-进入，1-离开
 */
function chatMouse(type) {
    // 处理鼠标进入/离开聊天区域的逻辑
    // ... existing code ...
}

/**
 * 获取知识库列表
 * @param {string} keyword - 搜索关键词
 */
async function getKnowledgeBaseList(keyword) {
    try {
        const response = await getPageListData('/knowledge/search', { keyword });
        recommendedKnowledge.value = response.data || [];
    } catch (error) {
        ElMessage.error('获取知识库信息失败');
    }
}

/**
 * 打开知识详情
 * @param {string} docId - 文档ID
 */
function openKnowledgeAi(docId) {
    // 打开知识详情页面
    // ... existing code ...
}

/**
 * 性别变更处理
 */
function sexChange() {
    // 处理性别变更逻辑
    // ... existing code ...
}

/**
 * 测试电话功能
 */
function testPhone() {
    // 测试电话功能
    // ... existing code ...
}
</script>

<style scoped>
/* 自定义样式 */
.min-h-screen-nav-height {
    min-height: calc(100vh - 60px);
}

/* 滚动条样式优化 */
:deep(.el-scrollbar__wrap) {
    overflow-x: hidden;
}

/* 标签页样式 */
:deep(.el-tabs__item) {
    font-size: 14px;
}

/* 渐变效果 */
.from-white {
    --tw-gradient-from: #ffffff;
    --tw-gradient-stops: var(--tw-gradient-from), transparent;
}
</style>