<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <!-- 悬浮通话控制区 -->
    <div class="fixed bottom-6 left-64 z-50" v-if="callPhoneFlag">
        <!-- 悬浮通话状态卡片 -->
        <div class="bg-white rounded-lg shadow-lg p-3 flex items-center cursor-pointer hover:shadow-xl transition-shadow"
            @click="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 justify-between items-center mb-4">
                    <div class="flex items-center space-x-2">
                        <el-avatar :size="48" :src="defaultTubiao" />
                        <div>
                            <h3 class="font-semibold text-lg">{{ currentCall.name || '暂无姓名' }}</h3>
                            <p class="text-sm opacity-90">{{ currentCall.phone || '暂无电话'}}</p>
                        </div>
                    </div>
                    <el-button size="small" type="danger" circle class="!rounded-button" @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.location || '暂无地址' }}
                    </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"
                        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>
                </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" />
                </div>
                <div class="space-y-3 overflow-y-auto scrollbar-hide pr-2 h-[200px]">
                    <div v-for="(contact, index) in filteredContacts" :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="contact.avatar" class="mr-3" />
                            <div>
                                <p class="font-medium">{{ contact.name }}</p>
                                <p class="text-xs text-gray-500">{{ contact.phone }}</p>
                            </div>
                        </div>
                        <el-button type="primary" circle class="!rounded-button" @click="handleCall(contact)">
                            <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 } from '@/api/main/system/system'
import defaultTubiao from '@/assets/images/defaultTubiao.png'
import { getCallSate,getUnprefixNuber} from '@/utils/index';

const router = useRouter();
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 showCallPanel = ref(false);
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 dragRef = ref<HTMLElement | null>(null);
// const position = ref({ x: window.innerWidth - 350, y: window.innerHeight - 100 });
// const isDragging = ref(false);
// let initialMousePosition = { x: 0, y: 0 };
// let initialElementPosition = { x: 0, y: 0 };

// const startDrag = (event: MouseEvent) => {
//     isDragging.value = true;
//     initialMousePosition = { x: event.clientX, y: event.clientY };
//     initialElementPosition = { x: position.value.x, y: position.value.y };

//     document.addEventListener('mousemove', handleDrag);
//     document.addEventListener('mouseup', stopDrag);
// };

// const handleDrag = (event: MouseEvent) => {
//     if (!isDragging.value) return;

//     const dx = event.clientX - initialMousePosition.x;
//     const dy = event.clientY - initialMousePosition.y;

//     position.value = {
//         x: Math.min(Math.max(0, initialElementPosition.x + dx), window.innerWidth - (dragRef.value?.offsetWidth || 0)),
//         y: Math.min(Math.max(0, initialElementPosition.y + dy), window.innerHeight - (dragRef.value?.offsetHeight || 0))
//     };
// };

// const stopDrag = () => {
//     isDragging.value = false;
//     document.removeEventListener('mousemove', handleDrag);
//     document.removeEventListener('mouseup', stopDrag);
// };

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 callPhoneFlag = ref(false)

const callData = ref({});

const initCall = (isPause = false) => {
    if (!isPause) callDuration.value = '00:00:00'
    // startTime.value = Date.now()
    if (timer) {
        clearInterval(timer);
    }
}

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

});

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) => {
    // console.log(newValue, 'lineState')
    if (state === 2) {
        initCall()
        callState.value = 0
        callPhoneFlag.value = true
    } 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 ) {
            allState.value = 10
        }
        startTime.value = Date.now()
        if (!timer) timer = window.setInterval(updateCallDuration, 1000);
    } else if (state === 4) {
        initCall(true)
    }
}
const state = {
    0: '离线',
    1: '登录中',
    2: '空闲',
    3: '通话中',
    4: '话后处理中',
    5: '忙碌',
    6: '振铃',
    7: '注销',
}
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 'state': // 坐席自身状态
                    lineState.value = telWSData.State
                    useSocketStore().setLineState(state[lineState.value])
                    changeState(lineState.value)
                    break
                case 'incoming': // 来电
                    {
                        currentCall.value.phone = getUnprefixNuber(telWSData.Number) 
                        currentCall.value.truePhone = hidePhone(telWSData.Number)
                        getUserInfo(currentCall.value.phone)
                        router.push({
                            path: '/inComming/callScreen/' + telWSData.Number,
                            query: {
                                callid: telWSData.CallID,
                            }
                        });
                        callDirection.value = 1
                        console.log(telWSData, 'telWSData')
                    };
                    break
                case 'asr': // 坐席辅助
                    // incomingBack(telWSData)
                    // asrMessageEvent(telWSData)
                    break
            }
        }
    })
}

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: any = ref({
    // name: '赵梦琪',
    // phone: '138 **** 5678',
    // truePhone: '13812345678',
    // avatar: 'https://ai-public.mastergo.com/ai/img_res/912893976024911f35afb12190e1c1f7.jpg',
    // 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 handleDialNumberInput = () => {
    // 判断号码是否是数字
    if (!dialNumber.value.match(/^[0-9]*$/) || dialNumber.value.length > 11) return ElMessage.error('请输入正确的电话号码');

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

    // 'dial' | 'transfer' | 'conference'
    if (dialpadMode.value === 'dial') socketParams.Type = 'MakeCall';
    if (dialpadMode.value === 'transfer') socketParams.Type = 'Transfer';
    if (dialpadMode.value === 'conference') socketParams.Type = 'Meeting';
    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)
            console.log(socketParams, 'socketParams')
            // 发送socket请求
            Send(socketParams, (data) => {
                if (data.Type === 'MakeCall') {
                    if (data.Result === true) {
                        callDirection.value = 2
                        ElMessage.success('外呼成功')
                    } else {
                        ElMessage.error('外呼失败')
                    }
                }
            })
        }
    })
};


const holdEvent = (type) => {

  const socketParams = {
    Type: type,
    AgentId: useSocketStore().accountNumber,
    AgentExten: useSocketStore().extensionNumber
  }
  Send(socketParams, (data) => {
    // console.log('通话保持中成功')
    // scoketState.value = '通话保持中'
    
    if (type === 'HoldOn') {
        useSocketStore().setLineState('通话保持中')
        callState.value = 2
    }
    if (type === 'HoldOff') {
        useSocketStore().setLineState('通话中')
        callState.value = 1
    }
    
  })
}


const callStateData = ref({
    0:['外呼'], 
    1:['转接','会议','挂断','保持'],
    2:['转接','会议','挂断','取消'],
    10:['挂断'],
})
const callActions = [
    { name: '外呼', status: [2], isShow: true, 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], isShow: true, icon: 'Switch', iconColor: '#a855f7', handler: () => toggleDialpad('transfer') }, 
    { name: '会议', status: [2, 3], isShow: true, icon: 'Connection', iconColor: '#6366f1', handler: () => toggleDialpad('conference') },
    // { name: '通讯录', status: [2, 3, 4, 5], isShow: true, icon: 'Notebook', iconColor: 'text-orange-500', handler: () => toggleContacts() },
    { name: '挂断', status: [3], isShow: true, icon: 'CircleClose', iconColor: '#ef4444', handler: () => holdEvent('DropCall') },
    { name: '保持', status: [3], isShow: true, icon: 'Mute', iconColor: '#ef4444', handler: () => holdEvent('HoldOn') }, 
    { name: '取消', status: [3], isShow: true, icon: 'Mute', iconColor: '#ef4444', handler: () => holdEvent('HoldOff') }, 
    // { name: '接听', status: [6], isShow: true, 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]
      console.log(newArray)
      currentCall.value = {
        name: newArray.name,
        phone: phoneNumber,
        avatar: newArray.avatar,
        location:  newArray.address
      }
    }
  )
}
const dialKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#'];


const toggleCallPanel = () => {
    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 = (contact: any) => {
    showContacts.value = false;
    showCallPanel.value = true;
    currentCall.value = {
        name: contact.name,
        phone: contact.phone,
        avatar: contact.avatar,
        location: '浙江省杭州市'
    };
};

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('挂断成功')
    })
};
</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>