<?php
require_once 'conn.php';
checkLogin();

// 获取当前登录员工ID
$employee_id = $_SESSION['employee_id'];

// 筛选参数
$message_type = isset($_GET['message_type']) ? intval($_GET['message_type']) : 0;
$is_read = isset($_GET['is_read']) ? intval($_GET['is_read']) : -1;
$priority = isset($_GET['priority']) ? intval($_GET['priority']) : -1;
$urlStr = '';

// 搜索参数
$keys = $_GET['Keys'] ?? '';
$keyscode = mysqli_real_escape_string($conn, $keys);

// 页码参数
$page = $_GET['Page'] ?? 1;
$ord = $_GET['Ord'] ?? '';

$ordStr = !empty($ord) ? "$ord," : "";

// 构建SQL查询
$sql = "SELECT m.*, mr.is_read, mr.read_time 
        FROM messages m 
        LEFT JOIN message_recipients mr ON m.id = mr.message_id AND mr.employee_id = $employee_id
        WHERE (m.target_type = 2 OR (mr.employee_id = $employee_id)) AND (mr.is_deleted = 0 OR mr.is_deleted IS NULL)";

// 添加筛选条件
if ($message_type > 0) {
    $sql .= " AND m.message_type = $message_type";
    $urlStr .= "&message_type=" . urlencode($message_type);
}

if ($is_read >= 0) {
    $sql .= " AND mr.is_read = $is_read";
    $urlStr .= "&is_read=" . urlencode($is_read);
}

if ($priority >= 0) {
    $sql .= " AND m.priority = $priority";
    $urlStr .= "&priority=" . urlencode($priority);
}

// 关键词搜索
if (!empty($keyscode)) {
    $sql .= " AND (m.title LIKE '%$keyscode%' OR m.content LIKE '%$keyscode%')";
    $urlStr .= "&Keys=" . urlencode($keys);
}

// 排序 - 未读优先,然后按时间倒序
$sql .= " ORDER BY CASE WHEN mr.is_read = 0 OR mr.is_read IS NULL THEN 0 ELSE 1 END, m.created_at DESC";

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>消息列表</title>
    <link rel="stylesheet" href="css/common.css" type="text/css" />
    <link rel="stylesheet" href="css/alert.css" type="text/css" />
    <script src="js/jquery-1.7.2.min.js"></script>
    <script src="js/js.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background: #fff;
        }
        #man_zone {
            margin-left: 0;
        }
        
        /* 表格布局修复 */
        .table2 {
            width: 100%;
        }
        
        .theader, .tline {
            display: flex;
            flex-direction: row;
            align-items: center;
            width: 100%;
            border-bottom: 1px solid #ddd;
        }
        
        .theader {
            background-color: #f2f2f2;
            font-weight: bold;
            height: 40px;
        }
        
        .tline {
            height: 45px;
        }
        
        .tline:hover {
            background-color: #f5f5f5;
        }
        
        .col2 { width: 5%; text-align: center; }
        .col3 { width: 40%; }
        .col4 { width: 10%; }
        .col5 { width: 10%; }
        .col6 { width: 15%; }
        .col7 { width: 20%; }
        
        .theader > div, .tline > div {
            padding: 0 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        /* 消息状态标签 */
        .badge {
            display: inline-block;
            padding: 3px 6px;
            border-radius: 3px;
            font-size: 12px;
            color: white;
            box-sizing: border-box;
            height: 22px;
            line-height: 16px;
            vertical-align: middle;
        }
        
        .badge-primary {
            background-color: #4285f4;
        }
        
        .badge-secondary {
            background-color: #888;
        }
        
        .badge-warning {
            background-color: #f4b400;
            color: #333;
        }
        
        .badge-danger {
            background-color: #db4437;
        }
        
        /* 按钮样式 */
        .btn {
            display: inline-block;
            padding: 3px 8px;
            margin: 0 2px;
            border-radius: 3px;
            cursor: pointer;
            text-decoration: none;
            font-size: 12px;
            box-sizing: border-box;
            height: 32px;
            line-height: 26px;
            vertical-align: middle;
        }
        
        .btn-info {
            background-color: #4285f4;
            color: white;
        }
        
        .btn-success {
            background-color: #0f9d58;
            color: white;
        }
        
        .btn-danger {
            background-color: #db4437;
            color: white;
        }
        
        .btn:hover {
            /* opacity: 0.8; */
            color: #fff;
            /* background-color: #999; */
        }
        
        /* 未读消息样式 */
        .unread {
            font-weight: bold;
        }
        
        /* 优先级颜色 */
        .priority-1 {
            color: #f4b400;
        }
        
        .priority-2 {
            color: #db4437;
            font-weight: bold;
        }
        
        /* 筛选控件样式 */
        .filter-select {
            padding: 3px;
            border: 1px solid #ccc;
            border-radius: 3px;
            margin: 3px 5px 3px 0;
            width: 100px;
            height: 32px;
            box-sizing: border-box;
            vertical-align: middle;
        }
        
        /* 筛选条件区域样式 */
        .filter-row {
            display: flex;
            flex-wrap: nowrap;
            align-items: center;
            margin-bottom: 8px;
            overflow-x: auto;
            padding-bottom: 5px;
        }
        
        .filter-item {
            display: flex;
            align-items: center;
            margin-right: 10px;
            white-space: nowrap;
        }
        
        .filter-item label {
            margin-right: 5px;
            white-space: nowrap;
        }
        
        /* 搜索框样式 */
        .search-input {
            padding: 3px 8px;
            border: 1px solid #ccc;
            border-radius: 3px;
            width: 120px;
            margin-right: 5px;
            height: 32px;
            box-sizing: border-box;
            vertical-align: middle;
            font-size: 12px;
        }
        
        .search-btn {
            padding: 3px 10px;
            background-color: #4285f4;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            height: 32px;
            box-sizing: border-box;
            vertical-align: middle;
            font-size: 12px;
            line-height: 1;
        }
        
        .search-btn:hover {
            background-color: #999;
        }
        
        /* 使按钮容器垂直居中 */
        .col7 {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            width: 20%; 
            text-align: left;
        }
        
        /* 状态标签容器垂直居中 */
        .col2 {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 5%;
            text-align: center;
        }
        
        /* 滑动面板样式 */
        .msg-slidepanel {
            cursor: pointer;
        }
        
        .msg-slidepanel.open {
            font-weight: bold;
            color: #3366cc;
        }
        
        .notepanel {
            display: none;
            background: #f9f9f9;
            padding: 10px;
            border: 1px solid #eee;
            margin-bottom: 10px;
            text-align: left;
        }
        
        .notepanel .noteItem {
            font-weight: bold;
            margin-bottom: 5px;
            text-align: left;
            padding-top:0px;
        }
        
        .notepanel .noteContent {
            margin: 10px 0;
            line-height: 1.5;
            white-space: pre-line;
            text-align: left;
            padding-top:0px;
        }
        
        .notepanel .noteInfo {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 10px;
            text-align: left;
        }
        
        .notepanel .message-header-row {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .notepanel .message-header-row .noteItem {
            margin-right: 15px;
            margin-bottom: 0;
            min-width: 80px;
        }
    </style>
</head>
<body>
<div id="man_zone">
    <div class="fastSelect clear">
        <H1>筛选条件</H1>
        <div class="filter-row">
            <div class="filter-item">
                <label>消息类型:</label>
                <select name="message_type" class="filter-select filterSearch">
                    <option value="0" <?= $message_type == 0 ? 'selected' : '' ?>>所有类型</option>
                    <option value="1" <?= $message_type == 1 ? 'selected' : '' ?>>系统消息</option>
                    <option value="2" <?= $message_type == 2 ? 'selected' : '' ?>>客户相关</option>
                    <option value="3" <?= $message_type == 3 ? 'selected' : '' ?>>订单相关</option>
                    <option value="4" <?= $message_type == 4 ? 'selected' : '' ?>>任务提醒</option>
                    <option value="5" <?= $message_type == 5 ? 'selected' : '' ?>>其他</option>
                </select>
            </div>
            
            <div class="filter-item">
                <label>状态:</label>
                <select name="is_read" class="filter-select filterSearch">
                    <option value="-1" <?= $is_read == -1 ? 'selected' : '' ?>>全部状态</option>
                    <option value="0" <?= $is_read == 0 ? 'selected' : '' ?>>未读</option>
                    <option value="1" <?= $is_read == 1 ? 'selected' : '' ?>>已读</option>
                </select>
            </div>
            
            <div class="filter-item">
                <label>优先级:</label>
                <select name="priority" class="filter-select filterSearch">
                    <option value="-1" <?= $priority == -1 ? 'selected' : '' ?>>所有优先级</option>
                    <option value="0" <?= $priority == 0 ? 'selected' : '' ?>>普通</option>
                    <option value="1" <?= $priority == 1 ? 'selected' : '' ?>>重要</option>
                    <option value="2" <?= $priority == 2 ? 'selected' : '' ?>>紧急</option>
                </select>
            </div>
            
            <div class="filter-item">
                <label>搜索:</label>
                <input type="text" id="keys" class="search-input" placeholder="标题或内容" value="<?= htmlspecialcharsFix($keys) ?>" />
                <input type="button" class="search-btn" value="搜索" onClick="doSearch()" />
            </div>
        </div>
    </div>

    <div class="table2 em<?= $_SESSION['employee_id'] ?>">
        <div class="theader">
            <div class="col2">状态</div>
            <div class="col3">标题</div>
            <div class="col4">类型</div>
            <div class="col5">优先级</div>
            <div class="col6">时间</div>
            <div class="col7">操作</div>
        </div>

        <?php
        // 设置每页显示记录数
        $pageSize = 20;

        // 获取总记录数
        $countSql = "SELECT COUNT(*) AS total 
                     FROM messages m 
                     LEFT JOIN message_recipients mr ON m.id = mr.message_id AND mr.employee_id = $employee_id
                     WHERE (m.target_type = 2 OR (mr.employee_id = $employee_id)) AND (mr.is_deleted = 0 OR mr.is_deleted IS NULL)";
                     
        // 添加筛选条件
        if ($message_type > 0) {
            $countSql .= " AND m.message_type = $message_type";
        }

        if ($is_read >= 0) {
            $countSql .= " AND mr.is_read = $is_read";
        }

        if ($priority >= 0) {
            $countSql .= " AND m.priority = $priority";
        }
        
        // 添加关键词搜索条件
        if (!empty($keyscode)) {
            $countSql .= " AND (m.title LIKE '%$keyscode%' OR m.content LIKE '%$keyscode%')";
        }

        $countResult = mysqli_query($conn, $countSql);
        $countRow = mysqli_fetch_assoc($countResult);
        $totalRecords = $countRow['total'];

        // 计算总页数
        $totalPages = ceil($totalRecords / $pageSize);
        if ($totalPages < 1) $totalPages = 1;

        // 验证当前页码
        $page = (int)$page;
        if ($page < 1) $page = 1;
        if ($page > $totalPages) $page = $totalPages;

        // 计算起始记录
        $offset = ($page - 1) * $pageSize;

        // 添加分页条件
        $sql .= " LIMIT $offset, $pageSize";

        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            $tempNum = ($page - 1) * $pageSize;
            while ($row = mysqli_fetch_assoc($result)) {
                $tempNum++;
                
                // 确定消息状态
                $is_read_status = $row['is_read'] ?? 0;
                
                // 确定消息类型
                $message_type_text = [
                    1 => '系统消息',
                    2 => '客户相关',
                    3 => '订单相关',
                    4 => '任务提醒',
                    5 => '其他'
                ][$row['message_type']] ?? '未知';
                
                // 确定优先级
                $priority_class = [
                    0 => '',
                    1 => 'priority-1',
                    2 => 'priority-2'
                ][$row['priority']] ?? '';
                
                $priority_text = [
                    0 => '普通',
                    1 => '重要',
                    2 => '紧急'
                ][$row['priority']] ?? '未知';
                
                // 行样式类,未读消息加粗显示
                $row_class = $is_read_status ? '' : 'unread';
                ?>
                <div class="tline <?= $row_class ?>">
                    <div class="col2">
                        <?php if ($is_read_status): ?>
                            <span class="badge badge-secondary">已读</span>
                        <?php else: ?>
                            <span class="badge badge-primary">未读</span>
                        <?php endif; ?>
                    </div>
                    <div class="col3 msg-slidepanel"><?= htmlspecialcharsFix($row['title']) ?></div>
                    <div class="col4"><?= $message_type_text ?></div>
                    <div class="col5 <?= $priority_class ?>"><?= $priority_text ?></div>
                    <div class="col6"><?= date('Y-m-d H:i', strtotime($row['created_at'])) ?></div>
                    <div class="col7">
                        <a href="message_detail.php?id=<?= $row['id'] ?>" class="btn btn-info">查看</a>
                        <?php if (!$is_read_status): ?>
                            <a href="javascript:void(0)" class="btn btn-success mark-read" data-id="<?= $row['id'] ?>">标记已读</a>
                        <?php endif; ?>
                        <a href="javascript:void(0)" class="btn btn-danger delete-message" data-id="<?= $row['id'] ?>">删除</a>
                    </div>
                </div>
                <div class="notepanel clear">
                   
                        <div class="noteItem" style="padding-top:0px;">详情</div>
                        <div class="noteInfo">
                            <div><strong>类型:</strong> <?= $message_type_text ?></div>
                            <div><strong>优先级:</strong> <span class="<?= $priority_class ?>"><?= $priority_text ?></span></div>
                            <div><strong>时间:</strong> <?= date('Y-m-d H:i:s', strtotime($row['created_at'])) ?></div>
                            <?php if ($row['read_time']): ?>
                            <div><strong>阅读时间:</strong> <?= date('Y-m-d H:i:s', strtotime($row['read_time'])) ?></div>
                            <?php endif; ?>
                        </div>
                   
                    <div class="noteItem" style="padding-top:0px;">内容</div>
                    <div class="noteContent"><?= nl2br(htmlspecialcharsFix($row['content'])) ?></div>
                </div>
                <?php
            }
        } else {
            if (empty($keys) && $message_type == 0 && $is_read == -1 && $priority == -1) {
                echo '<div class="tline"><div align="center" colspan="6">当前暂无消息记录</div></div>';
            } else {
                echo '<div class="tline"><div align="center" colspan="6"><a href="?">没有找到匹配的消息记录,点击返回</a></div></div>';
            }
        }
        ?>

        <div class="showpagebox">
            <?php
            if ($totalPages > 1) {
                $pageName = "?$urlStr&";
                if ($pageName == "?&") {
                    $pageName = "?";
                }
                $pageLen = 3;

                if ($page > 1) {
                    echo "<a href=\"{$pageName}Page=1\">首页</a>";
                    echo "<a href=\"{$pageName}Page=" . ($page - 1) . "\">上一页</a>";
                }

                if ($pageLen * 2 + 1 >= $totalPages) {
                    $startPage = 1;
                    $endPage = $totalPages;
                } else {
                    if ($page <= $pageLen + 1) {
                        $startPage = 1;
                        $endPage = $pageLen * 2 + 1;
                    } else {
                        $startPage = $page - $pageLen;
                        $endPage = $page + $pageLen;
                    }
                    if ($page + $pageLen > $totalPages) {
                        $startPage = $totalPages - $pageLen * 2;
                        $endPage = $totalPages;
                    }
                }

                for ($i = $startPage; $i <= $endPage; $i++) {
                    if ($i == $page) {
                        echo "<a class=\"current\">$i</a>";
                    } else {
                        echo "<a href=\"{$pageName}Page=$i\">$i</a>";
                    }
                }

                if ($page < $totalPages) {
                    if ($totalPages - $page > $pageLen) {
                        echo "<a href=\"{$pageName}Page=$totalPages\">...$totalPages</a>";
                    }
                    echo "<a href=\"{$pageName}Page=" . ($page + 1) . "\">下一页</a>";
                    echo "<a href=\"{$pageName}Page=$totalPages\">尾页</a>";
                }
            }
            ?>
        </div>
    </div>

    <script>
    $(document).ready(function() {
        // 处理筛选条件改变
        $('.filterSearch').change(function() {
            var url = buildSearchUrl();
            location.href = url;
        });
        
        // 标记为已读
        $('.mark-read').click(function() {
            var messageId = $(this).data('id');
            $.post('message_action.php', {
                action: 'mark_read',
                message_id: messageId
            }, function(response) {
                try {
                    var data = typeof response === 'string' ? JSON.parse(response) : response;
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('操作失败:' + data.message);
                    }
                } catch (e) {
                    alert('操作失败:服务器返回未知错误');
                }
            });
        });

        // 删除消息
        $('.delete-message').click(function() {
            if (confirm('确定要删除这条消息吗?')) {
                var messageId = $(this).data('id');
                $.post('message_action.php', {
                    action: 'delete',
                    message_id: messageId
                }, function(response) {
                    try {
                        var data = typeof response === 'string' ? JSON.parse(response) : response;
                        if (data.success) {
                            location.reload();
                        } else {
                            alert('操作失败:' + data.message);
                        }
                    } catch (e) {
                        alert('操作失败:服务器返回未知错误');
                    }
                });
            }
        });
        
        // 点击标题展开消息内容
        $('.msg-slidepanel').click(function() {
            var $this = $(this);
            var $panel = $this.closest('.tline').next('.notepanel');
            
            // 判断是否已经打开
            if ($panel.is(':visible')) {
                $panel.slideUp('fast');
                $this.removeClass('open');
            } else {
                // 先关闭其他已打开的面板
                $('.notepanel').slideUp('fast');
                $('.msg-slidepanel').removeClass('open');
                
                // 打开当前点击的面板
                $panel.slideDown('fast');
                $this.addClass('open');
                
                // 如果消息未读,自动标记为已读
                var $row = $this.closest('.tline');
                if ($row.hasClass('unread')) {
                    var messageId = $row.find('.mark-read').data('id');
                    if (messageId) {
                        $.post('message_action.php', {
                            action: 'mark_read',
                            message_id: messageId
                        }, function(response) {
                            try {
                                var data = typeof response === 'string' ? JSON.parse(response) : response;
                                if (data.success) {
                                    // 只更新样式,不刷新页面
                                    $row.removeClass('unread');
                                    $row.find('.badge-primary').removeClass('badge-primary').addClass('badge-secondary').text('已读');
                                    $row.find('.mark-read').remove();
                                }
                            } catch (e) {
                                // 忽略错误,不影响用户体验
                            }
                        });
                    }
                }
            }
        });
        
        // 回车键触发搜索
        $('#keys').keypress(function(e) {
            if (e.which == 13) {
                doSearch();
                return false;
            }
        });
    });
    
    // 执行搜索
    function doSearch() {
        var url = buildSearchUrl();
        location.href = url;
    }
    
    // 构建搜索URL
    function buildSearchUrl() {
        var url = '?';
        var keys = $.trim($('#keys').val());
        if (keys) {
            url += 'Keys=' + encodeURIComponent(keys) + '&';
        }

        $('.filterSearch').each(function() {
            var name = $(this).attr('name');
            var value = $(this).val();
            if (value && value != -1) {
                url += name + '=' + encodeURIComponent(value) + '&';
            }
        });

        // 移除末尾的&
        if (url.endsWith('&')) {
            url = url.substring(0, url.length - 1);
        }
        
        return url;
    }
    </script>
</div>
</body>
</html>