<?php
$title='支付接口配置';
include __DIR__ . '/head.php';
?>

<div class="p-6 space-y-6">
    <!-- 支付接口列表 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-6 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                <div>
                    <h2 class="text-lg font-semibold text-gray-800">支付接口列表</h2>
                    <p class="text-sm text-gray-500 mt-1">管理所有支付接口，支持多接口配置</p>
                </div>
                <div class="flex md:w-auto">
                    <button onclick="openAddModal()" class="md:flex-none px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition flex items-center whitespace-nowrap">
                        <i class="fas fa-plus mr-2"></i>添加接口
                    </button>
                </div>
            </div>
        </div>
        <div class="p-6">
            <div class="overflow-x-auto">
                <table class="w-full min-w-[700px] text-sm whitespace-nowrap">
                    <thead>
                        <tr class="bg-gray-50">
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">支付方式</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">接口类型</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">接口名称</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">状态</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">排序</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">操作</th>
                        </tr>
                    </thead>
                    <tbody id="payInterfaceList">
                        <?php
                        $payInterfaces = $DB->getAll("SELECT * FROM pre_pay_interface ORDER BY sort ASC");
                        foreach($payInterfaces as $item){
                            $typeName = '';
                            $typeClass = '';
                            switch($item['pay_type']){
                                case 'alipay':
                                    $typeName = '支付宝';
                                    $typeClass = 'bg-blue-100 text-blue-700';
                                    break;
                                case 'qqpay':
                                    $typeName = 'QQ钱包';
                                    $typeClass = 'bg-blue-100 text-blue-700';
                                    break;
                                case 'wxpay':
                                    $typeName = '微信支付';
                                    $typeClass = 'bg-green-100 text-green-700';
                                    break;
                            }
                            $interfaceName = '';
                            switch($item['interface_type']){
                                case 'alipay_official':
                                    $interfaceName = '支付宝官方';
                                    break;
                                case 'alipay_face':
                                    $interfaceName = '支付宝当面付';
                                    break;
                                case 'qqpay_official':
                                    $interfaceName = 'QQ钱包官方';
                                    break;
                                case 'wxpay_official':
                                    $interfaceName = '微信官方';
                                    break;
                                case 'epay':
                                    $interfaceName = '彩虹易支付';
                                    break;
                                default:
                                    $interfaceName = $item['interface_type'];
                            }
                        ?>
                        <tr class="border-b border-gray-100 hover:bg-gray-50">
                            <td class="px-4 py-3 whitespace-nowrap">
                                <span class="px-2 py-1 rounded text-xs font-medium <?php echo $typeClass;?>"><?php echo $typeName;?></span>
                            </td>
                            <td class="px-4 py-3 text-gray-600 whitespace-nowrap"><?php echo $interfaceName;?></td>
                            <td class="px-4 py-3 text-gray-800 font-medium whitespace-nowrap"><?php echo htmlspecialchars($item['name']);?></td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <?php if($item['status'] == 1){?>
                                <span class="px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-700">启用</span>
                                <?php }else{?>
                                <span class="px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-700">禁用</span>
                                <?php }?>
                            </td>
                            <td class="px-4 py-3 text-gray-600 whitespace-nowrap"><?php echo $item['sort'];?></td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <button onclick="copyInterface(<?php echo $item['id'];?>)" class="text-green-600 hover:text-green-800 mr-3 whitespace-nowrap" title="复制">
                                    <i class="fas fa-copy"></i>
                                </button>
                                <button onclick="editInterface(<?php echo $item['id'];?>)" class="text-indigo-600 hover:text-indigo-800 mr-3 whitespace-nowrap" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="deleteInterface(<?php echo $item['id'];?>)" class="text-red-600 hover:text-red-800 whitespace-nowrap" title="删除">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php }?>
                        <?php if(empty($payInterfaces)){?>
                        <tr>
                            <td colspan="6" class="px-4 py-8 text-center text-gray-500">
                                <i class="fas fa-inbox text-4xl mb-3 block text-gray-300"></i>
                                <p>暂无支付接口，点击上方按钮添加</p>
                            </td>
                        </tr>
                        <?php }?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑接口模态框 -->
<div id="interfaceModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 transition-opacity" onclick="closeInterfaceModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] flex flex-col relative transform transition-all">
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800">添加支付接口</h3>
                <button onclick="closeInterfaceModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="px-6 py-4 overflow-y-auto">
                <form id="interfaceForm" onsubmit="saveInterface(event)" class="space-y-4">
                    <input type="hidden" id="interfaceId" name="id">
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">支付方式</label>
                            <select id="payType" name="pay_type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" onchange="changePayType()">
                                <option value="">请选择</option>
                                <option value="alipay">支付宝</option>
                                <option value="qqpay">QQ钱包</option>
                                <option value="wxpay">微信支付</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">接口类型</label>
                            <select id="interfaceType" name="interface_type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" onchange="changeInterfaceType()">
                                <option value="">请先选择支付方式</option>
                            </select>
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">接口名称</label>
                        <input type="text" id="interfaceName" name="name" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="如：支付宝官方支付">
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
                            <select id="interfaceStatus" name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
                                <option value="1">启用</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">排序</label>
                            <input type="number" id="interfaceSort" name="sort" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="数字越小越靠前" value="10">
                        </div>
                    </div>
                    
                    <div id="configFields" class="space-y-4">
                        <!-- 动态配置字段将在这里显示 -->
                    </div>
                </form>
            </div>
            <div class="px-6 py-4 border-t border-gray-100 flex justify-end gap-3">
                <button onclick="closeInterfaceModal()" class="px-6 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition">取消</button>
                <button onclick="document.getElementById('interfaceForm').dispatchEvent(new Event('submit'))" class="px-6 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="../assets/js/jquery.min.js"></script>

<?php include 'foot.php'; ?>
<script type="text/javascript">
var interfaceConfigs = {
    alipay: {
        alipay_official: {
            name: '支付宝官方',
            fields: [
                {name: 'appid', label: '应用APPID', type: 'text'},
                {name: 'publickey', label: '支付宝公钥(RSA2)', type: 'textarea'},
                {name: 'privatekey', label: '应用私钥(RSA2)', type: 'textarea'}
            ]
        },
        alipay_face: {
            name: '支付宝当面付',
            fields: [
                {name: 'appid', label: '应用APPID', type: 'text'},
                {name: 'publickey', label: '支付宝公钥(RSA2)', type: 'textarea'},
                {name: 'privatekey', label: '应用私钥(RSA2)', type: 'textarea'}
            ]
        },
        epay: {
            name: '彩虹易支付',
            fields: [
                {name: 'url', label: '接口网址', type: 'text', placeholder: '如：http://xxx.cn/'},
                {name: 'pid', label: '商户ID', type: 'text'},
                {name: 'key', label: '商户密钥', type: 'text'}
            ]
        }
    },
    qqpay: {
        qqpay_official: {
            name: 'QQ钱包官方',
            fields: [
                {name: 'mchid', label: 'QQ钱包商户号', type: 'text'},
                {name: 'key', label: 'QQ钱包API密钥', type: 'text'}
            ]
        },
        epay: {
            name: '彩虹易支付',
            fields: [
                {name: 'url', label: '接口网址', type: 'text', placeholder: '如：http://xxx.cn/'},
                {name: 'pid', label: '商户ID', type: 'text'},
                {name: 'key', label: '商户密钥', type: 'text'}
            ]
        }
    },
    wxpay: {
        wxpay_official: {
            name: '微信官方',
            fields: [
                {name: 'appid', label: '微信公众号APPID', type: 'text'},
                {name: 'mchid', label: '微信支付商户号', type: 'text'},
                {name: 'key', label: '微信支付商户密钥', type: 'text'},
                {name: 'appsecret', label: '微信公众号APPSECRET', type: 'text'},
                {name: 'domain', label: '微信支付指定域名', type: 'text'}
            ]
        },
        epay: {
            name: '彩虹易支付',
            fields: [
                {name: 'url', label: '接口网址', type: 'text', placeholder: '如：http://xxx.cn/'},
                {name: 'pid', label: '商户ID', type: 'text'},
                {name: 'key', label: '商户密钥', type: 'text'}
            ]
        }
    }
};

function openAddModal(){
    document.getElementById('modalTitle').textContent = '添加支付接口';
    document.getElementById('interfaceForm').reset();
    document.getElementById('interfaceId').value = '';
    document.getElementById('interfaceStatus').value = '1';
    document.getElementById('interfaceSort').value = '10';
    document.getElementById('configFields').innerHTML = '';
    document.getElementById('interfaceModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeInterfaceModal(){
    document.getElementById('interfaceModal').classList.add('hidden');
    document.body.style.overflow = '';
}

function changePayType(){
    var payType = $('#payType').val();
    var interfaceSelect = $('#interfaceType');
    
    var configFields = $('#configFields');
    var savedConfig = configFields.data('savedConfig') || {};
    
    configFields.find('input, textarea').each(function(){
        var name = $(this).attr('name');
        if(name && name.match(/^config\[/)){
            var key = name.replace('config[', '').replace(']', '');
            savedConfig[key] = $(this).val();
        }
    });
    
    interfaceSelect.html('<option value="">请选择接口类型</option>');
    
    if(payType && interfaceConfigs[payType]){
        for(var type in interfaceConfigs[payType]){
            interfaceSelect.append('<option value="'+type+'">'+interfaceConfigs[payType][type].name+'</option>');
        }
    }
    
    configFields.html('');
    configFields.data('savedConfig', savedConfig);
}

function changeInterfaceType(){
    var payType = $('#payType').val();
    var interfaceType = $('#interfaceType').val();
    var configFields = $('#configFields');
    
    var savedConfig = configFields.data('savedConfig') || {};
    
    configFields.find('input, textarea').each(function(){
        var name = $(this).attr('name');
        if(name && name.match(/^config\[/)){
            var key = name.replace('config[', '').replace(']', '');
            savedConfig[key] = $(this).val();
        }
    });
    
    configFields.html('');
    configFields.data('savedConfig', savedConfig);
    
    if(payType && interfaceType && interfaceConfigs[payType] && interfaceConfigs[payType][interfaceType]){
        var config = interfaceConfigs[payType][interfaceType];
        var fields = config.fields;
        
        for(var i=0; i<fields.length; i++){
            var field = fields[i];
            var fieldHtml = '<div>';
            fieldHtml += '<label class="block text-sm font-medium text-gray-700 mb-2">'+field.label+'</label>';
            
            var savedValue = savedConfig[field.name] || '';
            
            if(field.type == 'textarea'){
                fieldHtml += '<textarea name="config['+field.name+']" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" rows="3"';
                if(field.placeholder) fieldHtml += ' placeholder="'+field.placeholder+'"';
                if(savedValue) fieldHtml += '>'+savedValue+'</textarea>';
                else fieldHtml += '></textarea>';
            }else{
                fieldHtml += '<input type="text" name="config['+field.name+']" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"';
                if(field.placeholder) fieldHtml += ' placeholder="'+field.placeholder+'"';
                if(savedValue) fieldHtml += ' value="'+savedValue+'">';
                else fieldHtml += '>';
            }
            
            fieldHtml += '</div>';
            configFields.append(fieldHtml);
        }
    }
}

function saveInterface(e){
    e.preventDefault();
    
    var formData = $('#interfaceForm').serialize();
    showLoading();
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=save_pay_interface',
        data: formData,
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1){
                showToast(data.msg, 'success');
                setTimeout(function(){
                    window.location.reload();
                }, 1000);
            }else{
                showToast(data.msg, 'error');
            }
        },
        error: function(){
            hideLoading();
            showToast('服务器错误', 'error');
        }
    });
}

function editInterface(id){
    showLoading();
    
    $.ajax({
        type: 'GET',
        url: 'ajax.php?act=get_pay_interface&id='+id,
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1){
                var item = data.data;
                document.getElementById('modalTitle').textContent = '编辑支付接口';
                document.getElementById('interfaceId').value = item.id;
                $('#payType').val(item.pay_type);
                changePayType();
                $('#interfaceType').val(item.interface_type);
                changeInterfaceType();
                $('#interfaceName').val(item.name);
                $('#interfaceStatus').val(item.status);
                $('#interfaceSort').val(item.sort);
                
                var config = JSON.parse(item.config || '{}');
                for(var key in config){
                    $('input[name="config['+key+']"], textarea[name="config['+key+']"]').val(config[key]);
                }
                
                document.getElementById('interfaceModal').classList.remove('hidden');
                document.body.style.overflow = 'hidden';
            }else{
                showToast(data.msg, 'error');
            }
        },
        error: function(){
            hideLoading();
            showToast('服务器错误', 'error');
        }
    });
}

function copyInterface(id){
    showLoading();
    
    $.ajax({
        type: 'GET',
        url: 'ajax.php?act=get_pay_interface&id='+id,
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1){
                var item = data.data;
                
                if(item.interface_type != 'epay'){
                    showToast('只能复制彩虹易支付接口', 'error');
                    return;
                }
                
                document.getElementById('modalTitle').textContent = '添加支付接口';
                document.getElementById('interfaceId').value = '';
                $('#payType').val(item.pay_type);
                changePayType();
                $('#interfaceType').val(item.interface_type);
                changeInterfaceType();
                $('#interfaceName').val(item.name + ' (副本)');
                $('#interfaceStatus').val(item.status);
                $('#interfaceSort').val(item.sort);
                
                var config = JSON.parse(item.config || '{}');
                for(var key in config){
                    $('input[name="config['+key+']"], textarea[name="config['+key+']"]').val(config[key]);
                }
                
                document.getElementById('interfaceModal').classList.remove('hidden');
                document.body.style.overflow = 'hidden';
            }else{
                showToast(data.msg, 'error');
            }
        },
        error: function(){
            hideLoading();
            showToast('服务器错误', 'error');
        }
    });
}

function deleteInterface(id){
    if(confirm('确定要删除这个支付接口吗？')){
        showLoading();
        
        $.ajax({
            type: 'POST',
            url: 'ajax.php?act=delete_pay_interface',
            data: {id: id},
            dataType: 'json',
            success: function(data) {
                hideLoading();
                if(data.code == 1){
                    showToast(data.msg, 'success');
                    setTimeout(function(){
                        window.location.reload();
                    }, 1000);
                }else{
                    showToast(data.msg, 'error');
                }
            },
            error: function(){
                hideLoading();
                showToast('服务器错误', 'error');
            }
        });
    }
}
</script>
