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

// 检查是否为编辑模式
$isEdit = false;
$relationshipData = null;

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $id = intval($_GET['id']);
    $query = "SELECT * FROM customer_relationship WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $relationshipData = $result->fetch_assoc();
        $isEdit = true;
        
        // 检查权限:如果不是管理员,只能编辑自己创建的关系
        $isAdmin = checkIfAdmin();
        if (!$isAdmin && $relationshipData['employee_id'] != $_SESSION['employee_id']) {
            echo "<script>alert('您没有权限编辑此客户关系记录!'); window.location.href='relationships.php';</script>";
            exit;
        }
    } else {
        echo "<script>alert('未找到指定的客户关系记录!'); window.location.href='relationships.php';</script>";
        exit;
    }
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><?= $isEdit ? '编辑' : '新增' ?>客户关系</title>
    <link rel="stylesheet" href="css/common.css" type="text/css" />
    <script src="js/jquery-1.7.2.min.js"></script>
    <script src="js/js.js"></script>
    <script src="js/ySearchSelect.js"></script>
    <style>
        body {
            margin: a;
            padding: 20px;
            background: #fff;
        }
        #man_zone {
            margin-left: 0;
        }
        .relationship-form-container {
            margin-bottom: 20px;
        }
        .customer-search-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            position: relative;
            width: 60%;
        }
        .customer-info {
            margin-top: 5px;
            padding: 5px;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 3px;
            display: none;
        }
        .customer-dropdown {
            display: none;
            position: absolute;
            background: white;
            border: 1px solid #ccc;
            max-height: 200px;
            overflow-y: auto;
            width: 100%;
            z-index: 1000;
            box-shadow: 0 3px 8px rgba(0,0,0,0.25);
            border-radius: 0 0 4px 4px;
            top: 100%;
            left: 0;
        }
        .customer-item {
            padding: 10px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .customer-item:hover {
            background-color: #f0f0f0;
        }
        .customer-item:last-child {
            border-bottom: none;
        }
        .selected-customer-info {
            font-weight: bold;
            padding: 8px 10px;
            border: 1px solid #ddd;
            background-color: #f9f9f9;
            display: none;
            width: 100%;
            box-sizing: border-box;
            word-break: break-all;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: normal;
            min-height: 38px;
            cursor: pointer;
        }
        .selected-customer-info:hover {
            background-color: #f0f0f0;
        }
        .customer-clear-btn {
            margin-left: 5px;
            color: #e74c3c;
            font-weight: bold;
            cursor: pointer;
            float: right;
        }
        .customer-clear-btn:hover {
            color: #c0392b;
        }
    </style>
    <script>
        $(document).ready(function() {
            // 处理表单提交前的验证
            $('#save').click(function() {
                if (validateForm()) {
                    $('#form1').submit();
                }
            });
            
            // 客户搜索功能
            var customerSearchTimeouts = {
                source: null,
                target: null
            };
            var customerIsComposing = false;
            
            // 监听输入法组合事件
            $(document).on('compositionstart', '.customer-search', function() {
                customerIsComposing = true;
            });

            $(document).on('compositionend', '.customer-search', function() {
                customerIsComposing = false;
                $(this).trigger('input'); // 手动触发一次input事件
            });
            
            // 客户搜索输入
            $(document).on('input', '.customer-search', function() {
                // 如果是输入法正在组合中文,不处理
                if (customerIsComposing) return;
                
                var $this = $(this);
                var searchType = $this.data('type'); // source 或 target
                var searchTerm = $this.val().trim();
                var customerDropdown = $('#' + searchType + '_customer_dropdown');
                
                // 清除之前的超时
                clearTimeout(customerSearchTimeouts[searchType]);
                
                // 隐藏之前的结果
                customerDropdown.hide();
                
                // 清除之前的选择
                $('#' + searchType + '_customer_id').val('');
                $('#' + searchType + '_customer_selected').hide();
                
                // 如果搜索词少于1个字符,不执行搜索
                if (searchTerm.length < 1) {
                    return;
                }
                
                // 设置一个300毫秒的超时,以减少请求数量
                customerSearchTimeouts[searchType] = setTimeout(function() {
                    $.ajax({
                        url: 'get_customer_search.php',
                        type: 'GET',
                        data: {search: searchTerm},
                        dataType: 'json',
                        success: function(data) {
                            customerDropdown.empty();
                            
                            if (data && data.customers && data.customers.length > 0) {
                                $.each(data.customers, function(i, customer) {
                                    var displayText = customer.cs_company;
                                    if (customer.cs_code) {
                                        displayText = customer.cs_code + ' - ' + displayText;
                                    }
                                    
                                    var item = $('<div class="customer-item"></div>')
                                        .attr('data-id', customer.id)
                                        .attr('data-company', customer.cs_company)
                                        .attr('data-display', displayText)
                                        .text(displayText);
                                    
                                    customerDropdown.append(item);
                                });
                                customerDropdown.show();
                            }
                        },
                        error: function() {
                            console.log('搜索客户失败,请重试');
                        }
                    });
                }, 300);
            });
            
            // 点击选择客户
            $(document).on('click', '.customer-item', function() {
                var $this = $(this);
                var customerId = $this.data('id');
                var customerName = $this.data('company');
                var displayText = $this.data('display');
                var parentContainer = $this.parent();
                var searchType = parentContainer.attr('id').replace('_customer_dropdown', '');
                
                // 设置选中的客户ID和名称
                $('#' + searchType + '_customer_id').val(customerId);
                $('#' + searchType + '_customer_search').hide();
                $('#' + searchType + '_customer_selected').text(displayText).append('<span class="customer-clear-btn" data-type="' + searchType + '">X</span>').show();
                $('#' + searchType + '_customer_company').val(customerName);
                
                // 添加标题属性,便于查看完整信息
                $('#' + searchType + '_customer_selected').attr('title', displayText);
                
                // 隐藏下拉菜单
                parentContainer.hide();
            });
            
            // 点击已选客户可以重新选择
            $(document).on('click', '.selected-customer-info', function() {
                // 点击整个已选区域不再执行任何操作
            });
            
            // 点击X按钮清除选择的客户
            $(document).on('click', '.customer-clear-btn', function(e) {
                e.stopPropagation();
                var searchType = $(this).data('type');
                
                // 显示搜索框,隐藏已选信息
                $('#' + searchType + '_customer_search').val('').show();
                $('#' + searchType + '_customer_selected').hide();
                
                // 清空客户ID
                $('#' + searchType + '_customer_id').val('');
            });
            
            // 点击其他地方隐藏下拉列表
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.customer-search-container').length) {
                    $('.customer-dropdown').hide();
                }
            });
            
            // 如果编辑模式下已有选中客户,显示客户信息
            <?php if ($isEdit): ?>
            $('#source_customer_selected').show();
            $('#target_customer_selected').show();
            $('#source_customer_search').hide();
            $('#target_customer_search').hide();
            <?php endif; ?>
        });
        
        // 表单验证函数
        function validateForm() {
            // 验证源客户和目标客户
            var sourceCustomerId = $('#source_customer_id').val();
            var targetCustomerId = $('#target_customer_id').val();
            var relationshipType = $('#relationship_type').val();
            
            if (!sourceCustomerId) {
                alert('请选择源客户');
                $('#source_customer_search').show().focus();
                $('#source_customer_selected').hide();
                return false;
            }
            
            if (!targetCustomerId) {
                alert('请选择目标客户');
                $('#target_customer_search').show().focus();
                $('#target_customer_selected').hide();
                return false;
            }
            
            if (sourceCustomerId === targetCustomerId) {
                alert('源客户和目标客户不能是同一个客户');
                return false;
            }
            
            if (!relationshipType) {
                alert('请选择关系类型');
                $('#relationship_type').focus();
                return false;
            }
            
            return true;
        }
    </script>
</head>
<body class="clear">
<?php // require_once 'panel.php'; ?>
<div id="man_zone">
    <form name="form1" id="form1" method="post" action="relationshipSave.php">
        <?php if ($isEdit): ?>
        <input type="hidden" name="id" value="<?= $relationshipData['id'] ?>">
        <?php endif; ?>
        
        <table width="100%" border="0" cellpadding="3" cellspacing="1" class="table1">
            <tbody>
                <tr>
                    <th width="15%">源客户</th>
                    <td>
                        <div class="customer-search-container">
                            <input type="text" id="source_customer_search" class="customer-search txt1" data-type="source" placeholder="输入客户编码或名称搜索..." value="" />
                            <div id="source_customer_selected" class="selected-customer-info" title="<?php 
                            if ($isEdit) {
                                $sourceCustQuery = "SELECT cs_company, cs_code FROM customer WHERE id = ?";
                                $stmt = $conn->prepare($sourceCustQuery);
                                $stmt->bind_param('i', $relationshipData['source_customer_id']);
                                $stmt->execute();
                                $result = $stmt->get_result();
                                if ($row = $result->fetch_assoc()) {
                                    $displayText = $row['cs_company'];
                                    if ($row['cs_code']) {
                                        $displayText = $row['cs_code'] . ' - ' . $displayText;
                                    }
                                    echo textDecode($displayText);
                                }
                            }
                            ?>"><?php 
                            if ($isEdit) {
                                $sourceCustQuery = "SELECT cs_company, cs_code FROM customer WHERE id = ?";
                                $stmt = $conn->prepare($sourceCustQuery);
                                $stmt->bind_param('i', $relationshipData['source_customer_id']);
                                $stmt->execute();
                                $result = $stmt->get_result();
                                if ($row = $result->fetch_assoc()) {
                                    $displayText = $row['cs_company'];
                                    if ($row['cs_code']) {
                                        $displayText = $row['cs_code'] . ' - ' . $displayText;
                                    }
                                    echo textDecode($displayText);
                                }
                            }
                            ?><span class="customer-clear-btn" data-type="source">X</span></div>
                            <div id="source_customer_dropdown" class="customer-dropdown"></div>
                        </div>
                        <input type="hidden" id="source_customer_id" name="source_customer_id" value="<?= $isEdit ? $relationshipData['source_customer_id'] : '' ?>" />
                        <input type="hidden" id="source_customer_company" name="source_customer_company" value="" />
                    </td>
                </tr>
                <tr>
                    <th>目标客户</th>
                    <td>
                        <div class="customer-search-container">
                            <input type="text" id="target_customer_search" class="customer-search txt1" data-type="target" placeholder="输入客户编码或名称搜索..." value="" />
                            <div id="target_customer_selected" class="selected-customer-info" title="<?php 
                            if ($isEdit) {
                                $targetCustQuery = "SELECT cs_company, cs_code FROM customer WHERE id = ?";
                                $stmt = $conn->prepare($targetCustQuery);
                                $stmt->bind_param('i', $relationshipData['target_customer_id']);
                                $stmt->execute();
                                $result = $stmt->get_result();
                                if ($row = $result->fetch_assoc()) {
                                    $displayText = $row['cs_company'];
                                    if ($row['cs_code']) {
                                        $displayText = $row['cs_code'] . ' - ' . $displayText;
                                    }
                                    echo textDecode($displayText);
                                }
                            }
                            ?>"><?php 
                            if ($isEdit) {
                                $targetCustQuery = "SELECT cs_company, cs_code FROM customer WHERE id = ?";
                                $stmt = $conn->prepare($targetCustQuery);
                                $stmt->bind_param('i', $relationshipData['target_customer_id']);
                                $stmt->execute();
                                $result = $stmt->get_result();
                                if ($row = $result->fetch_assoc()) {
                                    $displayText = $row['cs_company'];
                                    if ($row['cs_code']) {
                                        $displayText = $row['cs_code'] . ' - ' . $displayText;
                                    }
                                    echo textDecode($displayText);
                                }
                            }
                            ?><span class="customer-clear-btn" data-type="target">X</span></div>
                            <div id="target_customer_dropdown" class="customer-dropdown"></div>
                        </div>
                        <input type="hidden" id="target_customer_id" name="target_customer_id" value="<?= $isEdit ? $relationshipData['target_customer_id'] : '' ?>" />
                        <input type="hidden" id="target_customer_company" name="target_customer_company" value="" />
                    </td>
                </tr>
                <tr>
                    <th>关系类型</th>
                    <td>
                        <select id="relationship_type" name="relationship_type" class="txt1">
                            <option value="">请选择关系类型</option>
                            <option value="1" <?= $isEdit && $relationshipData['relationship_type'] == 1 ? 'selected' : '' ?>>母公司-子公司</option>
                            <option value="2" <?= $isEdit && $relationshipData['relationship_type'] == 2 ? 'selected' : '' ?>>供应商-客户</option>
                            <option value="3" <?= $isEdit && $relationshipData['relationship_type'] == 3 ? 'selected' : '' ?>>合作伙伴</option>
                            <option value="4" <?= $isEdit && $relationshipData['relationship_type'] == 4 ? 'selected' : '' ?>>竞争对手</option>
                            <option value="5" <?= $isEdit && $relationshipData['relationship_type'] == 5 ? 'selected' : '' ?>>推荐人</option>
                            <option value="6" <?= $isEdit && $relationshipData['relationship_type'] == 6 ? 'selected' : '' ?>>其他</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th>关系状态</th>
                    <td>
                        <label>
                            <input type="radio" name="relationship_status" value="1" <?= (!$isEdit || ($isEdit && $relationshipData['relationship_status'] == 1)) ? 'checked' : '' ?>>
                            启用
                        </label>
                        <label>
                            <input type="radio" name="relationship_status" value="0" <?= ($isEdit && $relationshipData['relationship_status'] == 0) ? 'checked' : '' ?>>
                            停用
                        </label>
                    </td>
                </tr>
                <tr>
                    <th>关系描述</th>
                    <td>
                        <textarea name="description" class="txt1" style="width:80%; height:100px;"><?= $isEdit ? htmlspecialchars(textDecode($relationshipData['description'])) : '' ?></textarea>
                    </td>
                </tr>
                <tr>
                    <th></th>
                    <td>
                        <input type="button" name="save" id="save" value="保存" class="btn1" />
                        <input type="button" value="返回" class="btn1" onClick="location.href='relationships.php'" />
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</div>
</body>
</html>