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

// 辅助函数
$act = $_GET['act'] ?? '';
$urlStr = '';

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

$fliterStr = "";

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

if (!empty($fliterToDate)) {
    $fliterStr .= " AND o.order_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 = $_GET['Page'] ?? 1;

// 构建基本条件SQL - 这部分是两个查询共用的
$employee_id = $_SESSION['employee_id'];
$isAdmin = checkIfAdmin();

// 步骤1:查询符合条件的客户ID列表
$customerListSql = "SELECT DISTINCT o.customer_id
FROM orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN customer c ON o.customer_id = c.id
JOIN products p ON oi.product_id = p.id
WHERE 
    o.order_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
    AND o.order_type = 1
    AND p.rebate = 1
    AND NOT EXISTS (
        SELECT 1
        FROM rebate_redemption_items rri
        WHERE rri.order_item_id = oi.id
    )
    AND EXISTS (
        SELECT 1
        FROM rebate_rules rr
        WHERE rr.product_id = oi.product_id
    )
    AND (
        SELECT SUM(oi2.quantity)
        FROM order_items oi2
        JOIN orders o2 ON oi2.order_id = o2.id
        WHERE o2.customer_id = o.customer_id
        AND o2.order_type = 1
        AND oi2.product_id = oi.product_id
        AND o2.order_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
        AND NOT EXISTS (
            SELECT 1
            FROM rebate_redemption_items rri
            WHERE rri.order_item_id = oi2.id
        )
    ) >= (
        SELECT MIN(rr.min_quantity)
        FROM rebate_rules rr
        WHERE rr.product_id = oi.product_id
    )";

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

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

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

// 执行查询获取客户ID列表
$customerResult = mysqli_query($conn, $customerListSql);
if (!$customerResult) {
    die("查询客户列表错误: " . mysqli_error($conn));
}

// 获取客户ID并创建IN子句
$customerIds = [];
while ($row = mysqli_fetch_assoc($customerResult)) {
    $customerIds[] = $row['customer_id'];
}

// 如果没有找到客户,设置一个不可能的ID以确保查询不返回任何结果
if (empty($customerIds)) {
    $customerIds = [-1]; // 不可能的ID
}

$customerIdsStr = implode(',', $customerIds);

// 设置每页显示记录数和分页
$pageSize = 20;
$totalRecords = count($customerIds);

// 计算总页数
$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;

// 步骤2:获取分页后的客户详细信息
// 为防止表结构问题,使用更简单的SQL格式并明确使用id字段

// 先获取客户基本信息
$paginatedCustomerIds = array_slice($customerIds, $offset, $pageSize);
if (empty($paginatedCustomerIds)) {
    $paginatedCustomerIds = [-1]; // 确保不会有结果
}
$paginatedIdsStr = implode(',', $paginatedCustomerIds);

$customerDetailSql = "
SELECT 
    c.id AS customer_id,
    c.cs_company AS customer_name,
    c.cs_code
FROM 
    customer c
WHERE 
    c.id IN ($paginatedIdsStr)";

$result = mysqli_query($conn, $customerDetailSql);
if (!$result) {
    die("查询客户基本信息错误: " . mysqli_error($conn));
}

$customers = [];
while ($row = mysqli_fetch_assoc($result)) {
    $customers[$row['customer_id']] = $row;
    $customers[$row['customer_id']]['total_rebate_amount'] = 0;
    $customers[$row['customer_id']]['qualifying_products'] = 0;
    $customers[$row['customer_id']]['rebate_details'] = '';
}

// 如果找到客户,获取每个客户的返点详情
if (!empty($customers)) {
    $customerIdsForDetails = array_keys($customers);
    $customerIdsForDetailsStr = implode(',', $customerIdsForDetails);
    
    // 获取客户返点总金额和产品数量
    $rebateDetailsSql = "
    SELECT 
        o.customer_id,
        SUM(
            oi.quantity * (
                SELECT rr.rebate_amount
                FROM rebate_rules rr
                WHERE rr.product_id = oi.product_id
                AND rr.min_quantity <= (
                    SELECT SUM(oi2.quantity)
                    FROM order_items oi2
                    JOIN orders o2 ON oi2.order_id = o2.id
                    WHERE o2.customer_id = o.customer_id
                    AND o2.order_type = 1
                    AND oi2.product_id = oi.product_id
                    AND o2.order_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
                    AND NOT EXISTS (
                        SELECT 1
                        FROM rebate_redemption_items rri
                        WHERE rri.order_item_id = oi2.id
                    )
                )
                ORDER BY rr.min_quantity DESC
                LIMIT 1
            )
        ) AS total_rebate_amount,
        COUNT(DISTINCT oi.product_id) AS qualifying_products
    FROM 
        orders o
    JOIN 
        order_items oi ON o.id = oi.order_id
    JOIN
        products p ON oi.product_id = p.id
    WHERE 
        o.customer_id IN ($customerIdsForDetailsStr)
        AND o.order_type = 1
        AND o.order_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
        AND p.rebate = 1
        AND NOT EXISTS (
            SELECT 1
            FROM rebate_redemption_items rri
            WHERE rri.order_item_id = oi.id
        )
    GROUP BY 
        o.customer_id";
    
    $detailsResult = mysqli_query($conn, $rebateDetailsSql);
    if (!$detailsResult) {
        die("查询返点详情错误: " . mysqli_error($conn));
    }
    
    // 填充总金额和产品数量
    while ($detailRow = mysqli_fetch_assoc($detailsResult)) {
        if (isset($customers[$detailRow['customer_id']])) {
            $customers[$detailRow['customer_id']]['total_rebate_amount'] = $detailRow['total_rebate_amount'];
            $customers[$detailRow['customer_id']]['qualifying_products'] = $detailRow['qualifying_products'];
        }
    }
    
    // 获取每个客户的产品返点详情
    foreach ($customerIdsForDetails as $customerId) {
        $productDetailsSql = "
        SELECT 
            p.ProductName,
            SUM(oi.quantity) AS quantity,
            (
                SELECT rr.rebate_amount
                FROM rebate_rules rr
                WHERE rr.product_id = oi.product_id
                AND rr.min_quantity <= SUM(oi.quantity)
                ORDER BY rr.min_quantity DESC
                LIMIT 1
            ) AS rebate_amount
        FROM 
            order_items oi
        JOIN 
            orders o ON oi.order_id = o.id
        JOIN 
            products p ON oi.product_id = p.id
        WHERE 
            o.customer_id = $customerId
            AND o.order_type = 1
            AND o.order_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
            AND p.rebate = 1
            AND NOT EXISTS (
                SELECT 1
                FROM rebate_redemption_items rri
                WHERE rri.order_item_id = oi.id
            )
        GROUP BY 
            oi.product_id, p.ProductName";
        
        $productResult = mysqli_query($conn, $productDetailsSql);
        if (!$productResult) {
            die("查询产品详情错误: " . mysqli_error($conn));
        }
        
        // 构建返点详情文本
        $details = [];
        while ($productRow = mysqli_fetch_assoc($productResult)) {
            $details[] = $productRow['ProductName'] . ': ' . 
                         $productRow['quantity'] . ' 件 x ' . 
                         $productRow['rebate_amount'] . ' 元/件';
        }
        
        $customers[$customerId]['rebate_details'] = implode('; ', $details);
    }
    
    // 按照返点金额排序
    usort($customers, function($a, $b) {
        return $b['total_rebate_amount'] <=> $a['total_rebate_amount'];
    });
}
?>
<!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: 25%; }
        .col5 { width: 10%; text-align: center; }
        .col6 { width: 15%; text-align: right; }
        .col7 { width: 10%; text-align: center; }
        .col8 { width: 20%; text-align: center; }

        /* 表格布局修复,因为 "css/common.css 覆盖了 */
        .table2 .col2 { width: 5%; text-align: center; }
        .table2 .col3 { width: 15%; }
        .table2 .col4 { width: 25%; }
        .table2 .col5 { width: 10%; text-align: center; }
        .table2 .col6 { width: 15%; text-align: right; }
        .table2 .col7 { width: 10%; text-align: center; }
        .table2 .col8 { width: 20%; 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;
        }
        
        .col6 {
            justify-content: flex-end !important;
        }
        
        /* 日期选择器样式 */
        .date-input {
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        
        /* 滑动面板样式 */
        .slidepanel {
            cursor: pointer;
        }
        
        .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;
        }
    </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_history.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>

        <?php
        if (!empty($customers)) {
            $tempNum = ($page - 1) * $pageSize;
            foreach ($customers as $customer) {
                $tempNum++;
                ?>
                <div class="tline">
                    <div class="col2"><?= $tempNum ?></div>
                    <div class="col3 slidepanel "><?= htmlspecialcharsFix($customer['cs_code']) ?></div>
                    <div class="col4 slidepanel " data-id="<?= $customer['customer_id'] ?>"><?= htmlspecialcharsFix($customer['customer_name']) ?></div>
                    <div class="col5"><?= $customer['qualifying_products'] ?></div>
                    <div class="col6"><?= number_format($customer['total_rebate_amount'], 2) ?> 元</div>
                    <div class="col7">
                        <a href="javascript:void(0)" class="toggleDetail" data-id="<?= $customer['customer_id'] ?>">展开详情</a>
                    </div>
                    <div class="col8">
                        <a href="rebate_redeem.php?customer_id=<?= $customer['customer_id'] ?>" class="ico_edit ico">处理兑换</a>
                    </div>
                </div>
                <div class="notepanel clear" id="detail-<?= $customer['customer_id'] ?>">
                    <div class="noteItem">返点详情</div>
                    <div class="rebate-details">
                        <?= htmlspecialcharsFix($customer['rebate_details']) ?>
                    </div>
                </div>
                <?php
            }
        } else {
            if (empty($keys) && empty($fliterStr)) {
                echo '<div class="tline"><div align="center" colspan="7">当前没有客户有可用返点</div></div>';
            } else {
                echo '<div class="tline"><div align="center" colspan="7"><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;
        });
        
        // 添加展开详情的点击事件处理
        $('.toggleDetail').click(function() {
            var customerId = $(this).data('id');
            var detailPanel = $('#detail-' + customerId);
            
            if (detailPanel.is(':visible')) {
                detailPanel.slideUp();
                $(this).text('展开详情');
            } else {
                detailPanel.slideDown();
                $(this).text('收起详情');
            }
        });
  
    });
    </script>
</div>
</body>
</html>