<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <!-- 悬浮通话控制区 -->
    <div ref="draggableDiv" class="fixed z-50" v-if="callPhoneFlag"
        :style="{ right: position.right + 'px', bottom: position.bottom + 'px' }" @mousedown.stop="startDrag">
        <!-- 悬浮通话状态卡片 -->
        <div class="bg-white rounded-lg shadow-lg p-3 flex items-center cursor-pointer hover:shadow-xl transition-shadow"
            @click.stop="toggleCallPanel" v-if="!showCallPanel">
            <span :class="`${stateObj[lineState].bgColor} font-medium mr-2 ml-2`">{{ stateObj[lineState].label }}</span>
            <div class="w-px h-5 bg-gray-300 mx-2"></div>
            <div v-if="[3, 4, 6].includes(lineState)" class="flex-1">
                <h4 class="font-medium text-sm">{{ currentCall.phone }}</h4>
                <div class="flex items-center text-xs text-gray-500 space-x-2">
                    <span class="flex items-center">
                        <el-icon class="mr-1 text-xs">
                            <Timer style="width: 1rem;height: 1rem;" />
                        </el-icon>
                        {{ callDuration }}
                    </span>
                </div>
            </div>
            <div v-else class="flex-1">
                <h4 class="font-medium text-sm">{{ useSocketStore().extensionNumber }}</h4>
                <div class="flex items-center text-xs text-gray-500 space-x-2">
                    <span class="flex items-center">
                        <el-icon class="mr-1 text-xs">
                            <Timer style="width: 1rem;height: 1rem;" />
                        </el-icon>
                        {{ callDuration }}
                    </span>
                </div>
            </div>
        </div>
        <!-- 通话面板 -->
        <div v-if="showCallPanel" class="bg-white rounded-lg shadow-2xl w-[320px]">
            <!-- 通话信息头部 -->
            <div class="p-6 bg-gradient-to-r from-blue-500 to-blue-600 rounded-t-lg text-white">
                <div class="flex flex-col">
                    <div class="flex items-center space-x-2">
                        <el-avatar :size="48" :src="defaultTubiao" class="flex-shrink-0" />
                        <!-- <div>
                            <h3 class="font-semibold text-lg">{{ currentCall.name || '暂无姓名' }}</h3>
                            <p class="text-sm opacity-90">{{ currentCall.phone || '暂无电话'}}</p>
                        </div> -->
                        <div class="min-w-0">
                            <h3
                                class="font-semibold text-lg flex items-center overflow-hidden text-ellipsis whitespace-nowrap">
                                {{ currentCall.name || '暂无姓名' }}
                                <span v-if="operText"
                                    class="text-sm bg-white/20 px-2 py-0.5 rounded-full ml-2 text-white/90">
                                    {{ operText }}
                                </span>
                            </h3>
                            <p class="text-sm opacity-90">
                                {{ currentCall.phone || '暂无电话' }}
                                <span style="margin-left: 0px;">{{ currentCall.locationName || '' }}</span>
                            </p>
                            <!-- 客户标签 -->
                            <div class="flex flex-wrap gap-2 mt-2 mb-2">
                                <el-tag v-for="tag in customerTags" :key="tag.labelName" :color="tag.color || 'white'"
                                    effect="dark" size="small" class="opacity-90 !rounded-full">
                                    {{ tag.labelName }}
                                </el-tag>
                            </div>
                        </div>
                    </div>
                    <el-button size="small" type="danger" circle class="!rounded-button absolute right-2 top-2"
                        @click="toggleCallPanel">
                        <el-icon>
                            <Close />
                        </el-icon>
                    </el-button>
                </div>
                <div class="flex items-center justify-center space-x-4 text-sm">
                    <span class="flex items-center">
                        <el-icon class="mr-1">
                            <Timer />
                        </el-icon>
                        {{ callDuration }}
                    </span>
                    <span class="flex items-center">
                        <el-icon class="mr-1">
                            <Location />
                        </el-icon>
                        {{ currentCall.locationName || '暂无地址' }}
                    </span>
                </div>
            </div>
            <!-- 功能区 -->
            <div class="p-4 border-b">
                <div class="grid grid-cols-5 gap-1">
                    <!-- .filter((o) => { return o.status.includes(lineState) }) -->
                    <button v-for="action in callActions" :key="action.name"
                        v-show="callStateData[callState].indexOf(action.name) !== -1 || (isMeetingStart && action.name === '回签')"
                        class="flex flex-col items-center justify-center p-2 rounded-lg hover:bg-gray-50"
                        @click="action.handler">
                        <el-icon class="text-xl mb-1" :style="{ color: action.iconColor }">
                            <component :is="action.icon" />
                        </el-icon>
                        <span class="text-xs">{{ action.name }}</span>
                    </button>
                    <button 
                    v-show="phoneType==='SIP' &&  lineState === 6" 
                    class="flex flex-col items-center justify-center p-2 rounded-lg hover:bg-gray-50"  @click="answerCallSip">
                        <el-icon class="text-xl mb-1" style="color:#67C23A"> 
                            <component is="PhoneFilled" />
                        </el-icon>
                        <span class="text-xs">接听</span>
                    </button>
                </div>
            </div>
            <!-- 拨号键盘 -->
            <div v-show="showDialpad" class="p-4 border-b h-[300px]">
                <div class="mb-4">
                    <el-input v-model="dialNumber" placeholder="输入电话号码" clearable
                        style="text-align: center; font-size: 1.25rem;" @keyup.enter="handleDialNumberInput" />
                </div>
                <div class="grid grid-cols-3 gap-4">
                    <button v-for="key in dialKeys" :key="key"
                        class="h-10 rounded-full bg-gray-50 hover:bg-gray-100 flex items-center justify-center text-base font-medium"
                        @click="appendDialNumber(key)">
                        {{ key }}
                    </button>
                </div>
            </div>
            <!-- 通讯录 -->
            <div v-if="showContacts" class="h-[300px] p-4" v-show="contentVisible">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-medium">通讯录</h3>
                    <el-input v-model="searchContactQuery" placeholder="输入姓名、电话或部门" :prefix-icon="Search" class="w-40"
                        style="width: 200px;" size="small" @keyup.enter="handleEnter" />
                </div>
                <div class="space-y-3 overflow-y-auto scrollbar-hide h-[230px] overflow-x-hidden">
                    <div v-for="(contact, index) in contacts" :key="index"
                        class="flex items-center p-2 hover:bg-gray-50 rounded-lg cursor-pointer">
                        <div class="flex items-center flex-1 min-w-0 mr-4">
                            <el-avatar :size="32" :src="contact.avatar" class="mr-3 flex-shrink-0" />
                            <div class="min-w-0 overflow-hidden">
                                <el-tooltip :content="contact.phone" placement="top" :hide-after="0">
                                    <p class="font-medium whitespace-nowrap overflow-hidden text-ellipsis">{{
                                        contact.name }}

                                        <span class="text-xs text-gray-500 ml-2">{{ contact.phone }}</span>
                                    </p>
                                </el-tooltip>
                                <p class="text-xs text-gray-500 whitespace-nowrap overflow-hidden text-ellipsis">{{
                                    contact.notes || '' }}
                                </p>
                            </div>
                        </div>
                        <el-button type="primary" circle class="!rounded-button flex-shrink-0"
                            @click="callOutClick(contact.phone)">
                            <el-icon>
                                <Phone />
                            </el-icon>
                        </el-button>
                    </div>
                </div>
            </div>
            <!-- 通话记录 -->
            <div v-else class="h-[300px] p-4" v-show="contentVisible">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-medium">最近通话</h3>
                    <!-- <el-button text>查看全部</el-button> -->
                </div>
                <div class="space-y-3 overflow-y-auto scrollbar-hide pr-2 h-[200px]">
                    <div v-for="(record, index) in callHistory" :key="index"
                        class="flex items-center justify-between p-2 hover:bg-gray-50 rounded-lg cursor-pointer">
                        <div class="flex items-center">
                            <el-avatar :size="32" :src="defaultTubiao" class="mr-3" />
                            <div>
                                <p class="font-medium">{{ record.phone || '未知' }}</p>
                                <div class="flex items-center space-x-2">
                                    <p class="text-xs text-gray-500">{{ record.answerTime }}</p>
                                    <!-- <p class="text-xs text-gray-500">{{ record.phone }}</p> -->
                                </div>
                            </div>
                        </div>
                        <el-icon @click="callOutClick(record.phone)"
                            :style="{ color: record.type == '1' ? '#409EFF' : '#F56C6C' }">
                            <Phone />
                        </el-icon>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import {

    ElMessage,
} from 'element-plus'
import { getPhoneFix } from '@/api/main/main'
import useSocketStore from '@/store/modules/socket'
import { Send, ws } from '@/utils/telWebsocket'
import { hidePhone } from '@/utils/tools';
import { useRouter } from 'vue-router';
import { getPageListData, createPageData } from '@/api/main/system/system'
import defaultTubiao from '@/assets/images/defaultTubiao.png'
import { getCallSate, getUnprefixNuber } from '@/utils/index';
import { answerSip, hangUp, sipCall } from '@/utils/jsSip'


import {
    UserFilled,
    Phone,
    Message,
    Location,
    Document,
    Search,
    Timer,
    Switch,
    Service,
    CircleClose,
    Operation,
    Close,
    VideoCamera,
    Microphone,
    Connection,
    List,
    Notebook,
    Mute
} from '@element-plus/icons-vue';
const router = useRouter()
const showCallPanel = ref(false);

const draggableDiv = ref(null); // 获取 DOM 元素
const position = ref({ right: 14, bottom: 20 }); // 存储 div 的位置
let offset = { x: 0, y: 0 }; // 存储鼠标点击时的偏移量
let isDragging = ref(false); // 是否正在拖动
const phoneType = ref(import.meta.env.VITE_APP_PHONE_TYPE)
const searchQuery = ref('');
const searchContactQuery = ref('');
const filteredContacts = computed(() => {
    if (!searchContactQuery.value) return contacts.value;
    const query = searchContactQuery.value.toLowerCase();
    return contacts.value.filter(contact =>
        contact.name.toLowerCase().includes(query) ||
        contact.phone.includes(query) ||
        contact.department.toLowerCase().includes(query)
    );
});

const getBooks = (key = '') => {
    const params = {
        pageNum: 1,
        pageSize: 50,
    }
    contacts.value = []
    if (key) params['key'] = key
    getPageListData('/system/addressbook', params).then(res => {
        if (res?.data?.length) {
            contacts.value = res.data.map((o) => {
                return {
                    avatar: '/src/assets/images/defaultTubiao.png',
                    name: o.name,
                    phone: o.mobile,
                    notes: o.notes,
                }
            });
        }
    })
}

const callDuration = ref('00:00:00');
let timer: number;
const startTime = ref(Date.now());
const updateCallDuration = () => {
    const diff = Math.floor((Date.now() - startTime.value) / 1000);
    const hours = Math.floor(diff / 3600).toString().padStart(2, '0');
    const minutes = Math.floor((diff % 3600) / 60).toString().padStart(2, '0');
    const seconds = Math.floor(diff % 60).toString().padStart(2, '0');
    callDuration.value = `${hours}:${minutes}:${seconds}`;
};

const lineState = ref(7);
const msgs: any = ref([])

const callPhoneFlag = ref(false)

const callData = ref({});

const initCall = (isPause = false) => {
    // customerTags = customerTags.map((o) => {
    //     o.show = false
    //     return o
    // })
    if (!isPause) callDuration.value = '00:00:00'
    // startTime.value = Date.now()
    if (timer) {
        clearInterval(timer);
        timer = null
    }
    useSocketStore().setCallId('')
}

onMounted(() => {
    getBooks();
    // document.removeEventListener('mousemove', handleDrag);
    // document.removeEventListener('mouseup', stopDrag);
    initWs();
    getcalllogData()

});

const handleEnter = () => {
    if (searchContactQuery.value) getBooks(searchContactQuery.value);
}

const stateObj = {
    0: { key: 'offline', label: '离线', count: 0, bgColor: 'text-red-500' },
    1: { key: 'offline', label: '登陆中', count: 0, bgColor: 'bg-green-300' },
    2: { key: 'online', label: '空闲', count: 0, bgColor: 'text-green-500' },
    3: { key: 'calling', label: '通话中', count: 0, bgColor: 'text-blue-500' },
    4: { key: 'afterCall', label: '话后处理', count: 0, bgColor: 'text-purple-500' },
    5: { key: 'idle', label: '小休', count: 0, bgColor: 'text-yellow-500' },
    6: { key: 'afterCall', label: '振铃', count: 0, bgColor: 'text-blue-300' },
    7: { key: 'offline', label: '离线', count: 0, bgColor: 'text-red-500' },
}

const callState = ref(0) // 0 空闲/默认，1来电通话中，2来电通话保持中，10 外呼通话中/振铃中

const callDirection = ref(1) // 1来电，2外呼
const changeState = (state) => {
    if (state === 2) {
        console.log('空闲', state)
        initCall()
        callState.value = 0
        callPhoneFlag.value = true
        operText.value = ''
    } else if ([0, 7].includes(state)) {
        initCall()
        callPhoneFlag.value = false
    } else if (state === 6) {
        callState.value = 10
        initCall()
        // showPhone()
        showCallPanel.value = true
    } else if (state === 3) {
        if (callDirection.value == 1) {
            callState.value = 1
        } else if (callDirection.value == 2) {
            callState.value = 10
        }

        startTime.value = Date.now()
        if (!timer) timer = window.setInterval(updateCallDuration, 1000);
        getLabels();
    } else if (state === 4) {
        callState.value = 0
        saveTranslate(currentCall.value.callid, msgs.value)
        initCall(true)
    }
}
const state = {
    0: '离线',
    1: '登录中',
    2: '空闲',
    3: '通话中',
    4: '话后处理中',
    5: '忙碌',
    6: '振铃',
    7: '注销',
}


const showAsr = ref(import.meta.env.VITE_APP_AI_ASR === 'true');
const saveTranslate = (callid, translate) => {
    if (!translate || !translate.length || !callid || !showAsr) return;
    createPageData('/call/translate', {
        callid,
        translate: JSON.stringify(translate),
    }).then(() => {

    }).catch(() => {

    })
}

function answerCallSip (data) {
  answerSip(callType.value)
//   inComingHandle()
}
function dropCallSip () {
  hangUp()
}
window.addEventListener("sipInComming", (e) => {
  inCommingSip(e.detail, 1)
});
window.addEventListener("sipCallOut", (e) => {
  inCommingSip(e.detail, 2)
});
function inCommingSip (res, direction) {
//   mediaStream()
  if (direction === 1) {
    // sipPhoneFlag.value = true
    // videoBtnFlag.value = true
  }
  res.session.on("confirmed", function (data) {
    if (res.session.connection.getReceivers) {
      let remoteStream = new MediaStream();
      res.session.connection.getReceivers().forEach(element => {
        // track可能一个音轨或者视频轨迹
        remoteStream.addTrack(element.track)
      })
      if (callType.value === 'VIOCE') {
        audioElement.value.srcObject = remoteStream
        audioElement.value.onloadedmetadata = function () {
          audioElement.value.play();
          audioElement.value.muted = false;
        //   sipPhoneFlag.value = false
        }
      } else if (callType.value === 'VIDEO') {
        videoElement.value.srcObject = remoteStream
        videoElement.value.onloadedmetadata = function () {
          videoElement.value.play();
          videoElement.value.muted = false;
        //   sipPhoneFlag.value = false
        }
      }
    }
  })

}
const initWs = () => {
    ws.addEventListener('message', function (evt) {
        const telWSData = JSON.parse(evt.data)
        if (telWSData) {
            switch (telWSData.Type.toLowerCase()) {
                // case 'linestate': // 这个目前应该没用了
                //     lineState.value = telWSData.Result
                //     changeState(lineState.value)
                //     break
                case 'callid': {
                    currentCall.value.name = '';
                    currentCall.value.phone = getUnprefixNuber(telWSData.Number)
                    currentCall.value.truePhone = hidePhone(telWSData.Number)
                    currentCall.value.callid = telWSData.CallID
                    useSocketStore().setCallId(telWSData.CallID)
                    console.log(currentCall.value, 'currentCall.value')
                    getUserInfo(currentCall.value.phone)

                    if (currentCall.value.phone.toString().length > 4) {
                        getCallMobile(currentCall.value.phone)
                    }
                }; break;
                case 'state': // 坐席自身状态
                    lineState.value = telWSData.State
                    // if(pphoneType.value === 'SIP' && lineState.value === 7) {
                    //     useSocketStore().setLineState(state[2])
                    // }else {
                    //     useSocketStore().setLineState(state[lineState.value])
                    // }
                    
                    changeState(lineState.value)
                    break
                case 'incoming': // 来电
                    {
                        msgs.value = []
                        currentCall.value.name = '';
                        currentCall.value.phone = getUnprefixNuber(telWSData.Number)
                        currentCall.value.truePhone = hidePhone(telWSData.Number)
                        currentCall.value.callid = telWSData.CallID
                        console.log(currentCall.value, 'currentCall.value')
                        getUserInfo(currentCall.value.phone)
                        if (currentCall.value.phone.toString().length > 4) {
                            getCallMobile(currentCall.value.phone)
                        }
                        router.push({
                            path: '/inComming/callScreen/' + telWSData.Number,
                            query: {
                                callNumber: telWSData.Number,
                                callid: telWSData.CallID,
                            }
                        });
                        callDirection.value = 1
                        console.log(telWSData, 'telWSData')
                    };
                    break
                case 'asr': // 坐席辅助
                    // incomingBack(telWSData)
                    asrMessageEvent(telWSData)
                    break
            }
        }
    })
}



const asrMessageEvent = (msg) => {
    msgs.value.push(msg);
    const event = new CustomEvent(`AsrMessageEvent-${currentCall.value.callid}`, { detail: {
        ...msg,
        // callid: currentCall.value.callid,
    } });
    window.dispatchEvent(event);
}

onUnmounted(() => {
    if (timer) {
        clearInterval(timer);
    }
});
const showDialpad = ref(false);
const dialpadMode = ref<'dial' | 'transfer' | 'conference'>('dial');
const dialNumber = ref('');
const contentVisible = ref(true);
const currentCall = ref({
    phone: '', // 手机号
    truePhone: '',
    callid: '',
    locationName: '',
    address: '',
    phoneNumber: '',
    name: '',
    avatar: '',
    location: '',

});
const showContacts = ref(false);
const contacts = ref([
    // {
    //     name: '李晓华',
    //     phone: '13812345678',
    //     avatar: 'https://mastergo.com/ai/api/search-image?query=professional asian businessman portrait with confident expression in modern office setting clean simple background&width=100&height=100&orientation=squarish',
    //     department: '销售部'
    // },
    // {
    //     name: '王建国',
    //     phone: '13987654321',
    //     avatar: 'https://mastergo.com/ai/api/search-image?query=mature asian business man portrait with warm smile in corporate environment clean simple background&width=100&height=100&orientation=squarish',
    //     department: '技术部'
    // },
    // {
    //     name: '张美玲',
    //     phone: '13567891234',
    //     avatar: 'https://mastergo.com/ai/api/search-image?query=elegant asian businesswoman portrait with gentle smile in professional setting clean simple background&width=100&height=100&orientation=squarish',
    //     department: '客服部'
    // }
]);

const isMeetingStart = ref(false); // 会议发起成功之后，呼入人是静音的需要点击回签操作，如果为true，则可以点击回签


const handleDialNumberInput = () => {
    // 判断号码是否是数字
    if (!dialNumber.value.match(/^[0-9]*$/) || dialNumber.value.length > 11) return ElMessage.error('请输入正确的电话号码');

    const socketParams: any = {
        AgentId: useSocketStore().accountNumber,
        AgentExten: useSocketStore().extensionNumber,
        DestinationNumber: dialNumber.value,
        Type: ''
    };

    // 'dial' | 'transfer' | 'conference'
    if (dialpadMode.value === 'dial') {
        socketParams.Type = 'MakeCall'
        operText.value = '外呼中'
    };
    if (dialpadMode.value === 'transfer') {
        socketParams.Type = 'Transfer'
        operText.value = '转接中'
    };
    if (dialpadMode.value === 'conference') {
        socketParams.Type = 'Meeting'
        operText.value = '会议连接中'
    };
    if (!socketParams.Type) return ElMessage.error('请选择拨号方式');

    getPhoneFix(dialNumber.value).then((data) => {
        if (data.state === 'success') {

            socketParams.DestinationNumber = data.data[0]
            currentCall.value.phone = socketParams.DestinationNumber
            currentCall.value.truePhone = hidePhone(socketParams.DestinationNumber)

            if (['Meeting'].includes(socketParams.Type)) {
                socketParams.Mute = true;
            }

            // 发送socket请求
            Send(socketParams, (data) => {
                if (data.Result === true) {
                    if (data.Type === 'MakeCall') {
                        callDirection.value = 2
                        ElMessage.success('外呼成功')
                        operText.value = '外呼通话中'
                    }
                    if (data.Type === 'Transfer') {
                        ElMessage.success('转接成功')
                        operText.value = ''
                    }
                    if (data.Type === 'Meeting') {
                        ElMessage.success('会议成功')
                        operText.value = '会议中'
                        isMeetingStart.value = true;
                    }
                } else {
                    if (data.Type === 'Meeting') {
                        // ElMessage.success('会议成功')
                        operText.value = '会议中'
                        isMeetingStart.value = true;
                    }
                    operText.value = ''
                    ElMessage.error('操作失败')
                }
            })

        }
    })
};


const holdEvent = (type) => {

    const socketParams = {
        Type: type,
        AgentId: useSocketStore().accountNumber,
        AgentExten: useSocketStore().extensionNumber
    }
    Send(socketParams, (data) => {
        // scoketState.value = '通话保持中'

        if (type === 'HoldOn') {
            useSocketStore().setLineState('通话保持中')
            callState.value = 2
        }
        if (type === 'HoldOff') {
            useSocketStore().setLineState('通话中')
            callState.value = 1
        }

        if (type === 'DropCall') {
            operText.value = ''
        }

    })
}

// 回签操作事件
const meetingMuteOffEvent = () => {
    console.log('meetingMuteOffEvent')
    if (isMeetingStart.value) {
        const socketParams = {
            Type: 'MeetingMuteOff',
            AgentId: useSocketStore().accountNumber,
            AgentExten: useSocketStore().extensionNumber
        }
        Send(socketParams, (data) => {
            console.log('meetingMuteOffEvent-msg:', data)
            if (data.Result === true) {
                if (data.Type === 'MeetingMuteOff') {
                    ElMessage.success('回签成功');
                    isMeetingStart.value = false;
                }
                
            } else {
                ElMessage.error('回签操作失败')
            }
        })

    }
}

const operText = ref('');
const callStateData = ref({
    0: ['外呼', '通讯录'],
    1: ['转接', '会议', '挂断', '保持', '满意度', '通讯录'],
    2: ['转接', '会议', '挂断', '取消', '通讯录'],
    10: ['挂断', '通讯录'],
})
const callActions = [
    { name: '外呼', status: [2], icon: 'Operation', iconColor: '#3b82f6', handler: () => toggleDialpad('dial') },
    //   { name: '视频', icon: 'VideoCamera', iconColor: 'text-green-500', handler: () => handleVideo() },
    //   { name: '静音', icon: 'Microphone', iconColor: 'text-yellow-500', handler: () => handleMute() },
    { name: '转接', status: [3], icon: 'Switch', iconColor: '#a855f7', handler: () => toggleDialpad('transfer') },
    { name: '会议', status: [2, 3], icon: 'Connection', iconColor: '#6366f1', handler: () => toggleDialpad('conference') },
    { name: '回签', status: [3], icon: 'Back', iconColor: '#6366f1', handler: () => meetingMuteOffEvent() },
    { name: '通讯录', status: [2, 3, 4, 5], icon: 'Notebook', iconColor: 'text-orange-500', handler: () => toggleContacts() },
    { name: '挂断', status: [3], icon: 'CircleClose', iconColor: '#ef4444', handler: () => dropCallSip() },
    { name: '保持', status: [3], icon: 'Mute', iconColor: '#ef4444', handler: () => holdEvent('HoldOn') },
    { name: '取消', status: [3], icon: 'Mute', iconColor: '#ef4444', handler: () => holdEvent('HoldOff') },
    { name: '满意度', status: [3], icon: 'CircleClose', iconColor: '#ef4444', handler: () => holdEvent('TurnMyd') },
    // { name: '接听', status: [6], icon: 'Headset', iconColor: 'text-red-500', handler: () => holdEvent('DropCall') },

];
const callHistory = ref([])

function getcalllogData() {
    callHistory.value = []
    const params = {
        pageNum: 1,
        pageSize: 20,

    }
    getPageListData('/call/calllog', params).then(
        ({ data, total }) => {
            const newArray = data
            callHistory.value = newArray
        }
    )
}

function getUserInfo(phoneNumber) {

    getPageListData('/patient/patient', { phoneNumber }).then(
        ({ data, total }) => {
            const newArray = data[0]
            currentCall.value.phoneNumber = phoneNumber
            if (newArray) {
                currentCall.value.name = newArray.name
                currentCall.value.avatar = newArray.avatar
                currentCall.value.address = newArray.address
                
            } else {
                currentCall.value.name = ''
                currentCall.value.avatar = ''
                currentCall.value.address = ''
            }
            

        }
    )
}
function getCallMobile(phoneNumber) {
    const params = {
        mobilePrefix: phoneNumber.substring(0, 7),
        pageNum: 1,
        pageSize: 10
    }
    getPageListData('/call/mobile', params).then(
        ({ data, total }) => {
            const newArray = data[0]
            currentCall.value.locationName = newArray.locationName
        }
    )
}
const dialKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#'];


const toggleCallPanel = () => {
    if (isDragging.value) return;
    showCallPanel.value = !showCallPanel.value;
};
const toggleDialpad = (mode: 'dial' | 'transfer' | 'conference') => {
    if (dialpadMode.value === mode && showDialpad.value) {
        showDialpad.value = false;
        contentVisible.value = true;
    } else {
        dialpadMode.value = mode;
        showDialpad.value = true;
        contentVisible.value = false;
    }
};
const toggleContacts = () => {
    if (showContacts.value && contentVisible.value) {
        showContacts.value = false;
    } else {
        showContacts.value = true;
        showDialpad.value = false;
        contentVisible.value = true;
    }
};
const appendDialNumber = (key: string) => {
    dialNumber.value += key;
};
const handleVideo = () => {
    // 处理视频通话
};
const handleMute = () => {
    // 处理静音
};
const handleRecords = () => {
    // 处理通话记录
};

const handleCall = (filteredContacts) => {
    showContacts.value = false;
    showCallPanel.value = true;
    currentCall.value.name = contact.name
    currentCall.value.phone = contact.phone
    currentCall.value.avatar = contact.avatar
}

function callOutClick(phone) {
    showContacts.value = false;
    showCallPanel.value = true;
    dialNumber.value = phone
    handleDialNumberInput()
}
const handleTransfer = () => {
    // 处理转接
};
const handleConference = () => {
    // 处理会议
};
const handleHangup = () => {
    // 处理挂断
    scoketDatas.value = {
        Type: 'DropCall',
        AgentId: useSocketStore().accountNumber,
        AgentExten: useSocketStore().extensionNumber
    }
    Send(scoketDatas.value, (data) => {
        // console.log('挂断成功')
    })
};

// 开始拖动
const startDrag = (e) => {
    e.preventDefault();

    // 计算鼠标点击位置与 div 左上角的偏移量
    const rect = draggableDiv.value.getBoundingClientRect();
    offset.x = e.clientX - (window.innerWidth - rect.width - position.value.right);
    offset.y = e.clientY - (window.innerHeight - rect.height - position.value.bottom);

    // 监听鼠标移动和释放事件
    window.addEventListener('mousemove', onDrag);
    window.addEventListener('mouseup', stopDrag);
};

// 拖动中
const onDrag = (e) => {
    const rect = draggableDiv.value.getBoundingClientRect();

    // 如果移动距离大于 5px，则视为拖动
    // isDragging.value = true;

    // 计算新的 right 和 bottom 值
    const newRight = window.innerWidth - (e.clientX - offset.x) - rect.width;
    const newBottom = window.innerHeight - (e.clientY - offset.y) - rect.height;

    if (Math.abs(newRight - position.value.right) > 5 || Math.abs(newBottom - position.value.bottom) > 5) {
        isDragging.value = true;
    }

    // 更新 div 的位置
    position.value.right = Math.max(0, newRight);
    position.value.bottom = Math.max(0, newBottom);
};

// 停止拖动
const stopDrag = () => {

    // 移除事件监听
    window.removeEventListener('mousemove', onDrag);
    window.removeEventListener('mouseup', stopDrag);

    setTimeout(() => {
        isDragging.value = false;
    }, 1000);
};

// 客户标签
let customerTags = [
    // {
    //         "labelName": "黑名单",
    //         "weight": 100,
    //         "color": "大红色",
    //         "createTime": "2025-05-12 17:23:26"
    //     }
    // { text: '多次来电', type: 'warning', show: false },
    // { text: '黑名单', type: 'danger', show: false },
    //   { text: 'VIP客户', type: 'success' },
    //   { text: '投诉倾向', type: 'warning' },
    //   { text: '高频咨询', type: 'info' }
];

const getLabels = () => {
    console.log(currentCall.value.phone, 'getLabels')
    if (!currentCall.value.phone) return;
    getPageListData(`/common/getlabel/${currentCall.value.phone}`).then(
        ({ data }) => {
            console.log(data, '标签');
            customerTags = data.splice(0, 5);
        }
    )
}

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

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

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

.slide-enter-active,
.slide-leave-active,
.container {
    transition: all 0.3s ease-out;
}

.slide-enter-from,
.slide-leave-to {
    transform: translateX(-20px);
    opacity: 0;
}

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

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

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

.el-tabs {
    height: calc(100vh - 5rem);
    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;
}
</style>