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

 
$keys = $_GET['Keys'] ?? '';
$fliterRelationType = $_GET['FliterRelationType'] ?? '';
$fliterStatus = $_GET['FliterStatus'] ?? '';
$page = $_GET['Page'] ?? 1;
$urlStr = '';

if (!empty($fliterRelationType)) {
    $urlStr .= "&FliterRelationType=" . urlencode($fliterRelationType);
}

if (isset($fliterStatus) && $fliterStatus !== '') {
    $urlStr .= "&FliterStatus=" . urlencode($fliterStatus);
}
?>
<!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: 20%; }
        .col4 { width: 20%; }
        .col5 { width: 10%; }
        .col6 { width: 8%; text-align: center; }
        .col7 { width: 8%; }
        .col8 { width: 14%; }
        .col9 { width: 15%; text-align: center; }
        
        /* 表格布局修复 */
        .table2 .col2 { width: 5%; text-align: center; }
        .table2 .col3 { width: 20%; }
        .table2 .col4 { width: 20%; }
        .table2 .col5 { width: 10%; }
        .table2 .col6 { width: 8%; text-align: center; }
        .table2 .col7 { width: 8%; }
        .table2 .col8 { width: 14%; }
        .table2 .col9 { width: 15%; text-align: center; }
        
        .theader > div, .tline > div {
            padding: 0 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        /* 搜索栏样式 */
        .fastSelect {
            margin-bottom: 20px;
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 3px;
            border: 1px solid #eee;
        }
        
        .fastSelect H1 {
            font-size: 16px;
            margin-top: 0;
            margin-bottom: 10px;
            color: #333;
        }
        
        .selectItem {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .selectItem label {
            font-weight: bold;
            font-size: 13px;
            color: #555;
        }
        
        .inputSearch {
            display: flex;
            align-items: center;
            margin-top: 0px;
        }



        .inputSearch .inputTxt {
            padding:1px 5px;
            border: 1px solid #ccc;

            width: 300px;
            height: 30px;
        }
        
        .searchgo {
            margin-left: 5px;
            padding: 0 15px;
            background: #337ab7;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            height: 32px;
            line-height: 32px;
        }
        
        /* 按钮容器 */
        .search-button-container {
            display: flex;
            align-items: flex-end;
        }
        
        /* 状态颜色 */
        .status-active {
            color: green;
        }
        
        .status-inactive {
            color: red;
        }
        
        /* 按钮样式 */
        .ico {
            margin: 0 5px;
            text-decoration: none;
        }
        
        .ico_edit {
            color: #3498db;
        }
        
        .ico_del {
            color: #e74c3c;
        }
        
        .ico:hover {
            text-decoration: underline;
        }
        
        /* 详情样式 */
        .detail-row {
            display: none;
            background-color: #f8f8f8;
            border-bottom: 1px solid #ddd;
            padding: 15px;
        }
        
        .detail-container {
            display: flex;
            flex-wrap: wrap;
        }
        
        .detail-item {
            width: 33%;
            margin-bottom: 10px;
        }
        
        .detail-item label {
            font-weight: bold;
            display: block;
            margin-bottom: 3px;
            color: #555;
        }
        
        .detail-item-full {
            width: 100%;
            margin-bottom: 10px;
        }
        
        .detail-content {
            margin-top: 5px;
        }
        
        .clickable-row {
            cursor: pointer;
        }
    </style>
</head>
<body>
<div id="man_zone">
    <div class="fastSelect clear">
        <H1>筛选条件</H1>
        <div class="selectItem">
            <label>关系类型</label>
            <select name="FliterRelationType" class="filterSearch">
                <option value="">所有关系类型</option>
                <option value="1" <?= $fliterRelationType == '1' ? 'selected' : '' ?>>母公司-子公司</option>
                <option value="2" <?= $fliterRelationType == '2' ? 'selected' : '' ?>>供应商-客户</option>
                <option value="3" <?= $fliterRelationType == '3' ? 'selected' : '' ?>>合作伙伴</option>
                <option value="4" <?= $fliterRelationType == '4' ? 'selected' : '' ?>>竞争对手</option>
                <option value="5" <?= $fliterRelationType == '5' ? 'selected' : '' ?>>推荐人</option>
                <option value="6" <?= $fliterRelationType == '6' ? 'selected' : '' ?>>其他</option>
            </select>
        </div>
        <div class="selectItem">
            <label>状态</label>
            <select name="FliterStatus" class="filterSearch">
                <option value="">全部状态</option>
                <option value="1" <?= $fliterStatus == '1' ? 'selected' : '' ?>>启用</option>
                <option value="0" <?= $fliterStatus == '0' ? 'selected' : '' ?>>停用</option>
            </select>
        </div>
        <div class="inputSearch">
            <input type="text" id="keys" class="inputTxt" placeholder="请输入搜索关键词"
                value="<?= empty($keys) ? '' : htmlspecialchars($keys) ?>" />
            <input type="button" id="searchgo" class="searchgo" value="搜索"
                onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)" />
        </div>
    </div>

    <div align="right" style="margin-bottom: 10px;">
        <input type="button" value="新增客户关系" class="btn1" onClick="location.href='relationshipAdd.php'" />
    </div>

    <div class="table2">
        <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
        // 构建查询条件
        $whereClause = "WHERE 1=1";
        $params = [];
        
        // 检查是否为管理员,非管理员只能查看自己创建的关系
        $isAdmin = checkIfAdmin();
        if (!$isAdmin) {
            $whereClause .= " AND cr.employee_id = " . $_SESSION['employee_id'];
        }
        
        if (!empty($keys)) {
            $searchKeys = '%' . $conn->real_escape_string($keys) . '%';
            $whereClause .= " AND (c1.cs_code LIKE '$searchKeys' OR c1.cs_company LIKE '$searchKeys' OR c2.cs_code LIKE '$searchKeys' OR c2.cs_company LIKE '$searchKeys' OR cr.description LIKE '$searchKeys')";
        }
        
        if (!empty($fliterRelationType)) {
            $whereClause .= " AND cr.relationship_type = '" . $conn->real_escape_string($fliterRelationType) . "'";
        }
        
        if (isset($fliterStatus) && $fliterStatus !== '') {
            $whereClause .= " AND cr.relationship_status = '" . $conn->real_escape_string($fliterStatus) . "'";
        }
        
        // 分页设置
        $page = (int)$page;
        $perpage = 20; // 每页显示条数
        $start = ($page - 1) * $perpage;
        
        // 计算总记录数
        $countQuery = "SELECT COUNT(*) as total 
                       FROM customer_relationship cr
                       JOIN customer c1 ON cr.source_customer_id = c1.id
                       JOIN customer c2 ON cr.target_customer_id = c2.id
                       $whereClause";
        
        $result = $conn->query($countQuery);
        $row = $result->fetch_assoc();
        $totalRecords = $row['total'];
        $totalPages = ceil($totalRecords / $perpage);
        if ($totalPages < 1) $totalPages = 1;
        
        // 验证当前页码
        if ($page < 1) $page = 1;
        if ($page > $totalPages) $page = $totalPages;
        
        // 获取关系列表
        $query = "SELECT cr.*, 
                  c1.cs_code as source_code,
                  c1.cs_company as source_company, 
                  c2.cs_code as target_code,
                  c2.cs_company as target_company,
                  e.em_user as creator
                  FROM customer_relationship cr
                  JOIN customer c1 ON cr.source_customer_id = c1.id
                  JOIN customer c2 ON cr.target_customer_id = c2.id
                  LEFT JOIN employee e ON cr.employee_id = e.id
                  $whereClause
                  ORDER BY cr.updated_at DESC
                  LIMIT $start, $perpage";
        
        $result = $conn->query($query);
        
        if ($result->num_rows > 0) {
            $tempNum = ($page - 1) * $perpage;
            while ($row = $result->fetch_assoc()) {
                $tempNum++;
                // 获取关系类型描述
                $relationType = '';
                switch ($row['relationship_type']) {
                    case 1: $relationType = '母公司-子公司'; break;
                    case 2: $relationType = '供应商-客户'; break;
                    case 3: $relationType = '合作伙伴'; break;
                    case 4: $relationType = '竞争对手'; break;
                    case 5: $relationType = '推荐人'; break;
                    case 6: $relationType = '其他'; break;
                }
                
                $status = $row['relationship_status'] == 1 ? 
                    '<span class="status-active">启用</span>' : 
                    '<span class="status-inactive">停用</span>';
                
                ?>
                <div class="tline clickable-row" data-id="<?= $row['id'] ?>">
                    <div class="col2"><?= $tempNum ?></div>
                    <div class="col3"><?= htmlspecialcharsFix($row['source_code'].' - '.$row['source_company']) ?></div>
                    <div class="col4"><?= htmlspecialcharsFix($row['target_code'].' - '.$row['target_company']) ?></div>
                    <div class="col5"><?= $relationType ?></div>
                    <div class="col6"><?= $status ?></div>
                    <div class="col7"><?= htmlspecialcharsFix($row['creator']) ?></div>
                    <div class="col8"><?= $row['updated_at'] ?></div>
                    <div class="col9">
                        <a href="relationshipAdd.php?id=<?= $row['id'] ?>" class="ico_edit ico">编辑</a>
                        <a href="javascript:void(0)" onclick="confirmDelete(<?= $row['id'] ?>); event.stopPropagation();" class="ico_del ico">删除</a>
                    </div>
                </div>
                <div id="detail-<?= $row['id'] ?>" class="detail-row">
                    <div class="detail-container">
                        <div class="detail-item">
                            <label>源客户</label>
                            <div><?= htmlspecialcharsFix($row['source_code'].' - '.$row['source_company']) ?></div>
                        </div>
                        <div class="detail-item">
                            <label>目标客户</label>
                            <div><?= htmlspecialcharsFix($row['target_code'].' - '.$row['target_company']) ?></div>
                        </div>
                        <div class="detail-item">
                            <label>关系类型</label>
                            <div><?= $relationType ?></div>
                        </div>
                        <div class="detail-item">
                            <label>状态</label>
                            <div><?= $row['relationship_status'] == 1 ? '启用' : '停用' ?></div>
                        </div>
                        <div class="detail-item">
                            <label>创建人</label>
                            <div><?= htmlspecialcharsFix($row['creator']) ?></div>
                        </div>
                        <div class="detail-item">
                            <label>创建时间</label>
                            <div><?= $row['created_at'] ?></div>
                        </div>
                        <div class="detail-item">
                            <label>更新时间</label>
                            <div><?= $row['updated_at'] ?></div>
                        </div>
                        <div class="detail-item-full">
                            <label>关系描述</label>
                            <div><?= nl2br(htmlspecialcharsFix($row['description'] ?? '无')) ?></div>
                        </div>
                    </div>
                </div>
                <?php
            }
        } else {
            if (empty($keys) && empty($fliterRelationType) && $fliterStatus === '') {
                echo '<div class="tline"><div style="text-align:center; width:100%;">当前暂无客户关系记录</div></div>';
            } else {
                echo '<div class="tline"><div style="text-align:center; width:100%;"><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() {
        // 处理筛选条件改变
        $('.filterSearch').change(function() {
            var url = '?';
            var keys = $('#keys').val();
            if (keys && keys != '请输入搜索关键词') {
                url += 'Keys=' + encodeURIComponent(keys) + '&';
            }

            // 获取所有筛选条件
            $('select.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;
        });
        
        // 点击行显示详情
        $('.clickable-row').click(function() {
            var id = $(this).data('id');
            $('#detail-' + id).slideToggle();
        });
    });
    
    function confirmDelete(id) {
        if (confirm("确定要删除此关系记录吗?此操作不可恢复!")) {
            window.location.href = "relationshipSave.php?act=delete&id=" + id + "&keys=<?= urlencode($keys) ?>&page=<?= $page ?>";
        }
    }
    </script>
</div>
</body>
</html>