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

// 辅助函数
$urlStr = '';

// 处理筛选条件
$fliterFromDate = $_GET['fliterFromDate'] ?? '';
$fliterToDate = $_GET['fliterToDate'] ?? '';

$fliterStr = "";

if (!empty($fliterFromDate)) {
    $fliterStr .= " AND rr.redemption_date >= '" . mysqli_real_escape_string($conn, $fliterFromDate) . "'";
    $urlStr .= "&fliterFromDate=" . urlencode($fliterFromDate);
}

if (!empty($fliterToDate)) {
    $fliterStr .= " AND rr.redemption_date <= '" . mysqli_real_escape_string($conn, $fliterToDate) . " 23:59:59'";
    $urlStr .= "&fliterToDate=" . urlencode($fliterToDate);
}

// 搜索参数
$keys = $_GET['Keys'] ?? '';
$keyscode = mysqli_real_escape_string($conn, $keys);
$page = isset($_GET['Page']) ? intval($_GET['Page']) : 1;

// 构建基本条件SQL
$employee_id = $_SESSION['employee_id'];
$isAdmin = checkIfAdmin();

// 基础查询,计算总记录数
$countSql = "SELECT COUNT(*) AS total 
             FROM rebate_redemptions rr
             JOIN customer c ON rr.customer_id = c.id
             WHERE 1=1";

// 非管理员只能查看自己客户的返点历史
if (!$isAdmin) {
    $countSql .= " AND c.cs_belong = $employee_id";
}

// 添加搜索条件
if (!empty($keyscode)) {
    $countSql .= " AND (c.cs_company LIKE '%$keyscode%' OR c.cs_code LIKE '%$keyscode%')";
}

// 添加日期筛选
$countSql .= $fliterStr;

// 执行查询获取总记录数
$countResult = mysqli_query($conn, $countSql);
if (!$countResult) {
    die("查询记录数量错误: " . mysqli_error($conn));
}
$countRow = mysqli_fetch_assoc($countResult);
$totalRecords = $countRow['total'];

// 设置每页显示记录数和分页
$pageSize = 20;

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

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

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

// 查询返点兑换历史记录
$sql = "SELECT 
            rr.id AS redemption_id,
            rr.customer_id,
            c.cs_code,
            c.cs_company AS customer_name,
            rr.redemption_date,
            rr.total_rebate_amount,
            rr.notes,
            rr.status,
            e.em_user AS employee_name,
            (SELECT COUNT(DISTINCT product_id) FROM rebate_redemption_items WHERE redemption_id = rr.id) AS product_count
        FROM 
            rebate_redemptions rr
        JOIN 
            customer c ON rr.customer_id = c.id
        LEFT JOIN
            employee e ON rr.created_by = e.id
        WHERE 
            1=1";

// 非管理员只能查看自己客户的返点历史
if (!$isAdmin) {
    $sql .= " AND c.cs_belong = $employee_id";
}

// 添加搜索条件
if (!empty($keyscode)) {
    $sql .= " AND (c.cs_company LIKE '%$keyscode%' OR c.cs_code LIKE '%$keyscode%')";
}

// 添加日期筛选
$sql .= $fliterStr;

// 添加排序和分页
$sql .= " ORDER BY rr.redemption_date DESC, rr.id DESC LIMIT $offset, $pageSize";

$result = mysqli_query($conn, $sql);
if (!$result) {
    die("查询返点历史错误: " . mysqli_error($conn));
}

// 获取返点历史记录
$redemptions = [];
while ($row = mysqli_fetch_assoc($result)) {
    $redemptions[] = $row;
}
?>
<!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: 15%; }
        .col4 { width: 20%; }
        .col5 { width: 12%; text-align: center; }
        .col6 { width: 10%; text-align: center; }
        .col7 { width: 15%; text-align: right; }
        .col8 { width: 10%; text-align: center; }
        .col9 { width: 13%; text-align: center; }

        /* 表格布局修复 */
        .table2 .col2 { width: 5%; text-align: center; }
        .table2 .col3 { width: 15%; }
        .table2 .col4 { width: 20%; }
        .table2 .col5 { width: 12%; text-align: center; }
        .table2 .col6 { width: 10%; text-align: center; }
        .table2 .col7 { width: 15%; text-align: right; }
        .table2 .col8 { width: 10%; text-align: center; }
        .table2 .col9 { width: 13%; text-align: center; }

        .theader > div, .tline > div {
            padding: 0 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .col3, .col4 {
            justify-content: flex-start !important;
        }
        
        .col7 {
            justify-content: flex-end !important;
        }
        
        /* 日期选择器样式 */
        .date-input {
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        
        /* 滑动面板样式 */
        .rb-slidepanel {
            cursor: pointer;
        }
        
        .rb-slidepanel.open {
            font-weight: bold;
            color: #3366cc;
        }
        
        .notepanel {
            display: none;
            background: #f9f9f9;
            padding: 10px;
            border: 1px solid #eee;
            margin-bottom: 10px;
        }
        
        .notepanel .noteItem {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .rebate-details {
            margin-top: 10px;
            border-top: 1px dashed #ddd;
            padding-top: 10px;
        }
        
        /* 状态样式 */
        .status-active {
            color: #27ae60;
            font-weight: bold;
        }
        
        .status-cancelled {
            color: #e74c3c;
            text-decoration: line-through;
        }
        
        /* 备注文本溢出控制 */
        .notes-text {
            max-width: 200px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            display: inline-block;
        }
    </style>
</head>
<body>
<div id="man_zone">
    <div class="fastSelect clear">
        <H1>客户返点历史查询</H1>
        <div class="selectItem">
            <label>兑换日期</label>
            <input type="date" name="fliterFromDate" class="date-input filterSearch" value="<?= $fliterFromDate ?>">
            <label>到</label>
            <input type="date" name="fliterToDate" class="date-input filterSearch" value="<?= $fliterToDate ?>">
        </div>
        <div class="inputSearch">
            <input type="text" id="keys" class="inputTxt" placeholder="请输入客户名称或编码"
                value="<?= empty($keyscode) ? '' : $keyscode ?>" />
            <input type="button" id="searchgo" class="searchgo" value="搜索"
                onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)" />
        </div>
        <div style="text-align: right; margin-top: 10px; clear: both;">
            <a href="rebate_expiring.php" class="btn1" style="display: inline-flex; align-items: center; justify-content: center; padding: 5px 15px; margin-top: 0; height: 22px; background-color: #e74c3c; margin-right: 5px;">查看过期预警</a>
            <a href="rebate_summary.php" class="btn1" style="display: inline-flex; align-items: center; justify-content: center; padding: 5px 15px; margin-top: 0; height: 22px;">返回返点统计</a>
        </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 class="col8">处理人</div>
            <div class="col9">操作</div>
        </div>

        <?php
        if (!empty($redemptions)) {
            $tempNum = ($page - 1) * $pageSize;
            foreach ($redemptions as $redemption) {
                $tempNum++;
                $statusClass = $redemption['status'] == 1 ? 'status-active' : 'status-cancelled';
                ?>
                <div class="tline">
                    <div class="col2"><?= $tempNum ?></div>
                    <div class="col3"><?= htmlspecialcharsFix($redemption['cs_code']) ?></div>
                    <div class="col4 rb-slidepanel" data-id="<?= $redemption['redemption_id'] ?>"><?= htmlspecialcharsFix($redemption['customer_name']) ?></div>
                    <div class="col5"><?= date('Y-m-d', strtotime($redemption['redemption_date'])) ?></div>
                    <div class="col6"><?= $redemption['product_count'] ?></div>
                    <div class="col7 <?= $statusClass ?>"><?= number_format($redemption['total_rebate_amount'], 2) ?> 元</div>
                    <div class="col8"><?= htmlspecialcharsFix($redemption['employee_name']) ?></div>
                    <div class="col9">
                        <a href="javascript:void(0)" class="rb-toggleDetail" data-id="<?= $redemption['redemption_id'] ?>">查看详情</a>
                    </div>
                </div>
                <div class="notepanel clear" id="detail-<?= $redemption['redemption_id'] ?>">
                    <div class="noteItem">返点详情</div>
                    <?php if (!empty($redemption['notes'])): ?>
                    <div style="margin-bottom: 10px; color: #666;">
                        <strong>备注:</strong> <?= htmlspecialcharsFix($redemption['notes']) ?>
                    </div>
                    <?php endif; ?>
                    <div class="rebate-details" id="rebate-details-<?= $redemption['redemption_id'] ?>">
                        <div style="text-align: center; padding: 10px;">
                            <img src="images/loading.gif" alt="加载中" style="width: 20px; height: 20px;">
                            加载返点详情...
                        </div>
                    </div>
                </div>
                <?php
            }
        } else {
            if (empty($keys) && empty($fliterStr)) {
                echo '<div class="tline"><div style="width: 100%; text-align: center;">当前没有返点历史记录</div></div>';
            } else {
                echo '<div class="tline"><div style="width: 100%; text-align: center;"><a href="?">没有找到匹配的返点历史记录,点击返回</a></div></div>';
            }
        }
        ?>

        <div class="showpagebox">
            <?php
            if ($totalPages > 1) {
                $pageName = "?Keys=$keys$urlStr&";
                $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() {
        // 添加日期验证逻辑
        $('input[name="fliterToDate"]').on('change', function() {
            var fromDate = $('input[name="fliterFromDate"]').val();
            var toDate = $(this).val();
            
            if (fromDate && toDate && new Date(toDate) < new Date(fromDate)) {
                alert('结束日期不能早于开始日期');
                $(this).val(''); // 清空结束日期
                return false;
            }
        });
        
        // 开始日期变更时也进行验证
        $('input[name="fliterFromDate"]').on('change', function() {
            var fromDate = $(this).val();
            var toDate = $('input[name="fliterToDate"]').val();
            
            if (fromDate && toDate && new Date(toDate) < new Date(fromDate)) {
                alert('开始日期不能晚于结束日期');
                $('input[name="fliterToDate"]').val(''); // 清空结束日期
                return false;
            }
        });

        // 处理筛选条件改变
        $('.filterSearch').change(function() {
            var url = '?';
            var keys = $('#keys').val();
            if (keys && keys != '请输入客户名称或编码') {
                url += 'Keys=' + encodeURIComponent(keys) + '&';
            }

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

            // 移除末尾的&
            if (url.endsWith('&')) {
                url = url.substring(0, url.length - 1);
            }

            location.href = url;
        });
        
        // 切换显示返点详情
        $('.rb-toggleDetail').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation(); // 阻止事件冒泡
            var redemptionId = $(this).data('id');
            var $detailPanel = $('#detail-' + redemptionId);
            var $panel = $(this);
            
            if ($detailPanel.is(':visible')) {
                $detailPanel.slideUp();
                $panel.text('查看详情');
                // 移除打开状态
                $panel.closest('.tline').find('.rb-slidepanel').removeClass('open');
            } else {
                $detailPanel.slideDown();
                $panel.text('收起详情');
                // 添加打开状态
                $panel.closest('.tline').find('.rb-slidepanel').addClass('open');
                
                // 加载详情数据
                loadRedemptionDetails(redemptionId);
            }
        });
        
        // 客户名称点击也可以切换显示
        $('.rb-slidepanel').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation(); // 阻止事件冒泡
            var redemptionId = $(this).data('id');
            var $detailPanel = $('#detail-' + redemptionId);
            var $toggleButton = $('.rb-toggleDetail[data-id="' + redemptionId + '"]');
            
            if ($detailPanel.is(':visible')) {
                $detailPanel.slideUp();
                $toggleButton.text('查看详情');
                $(this).removeClass('open');
            } else {
                $detailPanel.slideDown();
                $toggleButton.text('收起详情');
                $(this).addClass('open');
                
                // 加载详情数据
                loadRedemptionDetails(redemptionId);
            }
        });
        
        // 加载返点详情
        function loadRedemptionDetails(redemptionId) {
            var $detailsContainer = $('#rebate-details-' + redemptionId);
            
            // 检查是否已经加载过
            if ($detailsContainer.data('loaded')) {
                return;
            }
            
            // 异步加载详情
            $.ajax({
                url: 'get_rebate_details.php',
                type: 'GET',
                data: { redemption_id: redemptionId },
                dataType: 'json',
                success: function(data) {
                    if (data && data.success) {
                        var html = '<table class="detail-table" style="width:100%; border-collapse: collapse;">';
                        html += '<tr style="background-color: #eee; font-weight: bold;">' +
                                '<th style="padding: 8px; text-align: left; border: 1px solid #ddd;">订单编号</th>' +
                                '<th style="padding: 8px; text-align: left; border: 1px solid #ddd;">产品名称</th>' +
                                '<th style="padding: 8px; text-align: center; border: 1px solid #ddd;">数量</th>' +
                                '<th style="padding: 8px; text-align: right; border: 1px solid #ddd;">返点单价</th>' +
                                '<th style="padding: 8px; text-align: right; border: 1px solid #ddd;">返点金额</th>' +
                                '</tr>';
                                
                        $.each(data.items, function(i, item) {
                            html += '<tr style="border-bottom: 1px solid #ddd;">' +
                                   '<td style="padding: 8px; border: 1px solid #ddd;">' + item.order_code + '</td>' +
                                   '<td style="padding: 8px; border: 1px solid #ddd;">' + item.product_name + '</td>' +
                                   '<td style="padding: 8px; text-align: center; border: 1px solid #ddd;">' + item.quantity + ' ' + item.unit + '</td>' +
                                   '<td style="padding: 8px; text-align: right; border: 1px solid #ddd;">' + item.rebate_amount + ' 元/件</td>' +
                                   '<td style="padding: 8px; text-align: right; border: 1px solid #ddd;">' + item.total_rebate + ' 元</td>' +
                                   '</tr>';
                        });
                        
                        html += '</table>';
                        $detailsContainer.html(html);
                        $detailsContainer.data('loaded', true);
                    } else {
                        $detailsContainer.html('<div style="padding: 10px; color: #e74c3c;">加载详情失败: ' + (data.message || '未知错误') + '</div>');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $detailsContainer.html('<div style="padding: 10px; color: #e74c3c;">加载详情失败: ' + textStatus + '</div>');
                }
            });
        }
    });
    </script>
</div>
</body>
</html>