<?php 

include './head.php';

?>

<main class="h-full overflow-y-auto">
<div class="container px-6 mx-auto grid">
          
         <?php 

if ($active_ticket == "无") {



$out = <<<EOD


  <br><br><br>
    <form action="./new_ticket.php" method="POST">

    
    
    <div class="mdui-card">
  <div class="mdui-card-media">
    <img src="https://api.fuxsto.cn/img.php"/>
    <div class="mdui-card-media-covered mdui-card-media-covered-gradient">
      <div class="mdui-card-primary">
        <div class="mdui-card-primary-title">提交工单</div>
        <div class="mdui-card-primary-subtitle">请输入完整信息</div>
      </div>
    </div>
  </div>
  <div class="mdui-card-content">
  <div class="rk-in-gray-bg mdui-textfield mdui-textfield-floating-label">
  <div class="rk-in-la">
  <label style="" class="mdui-textfield-label">工单标题</label>
  </div>
  <input class="rk-in-la mdui-textfield-input" name="title" type="txt" />
</div>
<br>
<div class="rk-in-gray-bg mdui-textfield mdui-textfield-floating-label">
  <div class="rk-in-la">
  <label style="" class="mdui-textfield-label">问题描述</label>
  </div>
  <textarea class="rk-in-la mdui-textfield-input" name="msg" type="txt" ></textarea>
</div>
<p>紧急程度</p>
  <label class="mdui-radio">
    <input type="radio" name="priority" value="高"/>
    <i class="mdui-radio-icon"></i>
    高
  </label>
  <br>
  <label class="mdui-radio">
    <input type="radio" name="priority" value="中"/>
    <i class="mdui-radio-icon"></i>
    中
  </label>
<br>
  <label class="mdui-radio">
    <input type="radio" name="priority" checked  value="低"/>
    <i class="mdui-radio-icon"></i>
    低
  </label>

<br>

<select name="related_product" class="mdui-select" mdui-select="{position: 'top'}">
                  <option>虚拟主机</option>
                  <option>账号相关</option>
                  <option>前台咨询</option>
                  <option>售后相关</option>
                  <option>捐赠相关</option>
         
</select>
<br><br>


<button type="submit" style="margin-bottom: 15px;" class="mdui-float-right mdui-hoverable mdui-text-color-blue-a200 mdui-btn mdui-color-theme-accent mdui-ripple">
    <i class="mdui-icon mdui-icon-left material-icons">assistant_photo</i> 提交工单
    </button>
    </div>
  </div>
</div>
    
    
    
   </form>
  




EOD;




echo $out;


exit;

}








?>

    
    <div class="mdui-table-fluid rk-j-ro">
  <table class="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>








  <form action="./reply_ticket.php" method="POST">
            <div class="mdui-card mdui-card-content">

<div class="rk-in-gray-bg mdui-textfield mdui-textfield-floating-label">
  <div class="rk-in-la">
  <label style="" class="mdui-textfield-label">回复内容</label>
  </div>
  <textarea class="rk-in-la mdui-textfield-input" name="msg" type="txt"></textarea>
</div>
  <br>              
                
<button class="mdui-float-right mdui-hoverable mdui-text-color-blue-a200 mdui-btn mdui-color-theme-accent mdui-ripple" type="submit">
    <i class="mdui-icon mdui-icon-left material-icons">assistant_photo</i> 回复
    </button>

            </div>

                </form>





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

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

function fetchTicket() {
    fetch('./get_ticket.php')
        .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) {
    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 === 'admin' && ticket.conversation.length > cache.conversation.length;

    if (isNewCustomerReply) {
        handleCustomerServiceReply();
    }

    // 更新页面
    updatePage(ticket);
    cache = ticket; // 更新缓存
}

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>