<?php 

include './head.php';

?>

    
    <div class="rx mdui-card mdui-table-fluid rk-j-ro">
  <table class="rx mdui-card mdui-table rk-j-ro">
    <thead>
      <tr>
        <th>工单标题</th>
        <th>关联项目</th>
        <th>紧急程度</th>
        <th>工单状态</th>
        <th>最近回复</th>
      </tr>
    </thead>    
    <tbody class="mdui-typo">          
     
    
    <tr>
    <td id="title">无数据</td>
    <td id="related_product">无数据</td>
    <td id="priority">无数据</td>
    <td><code id="status">无数据</code></td>
    <td id="last_reply_time">无数据</td>
    </tr>
    
            </tbody>
  </table>
</div>
   
          
            <br>
            <div id="chat">
            
            
            </div>

<br>





<br><br><br><br><br>

<script>
let cache = null;
let lastAudioPlayTime = 0; // 记录上一次播放音频的时间
const audioInterval = 5000; // 设置音频播放的间隔，单位为毫秒

function fetchTicket() {
    fetch('./get_end_ticket.php?name=<?php echo $_GET['name']?>')
        .then(response => response.text())
        .then(data => {
            if (data === '无') return; // 如果返回无，则不进行任何操作

            const ticketData = JSON.parse(data);
            const { ticket } = ticketData;

            // 缓存第一次请求的数据
            if (!cache) {
                cache = ticket;
                updatePage(ticket);

                // 在第一次加载时，如果最后一条记录是客服回复，则进行提示
                const lastConversation = ticket.conversation[ticket.conversation.length - 1];
                if (lastConversation.role === 'admin') {
                    handleCustomerServiceReply();
                }
            } else {
                // 对比缓存和新数据
                if (JSON.stringify(cache) !== JSON.stringify(ticket)) {
                    handleUpdates(ticket);
                }
            }
        })
        .catch(err => console.error('Error fetching ticket:', err));
}

function updatePage(ticket) {
    rk.tip('Loading...', '<div class="mdui-progress"><div class="mdui-progress-indeterminate"></div></div>', 6000);
    
    document.getElementById('title').innerText = ticket.title;
    document.getElementById('last_reply_time').innerText = ticket.last_reply_time;
    document.getElementById('status').innerText = ticket.status;
    document.getElementById('priority').innerText = ticket.priority;
    document.getElementById('related_product').innerText = ticket.related_product;

    const chatElement = document.getElementById('chat');
    chatElement.innerHTML = ''; // 清空之前的聊天记录

    ticket.conversation.forEach(item => {
        const isAdmin = item.role === 'admin';
        const html = `
        
        
        <br>
        <div class="mdui-card">

  <div style="padding:0px" class="mdui-card-header">
  
  
  <li class="mdui-list-item"> <i class="mdui-list-item-avatar mdui-icon material-icons ${isAdmin ? 'mdui-color-blue' : 'mdui-color-indigo'} mdui-text-color-white">${isAdmin ? 'donut_large' : 'face'}</i> <div class="mdui-list-item-content"> <div class="mdui-list-item-title">${item.responder}</div> <div class="mdui-list-item-text">${item.reply_time}</div> </div> </li>
  
  
  </div>

  <div class="mdui-card-content">${item.reply_content}</div>


</div>`;
        chatElement.insertAdjacentHTML('beforeend', html);
    });
}

function handleUpdates(ticket) {
    // 检查是否有新的对话记录且为客服回复
    const lastConversation = ticket.conversation[ticket.conversation.length - 1];
    const isNewCustomerReply = lastConversation.role === 'main' && ticket.conversation.length > cache.conversation.length;

    if (isNewCustomerReply) {
        handleCustomerServiceReply();
    }

    // 更新页面
    updatePage(ticket);
    cache = ticket; // 更新缓存
        rk.tip('Loading...', '<div class="mdui-progress"><div class="mdui-progress-indeterminate"></div></div>', 6000);
    
}

function handleCustomerServiceReply() {
    rk.tip('叮叮叮~~', '工单已载入~~', 5);

    // 检查时间间隔，避免频繁播放音频
    const currentTime = Date.now();
    if (currentTime - lastAudioPlayTime >= audioInterval) {
        const audio = new Audio('./tip.mp3');
        audio.play().catch(error => console.error('Audio play error:', error)); // 捕获播放失败的错误
        lastAudioPlayTime = currentTime; // 更新播放时间
    }
}

// 启动定时器，每秒钟调用一次 fetchTicket
setInterval(fetchTicket, 1000);

// 页面加载完成后启动 Ticket 查询
document.addEventListener('DOMContentLoaded', (event) => {
    fetchTicket(); // 初次获取工单信息
});

</script>