<?php
include("./includes/common.php");

if(!$islogin2){
    header("Location: login.php");
    exit;
}

$csrf_token = md5(mt_rand(0,999).time());
$_SESSION['csrf_token'] = $csrf_token;

$title = '我的网盘 - ' . $conf['title'];
include SYSTEM_ROOT.'header.php';
?>
<style>
.disk-page-wrapper {
    padding: 20px 0;
}
.disk-header-card {
    background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
    border-radius: 20px;
    padding: 30px;
    margin-bottom: 25px;
    color: #fff;
    position: relative;
    overflow: hidden;
}
.disk-header-card::before {
    content: '';
    position: absolute;
    right: -30px;
    top: -30px;
    width: 150px;
    height: 150px;
    background: rgba(255,255,255,0.1);
    border-radius: 50%;
}
.disk-header-card h1 {
    font-size: 26px;
    font-weight: 700;
    margin: 0 0 8px;
    position: relative;
    z-index: 1;
}
.disk-header-card p {
    font-size: 14px;
    opacity: 0.9;
    margin: 0;
    position: relative;
    z-index: 1;
}
.disk-card {
    background: #fff;
    border-radius: 20px;
    box-shadow: 0 10px 40px rgba(15, 118, 110, 0.1);
    overflow: hidden;
    margin-bottom: 25px;
}
.disk-toolbar {
    padding: 20px 25px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}
.disk-toolbar-left {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}
.disk-toolbar-right {
    display: flex;
    gap: 10px;
}
.btn-disk {
    padding: 10px 20px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    gap: 8px;
    border: none;
}
.btn-disk-primary {
    background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
    color: #fff;
}
.btn-disk-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(15, 118, 110, 0.3);
}
.btn-disk-default {
    background: #f5f5f5;
    color: #555;
}
.btn-disk-default:hover {
    background: #eee;
}
.btn-disk-danger {
    background: #fee2e2;
    color: #dc2626;
}
.btn-disk-danger:hover {
    background: #dc2626;
    color: #fff;
}
.disk-breadcrumb {
    padding: 15px 25px;
    background: #fafafa;
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}
.disk-breadcrumb a {
    color: #0f766e;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.2s;
}
.disk-breadcrumb a:hover {
    color: #14b8a6;
}
.disk-breadcrumb .separator {
    color: #ccc;
    font-size: 12px;
}
.disk-breadcrumb .current {
    color: #333;
    font-weight: 500;
    font-size: 14px;
}
.disk-table {
    width: 100%;
    border-collapse: collapse;
}
.disk-table thead th {
    padding: 15px 20px;
    text-align: left;
    font-weight: 600;
    color: #666;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    background: #fafafa;
    border-bottom: 2px solid #f0f0f0;
}
.disk-table thead th:first-child {
    width: 50px;
    text-align: center;
}
.disk-table tbody tr {
    transition: all 0.2s;
    cursor: pointer;
}
.disk-table tbody tr:hover {
    background: #f0fdfa;
}
.disk-table tbody td {
    padding: 15px 20px;
    border-bottom: 1px solid #f5f5f5;
    vertical-align: middle;
}
.disk-table tbody td:first-child {
    text-align: center;
}
.disk-table .item-checkbox {
    width: 18px;
    height: 18px;
    accent-color: #14b8a6;
    cursor: pointer;
}
.disk-table .file-name {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
    min-width: 0;
}
.disk-table .folder-icon {
    width: 44px;
    height: 44px;
    background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 18px;
    flex-shrink: 0;
}
.disk-table .file-icon {
    width: 44px;
    height: 44px;
    background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 16px;
    flex-shrink: 0;
}
.disk-table .name-text {
    font-weight: 500;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
}
.disk-table .file-size {
    color: #666;
    font-size: 14px;
    white-space: nowrap;
}
.disk-table .file-time {
    color: #888;
    font-size: 14px;
    white-space: nowrap;
}
.btn-manage-modern {
    padding: 8px 16px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    background: #e6f9f7;
    color: #0f766e;
    border: 1px solid #14b8a6;
    white-space: nowrap;
}
.btn-manage-modern:hover {
    background: #14b8a6;
    color: #fff;
}
.disk-table .item-checkbox {
    width: 18px;
    height: 18px;
    accent-color: #14b8a6;
    cursor: pointer;
}
    .disk-table .file-name {
        display: flex;
        align-items: center;
        gap: 12px;
        flex: 1;
        min-width: 0;
    }
    .disk-table .folder-icon {
        width: 44px;
        height: 44px;
        background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 18px;
        flex-shrink: 0;
    }
    .disk-table .file-icon {
        width: 44px;
        height: 44px;
        background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 16px;
        flex-shrink: 0;
    }
    .disk-table .name-text {
        font-weight: 500;
        color: #333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px;
    }
    .disk-table .file-size {
        color: #666;
        font-size: 14px;
        white-space: nowrap;
    }
    .disk-table .file-time {
        color: #888;
        font-size: 14px;
        white-space: nowrap;
    }
    .btn-manage-modern {
        padding: 8px 16px;
        border-radius: 8px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
        background: #e6f9f7;
        color: #0f766e;
        border: 1px solid #14b8a6;
        white-space: nowrap;
    }
.btn-manage-modern:hover {
    background: #14b8a6;
    color: #fff;
}
.quota-alert {
    background: linear-gradient(135deg, rgba(220, 38, 38, 0.1) 0%, rgba(220, 38, 38, 0.05) 100%);
    border: 1px solid #fca5a5;
    border-radius: 12px;
    padding: 15px 20px;
    margin-bottom: 20px;
    display: none;
    align-items: center;
    gap: 12px;
    color: #dc2626;
}
.quota-alert i {
    font-size: 20px;
}
.context-menu-modern {
    position: fixed;
    display: none;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
    z-index: 1000;
    overflow: hidden;
    min-width: 180px;
}
.context-menu-modern ul {
    list-style: none;
    padding: 8px 0;
    margin: 0;
}
.context-menu-modern li {
    padding: 12px 20px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #555;
    font-size: 14px;
    transition: all 0.2s;
}
.context-menu-modern li:hover {
    background: #f0fdfa;
    color: #0f766e;
}
.context-menu-modern li.danger:hover {
    background: #fee2e2;
    color: #dc2626;
}
.context-menu-modern li i {
    width: 20px;
    text-align: center;
}
.manage-list-item-modern {
    padding: 14px 20px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 12px;
    color: #555;
    text-decoration: none !important;
    font-size: 14px;
}
.manage-list-item-modern:hover {
    background: #f0fdfa;
    color: #0f766e;
}
.manage-list-item-modern:last-child {
    border-bottom: none;
}
.manage-list-item-modern i {
    width: 20px;
    text-align: center;
    color: #0f766e;
}
.manage-list-item-modern.danger:hover {
    background: #fee2e2;
    color: #dc2626;
}
.manage-list-item-modern.danger i {
    color: #dc2626;
}
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;
}
.empty-state i {
    font-size: 60px;
    color: #ddd;
    margin-bottom: 20px;
    display: block;
}
.empty-state p {
    font-size: 16px;
    margin: 0;
}
.drop-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(15, 118, 110, 0.9);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    flex-direction: column;
    color: #fff;
}
.drop-overlay.active {
    display: flex;
}
.drop-overlay i {
    font-size: 80px;
    margin-bottom: 20px;
}
.drop-overlay p {
    font-size: 24px;
    font-weight: 600;
}
.share-settings-modal {
    padding: 0;
    display: flex;
    flex-direction: column;
    max-height: 70vh;
}
.share-settings-scroll {
    padding: 15px;
    overflow-y: auto;
    flex: 1;
}
.share-section {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
}
.share-section:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}
.share-section h4 {
    margin: 0 0 12px 0;
    font-size: 15px;
    color: #333;
    font-weight: 600;
}
.share-section h4 i {
    color: #0f766e;
    margin-right: 6px;
}
.share-url-box {
    display: flex;
    gap: 10px;
}
.share-url-input {
    flex: 1;
    background: #f8f9fa;
    border: 1px solid #e0e0e0;
}
.share-notice-textarea {
    resize: vertical;
    min-height: 120px;
    font-family: monospace;
    font-size: 13px;
}
.share-preview-section {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
}
.notice-preview-box {
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 12px;
    min-height: 60px;
    max-height: 200px;
    overflow-y: auto;
}
.notice-preview-box img {
    max-width: 100%;
    height: auto;
}
.notice-preview-box a {
    color: #0f766e;
    text-decoration: underline;
}
/* 胶囊开关样式 */
.capsule-toggle {
    display: inline-flex;
    align-items: center;
    gap: 12px;
    cursor: pointer;
}
.capsule-switch {
    position: relative;
    width: 56px;
    height: 30px;
    background: #e0e0e0;
    border-radius: 15px;
    transition: all 0.3s;
    flex-shrink: 0;
}
.capsule-switch::after {
    content: '';
    position: absolute;
    top: 3px;
    left: 3px;
    width: 24px;
    height: 24px;
    background: #fff;
    border-radius: 50%;
    transition: all 0.3s;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.capsule-toggle.active .capsule-switch {
    background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
}
.capsule-toggle.active .capsule-switch::after {
    left: 29px;
}
.capsule-label {
    font-size: 14px;
    color: #666;
    user-select: none;
}
.capsule-toggle.active .capsule-label {
    color: #0f766e;
    font-weight: 500;
}
/* 密码输入区域 */
.pwd-input-area {
    margin-top: 16px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 10px;
    border: 1px solid #e0e0e0;
}
.pwd-input-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-size: 13px;
    color: #666;
}
.pwd-input-header i {
    color: #14b8a6;
}
.pwd-input-wrapper {
    position: relative;
}
.pwd-input-wrapper .form-control {
    padding-right: 40px;
    font-size: 16px;
    letter-spacing: 2px;
}
.pwd-toggle-visible {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: #999;
    cursor: pointer;
    font-size: 16px;
    padding: 0;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.pwd-toggle-visible:hover {
    color: #0f766e;
}
.pwd-hint {
    margin-top: 10px;
    font-size: 12px;
    color: #888;
    display: flex;
    align-items: center;
    gap: 6px;
}
.pwd-hint i {
    color: #14b8a6;
}
.transfer-modal-content {
    padding: 20px;
}
.transfer-input-group {
    margin-bottom: 15px;
}
.transfer-input-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #555;
}
.transfer-url-input {
    width: 100%;
    padding: 12px 15px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    font-size: 14px;
    transition: all 0.3s;
}
.transfer-url-input:focus {
    outline: none;
    border-color: #14b8a6;
    box-shadow: 0 0 0 3px rgba(20, 184, 166, 0.1);
}
.transfer-preview {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 15px;
    display: none;
}
.transfer-preview.show {
    display: block;
}
.transfer-preview-header {
    font-size: 13px;
    color: #666;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 6px;
}
.transfer-item-info {
    display: flex;
    align-items: center;
    gap: 12px;
}
.transfer-item-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
}
.transfer-item-icon.folder {
    background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
    color: #fff;
}
.transfer-item-icon.file {
    background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
    color: #fff;
}
.transfer-item-details {
    flex: 1;
}
.transfer-item-name {
    font-weight: 500;
    color: #333;
    margin-bottom: 2px;
}
.transfer-item-meta {
    font-size: 12px;
    color: #888;
}
.transfer-password-section {
    display: none;
    margin-top: 15px;
    padding: 15px;
    background: #fff3cd;
    border-radius: 10px;
    border: 1px solid #ffeeba;
}
.transfer-password-section.show {
    display: block;
}
.transfer-password-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-size: 14px;
    color: #856404;
}
.transfer-progress {
    display: none;
    margin-top: 15px;
}
.transfer-progress.show {
    display: block;
}
.transfer-progress-bar {
    height: 8px;
    background: #e9ecef;
    border-radius: 4px;
    overflow: hidden;
}
.transfer-progress-fill {
    height: 100%;
    background: linear-gradient(135deg, #0f766e 0%, #14b8a6 100%);
    transition: width 0.3s;
    width: 0%;
}
.transfer-progress-text {
    text-align: center;
    font-size: 13px;
    color: #666;
    margin-top: 8px;
}
@media (max-width: 768px) {
    .disk-page-wrapper {
        padding: 10px 0;
    }
    .disk-header-card {
        padding: 20px 15px;
        border-radius: 15px;
        margin-bottom: 15px;
    }
    .disk-header-card h1 {
        font-size: 20px;
        white-space: nowrap;
    }
    .disk-header-card p {
        font-size: 13px;
    }
    .disk-card {
        border-radius: 15px;
        margin-bottom: 15px;
        overflow: hidden;
    }
    .disk-toolbar {
        flex-direction: column;
        gap: 12px;
        padding: 16px;
    }
    .disk-toolbar-left,
    .disk-toolbar-right {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }
    .disk-toolbar .btn-disk {
        min-height: 44px;
        padding: 12px 16px;
        font-size: 13px;
        white-space: nowrap;
    }
    .disk-breadcrumb {
        padding: 14px 16px;
        font-size: 12px;
        flex-wrap: wrap;
    }
    .disk-breadcrumb a {
        padding: 4px 8px;
    }
    
    .disk-table {
        display: table;
        width: 100%;
        border-collapse: collapse;
    }
    .disk-table thead {
        display: none;
    }
    .disk-table tbody {
        display: table-row-group;
    }
    .disk-table tbody tr {
        display: table-row;
        padding: 0;
        background: #fff;
        border-bottom: 1px solid #f0f0f0;
        box-shadow: none;
    }
    .disk-table tbody tr:hover {
        background: #f0fdfa;
    }
    .disk-table tbody td {
        padding: 14px 10px;
        border: none;
        display: table-cell;
        vertical-align: middle;
    }
    .disk-table tbody td:first-child {
        width: 40px;
        text-align: center;
        padding-left: 10px;
    }
    .disk-table tbody td:nth-child(2) {
        min-width: 150px;
    }
    .disk-table tbody td:nth-child(3),
    .disk-table tbody td:nth-child(4) {
        display: none;
    }
    .disk-table tbody td:nth-child(5) {
        width: 70px;
        text-align: right;
        padding-right: 10px;
    }
    .disk-table .file-icon,
    .disk-table .folder-icon {
        display: inline-flex;
        width: 32px;
        height: 32px;
        font-size: 14px;
        vertical-align: middle;
        margin-right: 8px;
    }
    .disk-table .file-name {
        display: inline-flex;
        align-items: center;
        gap: 0;
    }
    .disk-table .name-text {
        font-size: 14px;
        max-width: 120px;
    }
    .disk-table .btn-manage-modern {
        padding: 6px 10px;
        font-size: 11px;
    }
    .disk-table td:first-child input {
        width: 16px;
        height: 16px;
    }
    .disk-pagination {
        flex-wrap: wrap;
        gap: 5px;
        padding: 15px 10px;
    }
    .disk-pagination a,
    .disk-pagination span {
        padding: 8px 12px;
        font-size: 12px;
    }
    .disk-modal .modal-dialog {
        width: 95%;
        margin: 10px auto;
    }
    .disk-modal .modal-content {
        border-radius: 12px;
    }
    .disk-modal .modal-header {
        padding: 15px;
    }
    .disk-modal .modal-body {
        padding: 15px;
    }
    .disk-modal .modal-footer {
        padding: 10px 15px;
        flex-direction: column;
        gap: 10px;
    }
    .disk-modal .modal-footer .btn {
        width: 100%;
        min-height: 44px;
    }
    .quota-alert {
        padding: 12px 15px;
        border-radius: 10px;
        font-size: 13px;
    }
    /* 分享设置弹窗手机端适配 */
    .share-settings-modal {
        max-height: 65vh;
    }
    .share-settings-scroll {
        padding: 12px;
    }
    .share-section {
        margin-bottom: 15px;
        padding-bottom: 15px;
    }
    .share-section h4 {
        font-size: 14px;
        margin-bottom: 10px;
    }
    .share-url-box {
        flex-direction: column;
        gap: 8px;
    }
    .share-url-input {
        width: 100%;
        font-size: 13px;
        padding: 10px 12px;
    }
    .share-url-box .btn {
        width: 100%;
        padding: 10px;
        font-size: 14px;
    }
    .capsule-switch {
        width: 48px;
        height: 26px;
    }
    .capsule-switch::after {
        width: 20px;
        height: 20px;
        top: 3px;
        left: 3px;
    }
    .capsule-toggle.active .capsule-switch::after {
        left: 25px;
    }
    .capsule-label {
        font-size: 13px;
    }
    .pwd-input-area {
        margin-top: 12px;
        padding: 12px;
    }
    .pwd-input-wrapper .form-control {
        font-size: 14px;
        padding: 10px 12px;
        padding-right: 40px;
    }
    .share-notice-textarea {
        min-height: 80px;
        font-size: 14px;
        padding: 10px 12px;
    }
    .share-preview-section {
        padding: 12px;
    }
    .notice-preview-box {
        padding: 10px;
        min-height: 50px;
        max-height: 150px;
    }
    .pwd-hint {
        font-size: 11px;
    }
    /* 转存弹窗手机端适配 */
    .transfer-modal-content {
        padding: 15px;
    }
    .transfer-input-group label {
        font-size: 14px;
    }
    .transfer-url-input {
        padding: 12px;
        font-size: 14px;
    }
    .transfer-preview {
        padding: 12px;
    }
    .transfer-item-icon {
        width: 36px;
        height: 36px;
        font-size: 16px;
    }
    .transfer-item-name {
        font-size: 14px;
    }
    .transfer-item-meta {
        font-size: 11px;
    }
    .transfer-password-section {
        padding: 12px;
    }
    .transfer-password-header {
        font-size: 13px;
    }
    .transfer-progress-text {
        font-size: 12px;
    }
}
</style>

<div class="container disk-page-wrapper">
    <input type="hidden" id="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    
    <div class="disk-header-card">
        <h1><i class="fa fa-hdd-o"></i> 我的网盘</h1>
        <p>管理您的文件和文件夹</p>
    </div>
    
    <div id="quota-alert" class="quota-alert">
        <i class="fa fa-exclamation-triangle"></i>
        <span id="quota-msg"></span>
    </div>
    
    <div class="disk-card">
        <div class="disk-toolbar">
            <div class="disk-toolbar-left">
                <button class="btn-disk btn-disk-primary" onclick="createFolder()">
                    <i class="fa fa-folder-o"></i> 新建文件夹
                </button>
                <div id="batch-actions" style="display:none; display: flex; gap: 10px;">
                    <button class="btn-disk btn-disk-default" onclick="batchAction('copy')">
                        <i class="fa fa-copy"></i> 复制
                    </button>
                    <button class="btn-disk btn-disk-default" onclick="batchAction('move')">
                        <i class="fa fa-arrows"></i> 移动
                    </button>
                    <button class="btn-disk btn-disk-danger" onclick="batchAction('delete')">
                        <i class="fa fa-trash"></i> 删除
                    </button>
                </div>
            </div>
            <div class="disk-toolbar-right">
                <button class="btn-disk btn-disk-default" onclick="openTransferModal()">
                    <i class="fa fa-download"></i> 转存
                </button>
                <button class="btn-disk btn-disk-default" onclick="openSearchModal()">
                    <i class="fa fa-search"></i> 搜索
                </button>
                <button class="btn-disk btn-disk-default" onclick="loadFolder(currentFolderId)">
                    <i class="fa fa-refresh"></i> 刷新
                </button>
            </div>
        </div>
        
        <div class="disk-breadcrumb" id="breadcrumb">
            <a href="javascript:loadFolder(0)"><i class="fa fa-home"></i> 根目录</a>
        </div>
        
        <table class="disk-table">
            <thead>
                <tr>
                    <th><input type="checkbox" id="check-all" class="item-checkbox"></th>
                    <th>名称</th>
                    <th>大小</th>
                    <th>修改时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="file-list-body">
                <tr>
                    <td colspan="5" class="empty-state">
                        <i class="fa fa-spinner fa-spin"></i>
                        <p>加载中...</p>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<div class="context-menu-modern" id="context-menu">
    <ul>
        <li onclick="menuAction('rename')"><i class="fa fa-edit"></i> 重命名</li>
        <li onclick="menuAction('move')"><i class="fa fa-arrows"></i> 移动到</li>
        <li onclick="menuAction('copy')" id="menu-copy"><i class="fa fa-copy"></i> 复制到</li>
        <li onclick="menuAction('toggle_hide')" id="menu-hide"><i class="fa fa-eye-slash"></i> 隐藏/显示</li>
        <li onclick="menuAction('password')" id="menu-pwd"><i class="fa fa-lock"></i> 设置密码</li>
        <li onclick="menuAction('share')" id="menu-share"><i class="fa fa-share-alt"></i> 分享</li>
        <li class="danger" onclick="menuAction('delete')"><i class="fa fa-trash"></i> 删除</li>
    </ul>
</div>

<div class="drop-overlay" id="drop-overlay">
    <i class="fa fa-cloud-upload"></i>
    <p>释放以开始上传</p>
</div>

<input type="file" id="upload-input" multiple accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,image/*,.zip,.rar,.7z" style="display:none" onchange="performUpload()">

<!-- Folder Selector Template -->
<div id="folder-selector-tpl" style="display:none;">
    <div style="padding: 10px;">
        <div style="margin-bottom: 10px;">
            当前位置: <span id="fs-current-path">/</span>
            <button class="btn btn-xs btn-default pull-right" onclick="loadSelectorFolder(0)">根目录</button>
            <button class="btn btn-xs btn-default pull-right" onclick="loadSelectorFolder(fsCurrentParentId)" style="margin-right:5px;">上一级</button>
        </div>
        <div id="fs-tree" class="folder-tree-container"></div>
    </div>
</div>

<!-- Batch Upload Modal -->
<div id="batch-upload-modal-tpl" style="display:none;">
    <div style="padding: 15px;">
        <div class="row">
            <div class="col-xs-12">
                <div id="drop-zone" class="drop-zone text-center" onclick="$('#batch-file-input').click()">
                    <i class="fa fa-cloud-upload fa-3x"></i>
                    <p>点击选择文件 或 拖拽文件到此处</p>
                    <input type="file" id="batch-file-input" multiple style="display:none">
                </div>
            </div>
        </div>
        <div class="row" style="margin-bottom: 10px;">
             <div class="col-xs-12">
                 <button class="btn btn-success btn-sm" onclick="batchUploader.start()">开始上传</button>
                 <button class="btn btn-warning btn-sm" onclick="clearCompleted()">清除已完成</button>
                 <label class="checkbox-inline" style="margin-left:10px;"><input type="checkbox" class="show-on-index-chk" checked> 在首页文件列表显示</label>
                 <span id="batch-status-text" class="pull-right" style="line-height: 30px;"></span>
             </div>
        </div>
        <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
            <table class="table table-striped table-condensed">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th width="80">大小</th>
                        <th width="120">进度</th>
                        <th width="80">速度</th>
                        <th width="80">状态</th>
                        <th width="50">操作</th>
                    </tr>
                </thead>
                <tbody id="batch-file-list">
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/3.0.2/spark-md5.min.js"></script>
<script src="assets/js/batch_upload.js?v=<?php echo time();?>"></script>
<!-- Remove duplicate layer.js 2.3 if exists -->
<script src="https://s4.zstatic.net/ajax/libs/layer/3.1.1/layer.min.js"></script>
<script>
var currentFolderId = 0;
var currentRightClickItem = null; 
var fsCurrentFolderId = 0;
var fsCurrentParentId = 0;
var fsSelectedFolderId = null;
var batchUploader = null;
var batchLayerIndex = null;
var manageLayerIndex = null;

function openBatchUpload() {
    batchLayerIndex = layer.open({
        type: 1,
        skin: 'layer-no-padding',
        title: '批量上传',
        area: ['800px', '600px'],
        content: $('#batch-upload-modal-tpl').html(),
        success: function(layero, index){
            initBatchUploader();
        },
        cancel: function(){
        }
    });
}

function initBatchUploader() {
    if(!batchUploader) {
        batchUploader = new BatchUploader({
            concurrency: 3,
            onQueueUpdate: updateBatchList,
            onProgress: function(file, progress, speed) {
                 updateBatchList(batchUploader.queue);
            },
            onSuccess: function(file, res) {
                 if(res.id) file.db_id = res.id;
                 file.hide = (res.hide !== undefined) ? res.hide : (batchUploader.showInHome ? 0 : 1);
                 updateBatchList(batchUploader.queue);
                 if (batchUploader.queue.every(f => f.status === 'completed')) {
                     loadFolder(currentFolderId);
                 }
            },
            onError: function(file, err) {
                 updateBatchList(batchUploader.queue);
            },
            onComplete: function() {
                var newIds = [];
                batchUploader.queue.forEach(function(f){
                    if (f.status === 'completed' && f.db_id) {
                        newIds.push(f.db_id);
                    }
                });
                
                if (newIds.length > 0) {
                    $.post('ajax.php?act=sync_guest_ids', {ids: newIds}, function(res){
                        layer.alert('所有文件处理完毕', {icon: 1}, function(i){ layer.close(i); loadFolder(currentFolderId); });
                    }, 'json');
                } else {
                    layer.alert('所有文件处理完毕', {icon: 1}, function(i){ layer.close(i); loadFolder(currentFolderId); });
                }
            }
        });
    } else {

    }

    var $container = $('.layui-layer-content');
    $container.find('#batch-file-input').on('change', function(){
        batchUploader.addFiles(this.files);
        $(this).val('');
    });
    
    var $dropZone = $container.find('#drop-zone');
    $dropZone.on('dragover', function(e){
        e.preventDefault();
        e.stopPropagation();
        $(this).css('background-color', '#eee');
    });
    $dropZone.on('dragleave', function(e){
        e.preventDefault();
        e.stopPropagation();
        $(this).css('background-color', '#fff');
    });
    $dropZone.on('drop', function(e){
        e.preventDefault();
        e.stopPropagation();
        $(this).css('background-color', '#fff');
        var files = e.originalEvent.dataTransfer.files;
        batchUploader.addFiles(files);
    });
    
    $container.find('button[onclick="batchUploader.start()"]').attr('onclick', '').click(function(){
        batchUploader.start();
    });
    $container.find('button[onclick="clearCompleted()"]').attr('onclick', '').click(function(){
        clearCompleted();
    });

    var $chk = $container.find('.show-on-index-chk');
    batchUploader.setShowInHome($chk.prop('checked')); 
    $chk.on('change', function(){
        batchUploader.setShowInHome($(this).prop('checked'));
    });
    
    updateBatchList(batchUploader.queue);
}

function updateBatchList(queue) {
    var html = '';
    queue.forEach(function(f){
        var statusClass = 'text-muted';
        if(f.status == 'uploading') statusClass = 'text-primary';
        if(f.status == 'completed') statusClass = 'text-success';
        if(f.status == 'error') statusClass = 'text-danger';
        
        html += '<tr>';
        html += '<td title="'+f.file.name+'" style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">'+f.file.name+'</td>';
        html += '<td>'+batchUploader.formatSize(f.file.size)+'</td>';
        html += '<td><div class="progress" style="margin-bottom:0;"><div class="progress-bar progress-bar-success" style="width: '+f.progress+'%">'+f.progress+'%</div></div></td>';
        html += '<td>'+f.speed+'</td>';
        html += '<td class="'+statusClass+'">'+(f.status=='error'?f.message:f.status);
        if(f.status == 'completed' && f.db_id) {
            var hideText = f.hide == 1 ? '显示' : '隐藏';
            var hideClass = f.hide == 1 ? 'btn-success' : 'btn-warning';
            html += ' <button class="btn btn-xs '+hideClass+'" onclick="toggleHide('+f.db_id+', this)" style="margin-left:5px;">'+hideText+'</button>';
        }
        html += '</td>';
        html += '<td><a href="javascript:;" onclick="removeFromQueue(\''+f.id+'\')" class="text-danger"><i class="fa fa-times"></i></a></td>';
        html += '</tr>';
    });
    $('.layui-layer-content').find('#batch-file-list').html(html);
}

function toggleHide(id, btn, isManage) {
    var $btn = $(btn);
    var token = $('#csrf_token').val();
    if (!token) {
        token = $('input[name="csrf_token"]').val();
    }
    
    $.post('ajax.php?act=toggle_hide', {id: id, csrf_token: token}, function(res){
        if(res.code == 0) {
            if(isManage) {
                layer.alert('操作成功', {icon: 1}, function(i){
                    layer.close(i);
                    loadFolder(currentFolderId);
                    layer.close(manageLayerIndex);
                });
            } else {
                if(res.hide == 1) {
                    $btn.removeClass('btn-warning').addClass('btn-success').text('显示');
                } else {
                    $btn.removeClass('btn-success').addClass('btn-warning').text('隐藏');
                }
                var item = batchUploader.queue.find(function(f){ return f.db_id == id; });
                if(item) item.hide = res.hide;
                loadFolder(currentFolderId);
            }
        } else {
            layer.alert(res.msg, {icon: 2});
        }
    }, 'json');
}

function removeFromQueue(id) {
    batchUploader.removeFile(id);
}

function clearCompleted() {
    for(var i=batchUploader.queue.length-1; i>=0; i--) {
        if(batchUploader.queue[i].status === 'completed') {
            batchUploader.queue.splice(i, 1);
        }
    }
    updateBatchList(batchUploader.queue);
}

// ... existing code ...


$(document).ready(function() {
    loadFolder(currentFolderId);

    $(document).on('click', function() {
        $('#context-menu').hide();
    });

    $(document).on('dragenter dragover drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
    });

    $(document).on('dragenter', function(e) {
        $('#drop-overlay').addClass('active');
    });

    $(document).on('dragleave', function(e) {
        if (!e.relatedTarget || e.relatedTarget.nodeName == "HTML") {
            $('#drop-overlay').removeClass('active');
        }
    });

    $(document).on('drop', function(e) {
        $('#drop-overlay').removeClass('active');
        var files = e.originalEvent.dataTransfer.files;
        if(files.length > 0) {
            handleBatchUpload(files);
        }
    });

    $('#check-all').change(function() {
        $('.item-checkbox').prop('checked', $(this).prop('checked'));
        updateBatchActions();
    });
    
    $(document).on('change', '.item-checkbox', function() {
        updateBatchActions();
    });

    var urlParams = new URLSearchParams(window.location.search);
    if(urlParams.get('open_upload') === '1') {
        setTimeout(function(){
            uploadFile();
        }, 500);
    }
});

function manageItem(type, id, name, sort, hash) {
    var content = '';
    if(type == 'folder') {
        content += '<a href="javascript:;" class="manage-list-item-modern" onclick="promptRename(\'folder\', '+id+', \''+name+'\')"><i class="fa fa-edit"></i> 重命名</a>';
        content += '<a href="javascript:;" class="manage-list-item-modern" onclick="promptSort('+id+', '+(sort||0)+')"><i class="fa fa-sort-numeric-asc"></i> 排序</a>';
        content += '<a href="javascript:;" class="manage-list-item-modern" onclick="openShareSettings('+id+')"><i class="fa fa-share-alt"></i> 分享设置</a>';
        content += '<a href="javascript:;" class="manage-list-item-modern danger" onclick="deleteItem(\'folder\', '+id+')"><i class="fa fa-trash"></i> 删除</a>';
    } else {
        content += '<a href="./file.php?hash='+hash+'" target="_blank" class="manage-list-item-modern"><i class="fa fa-eye"></i> 查看</a>';
        content += '<a href="javascript:;" class="manage-list-item-modern" onclick="toggleHide('+id+', this, true)"><i class="fa fa-eye-slash"></i> 隐藏/显示</a>';
        content += '<a href="javascript:;" class="manage-list-item-modern danger" onclick="deleteItem(\'file\', '+id+', \''+hash+'\')"><i class="fa fa-trash"></i> 删除</a>';
    }
    
    manageLayerIndex = layer.open({
        type: 1,
        skin: 'layer-no-padding',
        title: '管理 - ' + name,
        content: '<div style="margin:0;">' + content + '</div>',
        area: ['300px', 'auto'],
        offset: 'auto',
        shadeClose: true,
        anim: 5,
        isOutAnim: true,
        success: function(layero, index){
        }
    });
}

function promptRename(type, id, name) {
    layer.closeAll('page');
    layer.prompt({title: '重命名', value: name}, function(value, index){
        var act = type == 'folder' ? 'rename' : 'rename_file';
        var data = type == 'folder' ? {folder_id: id, new_name: value} : {file_id: id, new_name: value};
        $.post('folder_api.php?act='+act, data, function(res){
            if(res.code == 0) { 
                layer.alert('成功', {icon: 1}, function(i){
                    layer.close(i);
                    loadFolder(currentFolderId);
                });
            }
            else layer.alert(res.msg, {icon: 2});
            layer.close(index);
        }, 'json');
    });
}

function promptSort(id, currentSort) {
    layer.closeAll('page');
    layer.prompt({title: '输入排序 (1-999, 小号在前)', value: currentSort}, function(value, index){
        var sort = parseInt(value);
        if(isNaN(sort) || sort < 1 || sort > 999) {
            layer.alert('请输入1-999之间的数字', {icon: 2});
            return;
        }
        $.post('folder_api.php?act=sort', {folder_id: id, sort: sort}, function(res){
            if(res.code == 0) { 
                layer.alert('设置成功', {icon: 1}, function(i){
                    layer.close(i);
                    loadFolder(currentFolderId);
                });
            }
            else layer.alert(res.msg, {icon: 2});
            layer.close(index);
        }, 'json');
    });
}

function handleBatchUpload(files) {
    if(files.length == 0) return;
    
    openBatchUpload();
    setTimeout(function(){
        if(batchUploader) {
            batchUploader.addFiles(files);
            // 自动开始上传
            batchUploader.start();
        }
    }, 100);
}

function updateProgress(completed, total, text) {
    var percent = Math.round((completed / total) * 100);
    $('#upload-progress-bar').css('width', percent + '%').text(percent + '%');
    $('#upload-status').text(text);
}

function uploadFile() {
    $('#upload-input').attr('multiple', 'multiple'); 
    $('#upload-input').click();
}

function performUpload() {
    var files = $('#upload-input')[0].files;
    handleBatchUpload(files);
    $('#upload-input').val(''); 
}

function updateBatchActions() {
    var checked = $('.item-checkbox:checked').length;
    if (checked > 0) {
        $('#batch-actions').css('display', 'flex');
    } else {
        $('#batch-actions').hide();
    }
}

function batchAction(action) {
    var folderIds = [];
    var fileIds = [];
    
    $('.item-checkbox:checked').each(function(){
        var type = $(this).data('type');
        var id = $(this).data('id');
        if(type == 'folder') folderIds.push(id);
        else fileIds.push(id);
    });
    
    if(folderIds.length == 0 && fileIds.length == 0) {
        layer.alert('请选择要操作的项目', {icon: 2});
        return;
    }
    
    if(action == 'delete') {
        layer.confirm('确定要删除选中的 '+(folderIds.length+fileIds.length)+' 项吗？', {icon: 3}, function(index){
            var loadIndex = layer.load(1);
            $.post('folder_api.php?act=batch_delete', {folder_ids: folderIds, file_ids: fileIds}, function(res){
                layer.close(loadIndex);
                if(res.code == 0) {
                    layer.alert('删除成功', {icon: 1}, function(i){
                        layer.close(i);
                        loadFolder(currentFolderId);
                        $('#check-all').prop('checked', false);
                        updateBatchActions();
                    });
                } else {
                    layer.alert(res.msg, {icon: 2});
                }
            }, 'json');
            layer.close(index);
        });
    } else if(action == 'move' || action == 'copy') {
        openFolderSelector(function(targetId){
            var loadIndex = layer.load(1);
            var act = action == 'move' ? 'move' : 'batch_copy';
            
            if(action == 'copy' && folderIds.length > 0) {
                layer.alert('暂不支持复制文件夹，仅复制文件', {icon: 2});
                if(fileIds.length == 0) { layer.close(loadIndex); return; }
            }
            
            var data = {target_id: targetId};
            if(action == 'move') {
                data.folder_ids = folderIds;
                data.file_ids = fileIds;
            } else {
                data.file_ids = fileIds;
            }
            
            $.post('folder_api.php?act='+act, data, function(res){
                layer.close(loadIndex);
                if(res.code == 0) {
                    layer.alert('操作成功', {icon: 1}, function(i){
                        layer.close(i);
                        loadFolder(currentFolderId);
                        $('#check-all').prop('checked', false);
                        updateBatchActions();
                    });
                } else {
                    layer.alert(res.msg, {icon: 2});
                }
            }, 'json');
        });
    }
}

function openSearchModal() {
    layer.prompt({title: '搜索文件', formType: 0}, function(value, index){
        layer.close(index);
        doSearch(value);
    });
}

function doSearch(kw) {
    if(!kw) {
        loadFolder(currentFolderId);
        return;
    }
    
    var loadIndex = layer.load(1);
    $.get('folder_api.php', {act: 'list', kw: kw, t: new Date().getTime()}, function(res) {
        layer.close(loadIndex);
        if(res.code == 0) {
            renderList(res);
            $('#breadcrumb').html('<a href="javascript:loadFolder(0)"><i class="fa fa-home"></i> 根目录</a><span class="separator"><i class="fa fa-angle-right"></i></span><span class="current">搜索结果: "'+kw+'"</span>');
        } else {
            layer.alert(res.msg, {icon: 2});
        }
    }, 'json').fail(function() {
        layer.close(loadIndex);
        layer.alert('搜索失败', {icon: 2});
    });
}

function loadFolder(folderId, callback) {
    currentFolderId = folderId;
    var loadIndex = layer.load(1);
    
    $.get('folder_api.php', {act: 'list', parent_id: folderId, t: new Date().getTime()}, function(res) {
        layer.close(loadIndex);
        if(res.code == 0) {
            renderList(res);
            if (typeof callback === 'function') callback();
        } else {
            layer.alert(res.msg, {icon: 2});
        }
    }, 'json').fail(function() {
        layer.close(loadIndex);
        layer.alert('加载失败', {icon: 2});
    });
}

function renderList(data) {
    if(data.quota && data.quota.code !== 0) {
        $('#quota-msg').text(data.quota.msg);
        $('#quota-alert').css('display', 'flex');
    } else {
        $('#quota-alert').hide();
    }

    var html = '';
    
    var bcHtml = '<a href="javascript:loadFolder(0)"><i class="fa fa-home"></i> 根目录</a>';
    if(data.path) {
        data.path.forEach(function(p) {
            bcHtml += '<span class="separator"><i class="fa fa-angle-right"></i></span>';
            bcHtml += '<a href="javascript:loadFolder('+p.folder_id+')">'+p.name+'</a>';
        });
    }
    $('#breadcrumb').html(bcHtml);

    if(data.folders && Array.isArray(data.folders)) {
        data.folders.forEach(function(f) {
            html += '<tr oncontextmenu="showContextMenu(event, \'folder\', '+f.folder_id+', \''+f.name+'\')">';
            html += '<td><input type="checkbox" class="item-checkbox" data-type="folder" data-id="'+f.folder_id+'"></td>';
            html += '<td onclick="loadFolder('+f.folder_id+')"><div class="file-name"><div class="folder-icon"><i class="fa fa-folder"></i></div><span class="name-text">'+f.name+'</span></div></td>';
            html += '<td class="file-size">-</td>';
            html += '<td class="file-time">'+f.updated_at+'</td>';
            html += '<td><button class="btn-manage-modern" onclick="event.stopPropagation(); manageItem(\'folder\', '+f.folder_id+', \''+f.name+'\', '+f.sort+')"><i class="fa fa-cog"></i> 管理</button></td>';
            html += '</tr>';
        });
    }

    if(data.files) {
        data.files.forEach(function(f) {
            html += '<tr oncontextmenu="showContextMenu(event, \'file\', '+f.id+', \''+f.name+'\', \''+f.hash+'\')">';
            html += '<td><input type="checkbox" class="item-checkbox" data-type="file" data-id="'+f.id+'" data-hash="'+f.hash+'"></td>';
            html += '<td><a href="./file.php?hash='+f.hash+'" target="_blank"><div class="file-name"><div class="file-icon"><i class="fa fa-file-o"></i></div><span class="name-text">'+f.name+'</span></div></a></td>';
            html += '<td class="file-size">'+formatSize(f.size)+'</td>';
            html += '<td class="file-time">'+f.addtime+'</td>';
            html += '<td><button class="btn-manage-modern" onclick="event.stopPropagation(); manageItem(\'file\', '+f.id+', \''+f.name+'\', 0, \''+f.hash+'\')"><i class="fa fa-cog"></i> 管理</button></td>';
            html += '</tr>';
        });
    }
    
    if(html == '') {
        html = '<tr><td colspan="5" class="empty-state"><i class="fa fa-folder-open-o"></i><p>空文件夹</p></td></tr>';
    }

    $('#file-list-body').html(html);
}

function formatSize(size) {
    if (size < 1024) return size + ' B';
    if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB';
    if (size < 1024 * 1024 * 1024) return (size / 1024 / 1024).toFixed(2) + ' MB';
    return (size / 1024 / 1024 / 1024).toFixed(2) + ' GB';
}

function createFolder() {
    layer.prompt({title: '请输入文件夹名称', offset: 'auto'}, function(value, index, elem){
        $.post('folder_api.php?act=create', {name: value, parent_id: currentFolderId}, function(res) {
            if(res.code == 0) {
                layer.alert('创建成功', {icon: 1}, function(i){
                    layer.close(i);
                    loadFolder(currentFolderId, function() {
                        setTimeout(function(){
                            var $row = $('#file-list-body tr').filter(function() {
                                return $(this).find('td:nth-child(2)').text().trim() === value;
                            });
                            if($row.length > 0) {
                                $row.addClass('new-item-highlight');
                                $('html, body').animate({
                                    scrollTop: $row.offset().top - 100
                                }, 500);
                            }
                        }, 200);
                    });
                });
            } else {
                layer.alert(res.msg, {icon: 2});
            }
            layer.close(index);
        }, 'json');
    });
}

function deleteItem(type, id, hash) {
    var msg = type == 'folder' ? '确定要删除该文件夹及其内容吗？' : '确定要删除该文件吗？';
    layer.confirm(msg, {icon: 3}, function(index){
        if(type == 'folder') {
            $.post('folder_api.php?act=delete', {folder_id: id}, function(res) {
                if(res.code == 0) { 
                    layer.alert('删除成功', {icon: 1}, function(i){
                        layer.close(i);
                        loadFolder(currentFolderId); 
                        $('#context-menu').hide();
                        if (manageLayerIndex) { layer.close(manageLayerIndex); manageLayerIndex = null; }
                    }); 
                } else {
                    layer.alert(res.msg, {icon: 2});
                }
                layer.close(index);
            }, 'json');
        } else {
            var token = $('#csrf_token').val();
            $.post('ajax.php?act=deleteFile', {hash: hash, csrf_token: token}, function(res) {
                if(res.code == 0) { 
                    layer.alert('删除成功', {icon: 1}, function(i){
                        layer.close(i);
                        loadFolder(currentFolderId); 
                        $('#context-menu').hide();
                        if (manageLayerIndex) { layer.close(manageLayerIndex); manageLayerIndex = null; }
                    }); 
                } else {
                    layer.alert(res.msg, {icon: 2});
                }
                layer.close(index);
            }, 'json');
        }
    });
}

function showContextMenu(e, type, id, name, hash) {
    e.preventDefault();
    currentRightClickItem = {type: type, id: id, name: name, hash: hash};
    $('#context-menu').css({
        top: e.pageY + 'px',
        left: e.pageX + 'px'
    }).show();
    
    if (type == 'file') {
        $('#menu-pwd').show();
        $('#menu-copy').show();
    } else {
        $('#menu-pwd').hide();
        $('#menu-copy').hide();
    }
}

function quickAction(action, type, id, name) {
    currentRightClickItem = {type: type, id: id, name: name};
    menuAction(action);
}

function menuAction(action) {
    if(!currentRightClickItem) return;
    var item = currentRightClickItem;
    
    if(action == 'share') {
        if(item.type == 'folder') {
            openShareSettings(item.id);
        } else {
            layer.alert('只有文件夹可以设置分享', {icon: 2});
        }
    } else if(action == 'rename') {
        if(item.type == 'folder') {
            layer.prompt({title: '重命名', value: item.name}, function(value, index){
                $.post('folder_api.php?act=rename', {folder_id: item.id, new_name: value}, function(res){
                    if(res.code == 0) { 
                        layer.alert('成功', {icon: 1}, function(i){
                            layer.close(i);
                            loadFolder(currentFolderId);
                        }); 
                    }
                    else layer.alert(res.msg, {icon: 2});
                    layer.close(index);
                }, 'json');
            });
        } else {
             layer.prompt({title: '重命名文件', value: item.name}, function(value, index){
                $.post('folder_api.php?act=rename_file', {file_id: item.id, new_name: value}, function(res){
                    if(res.code == 0) { 
                        layer.alert('成功', {icon: 1}, function(i){
                            layer.close(i);
                            loadFolder(currentFolderId);
                        }); 
                    }
                    else layer.alert(res.msg, {icon: 2});
                    layer.close(index);
                }, 'json');
            });
        }
    } else if(action == 'password') {
         if(item.type == 'file') {
             $.post('folder_api.php?act=get_password', {file_id: item.id}, function(res){
                 var oldPwdVal = '';
                 if(res.code == 0 && res.password) {
                     oldPwdVal = res.password;
                 }
                 
                 layer.open({
                     type: 1,
                     title: '设置/修改密码',
                     content: '<div style="padding:20px"><input type="text" id="old_pwd" class="form-control" placeholder="原密码(若无留空)" value="'+oldPwdVal+'"><br><input type="password" id="new_pwd" class="form-control" placeholder="新密码(留空则清除)"></div>',
                     btn: ['确定', '取消'],
                     yes: function(index, layero){
                         var oldPwd = $('#old_pwd').val();
                         var newPwd = $('#new_pwd').val();
                         $.post('folder_api.php?act=set_password', {file_id: item.id, password: newPwd, old_password: oldPwd}, function(res){
                             if(res.code == 0) { layer.alert('设置成功', {icon: 1}, function(i){ layer.close(i); layer.close(index); }); }
                             else layer.alert(res.msg, {icon: 2});
                         }, 'json');
                     }
                 });
             }, 'json');
         }
    } else if(action == 'delete') {
        if(item.type == 'folder') deleteItem('folder', item.id);
        else deleteItem('file', item.id, item.hash);
    } else if(action == 'toggle_hide') {
        toggleHide(item.id, null, true);
    } else if(action == 'move' || action == 'copy') {
        openFolderSelector(function(targetId){
            if (action == 'move') {
                 var data = {target_id: targetId};
                 if(item.type == 'folder') data.folder_ids = [item.id];
                 else data.file_ids = [item.id];
                 
                 $.post('folder_api.php?act=move', data, function(res){
                     if(res.code == 0) { 
                         layer.alert('移动成功', {icon: 1}, function(i){
                             layer.close(i);
                             loadFolder(currentFolderId);
                         }); 
                     }
                     else layer.alert(res.msg, {icon: 2});
                 }, 'json');
            } else if (action == 'copy') {
                 if (item.type == 'file') {
                     $.post('folder_api.php?act=batch_copy', {file_ids: [item.id], target_id: targetId}, function(res){
                         if(res.code == 0) { layer.alert('复制成功', {icon: 1}); loadFolder(currentFolderId); }
                         else layer.alert(res.msg, {icon: 2});
                     }, 'json');
                 } else {
                     layer.alert('暂不支持文件夹复制', {icon: 2});
                 }
            }
        });
    }
}

function openFolderSelector(callback) {
    fsSelectedFolderId = null;
    fsCurrentFolderId = 0;
    
    layer.open({
        type: 1,
        skin: 'layer-no-padding',
        title: '选择目标文件夹',
        area: ['300px', '400px'],
        content: $('#folder-selector-tpl').html(),
        btn: ['确定', '取消'],
        success: function(layero, index){
            loadSelectorFolder(0);
        },
        yes: function(index, layero){
            if (fsSelectedFolderId === null) {
                layer.alert('请选择一个文件夹', {icon: 2});
                return;
            }
            callback(fsSelectedFolderId);
            layer.close(index);
        }
    });
}

function loadSelectorFolder(folderId) {
    fsCurrentFolderId = folderId;
    $('#fs-tree').html('<div style="text-align:center;padding:10px;"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
    
    $.get('folder_api.php', {act: 'list', parent_id: folderId}, function(res) {
        if(res.code == 0) {
            var pathStr = '/';
            if (res.path && res.path.length > 0) {
                pathStr = '';
                res.path.forEach(function(p){ pathStr += '/' + p.name; });
            }
            if (res.path && res.path.length > 0) {
                var current = res.path[res.path.length-1];
                fsCurrentParentId = current.parent_id;
            } else {
                fsCurrentParentId = 0;
            }
            
            var $container = $('.layui-layer-content');
            $container.find('#fs-current-path').text(pathStr);
            $container.find('button[onclick*="loadSelectorFolder(fsCurrentParentId)"]').attr('onclick', 'loadSelectorFolder('+fsCurrentParentId+')');

            var html = '';
            html += '<div class="folder-tree-item" onclick="selectFsItem('+folderId+', this)">';
            html += '<i class="fa fa-folder-open"></i> . (当前文件夹)';
            html += '</div>';
            
            if(res.folders) {
                res.folders.forEach(function(f) {
                    html += '<div class="folder-tree-item" onclick="selectFsItem('+f.folder_id+', this)" ondblclick="loadSelectorFolder('+f.folder_id+')">';
                    html += '<i class="fa fa-folder"></i> '+f.name;
                    html += '<button class="btn btn-xs btn-default pull-right" onclick="event.stopPropagation();loadSelectorFolder('+f.folder_id+')">进入</button>';
                    html += '</div>';
                });
            }
            $container.find('#fs-tree').html(html);
        } else {
            $('.layui-layer-content').find('#fs-tree').html('<div class="text-danger">加载失败</div>');
        }
    }, 'json');
}

function selectFsItem(folderId, elem) {
    $('.folder-tree-item').removeClass('selected');
    $(elem).addClass('selected');
    fsSelectedFolderId = folderId;
}

function openShareSettings(folderId) {
    layer.closeAll('page');
    var loadIndex = layer.load(1);
    
    $.post('folder_api.php?act=get_share_info', {folder_id: folderId}, function(res) {
        layer.close(loadIndex);
        if(res.code !== 0) {
            layer.alert(res.msg, {icon: 2});
            return;
        }
        
        var data = res.data;
        var shareUrl = window.location.origin + '/folder.php?key=' + encodeURIComponent(data.share_key);
        
        var html = '<div class="share-settings-modal">';
        html += '<div class="share-settings-scroll">';
        html += '<div class="share-section">';
        html += '<h4><i class="fa fa-link"></i> 分享链接</h4>';
        html += '<div class="share-url-box">';
        html += '<input type="text" id="share_url_input" class="form-control share-url-input" value="' + shareUrl + '" readonly>';
        html += '<button class="btn btn-primary" onclick="copyShareUrl()"><i class="fa fa-copy"></i> 复制</button>';
        html += '</div>';
        html += '</div>';
        
        html += '<div class="share-section">';
        html += '<h4><i class="fa fa-lock"></i> 访问密码</h4>';
        html += '<div class="form-group">';
        html += '<div class="capsule-toggle ' + (data.share_need_pwd ? 'active' : '') + '" id="capsule_toggle">';
        html += '<div class="capsule-switch"></div>';
        html += '<span class="capsule-label">' + (data.share_need_pwd ? '已开启访问密码' : '未开启访问密码') + '</span>';
        html += '</div>';
        html += '<input type="hidden" id="share_need_pwd" value="' + (data.share_need_pwd ? '1' : '0') + '">';
        html += '</div>';
        html += '<div class="pwd-input-area" id="pwd_input_group" style="' + (data.share_need_pwd ? '' : 'display:none;') + '">';
        html += '<div class="pwd-input-header">';
        html += '<i class="fa fa-key"></i>';
        html += '<span>访问密码设置</span>';
        html += '</div>';
        html += '<div class="pwd-input-wrapper">';
        html += '<input type="password" id="share_pwd" class="form-control" placeholder="请输入访问密码" value="' + (data.share_pwd || '') + '">';
        html += '<button type="button" class="pwd-toggle-visible" onclick="togglePwdVisible()" title="显示/隐藏密码">';
        html += '<i class="fa fa-eye" id="pwd_eye_icon"></i>';
        html += '</button>';
        html += '</div>';
        html += '<div class="pwd-hint">';
        html += '<i class="fa fa-info-circle"></i>';
        html += '<span>访问者需要输入此密码才能查看文件夹内容</span>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        
        html += '<div class="share-section">';
        html += '<h4><i class="fa fa-bullhorn"></i> 公告栏</h4>';
        html += '<div class="form-group">';
        html += '<textarea id="share_notice" class="form-control share-notice-textarea" rows="6" placeholder="在此输入公告内容，支持HTML标签">' + escapeHtml(data.share_notice || '') + '</textarea>';
        html += '<p class="help-block">支持HTML标签，如 &lt;b&gt;加粗&lt;/b&gt;、&lt;i&gt;斜体&lt;/i&gt;、&lt;a href=\"...\"&gt;链接&lt;/a&gt; 等</p>';
        html += '</div>';
        html += '</div>';
        
        html += '<div class="share-section share-preview-section">';
        html += '<h4><i class="fa fa-eye"></i> 公告预览</h4>';
        html += '<div id="notice_preview" class="notice-preview-box">' + (data.share_notice || '<span class="text-muted">暂无公告内容</span>') + '</div>';
        html += '</div>';
        
        html += '</div></div>';
        
        var isMobile = window.innerWidth <= 768;
        layer.open({
            type: 1,
            title: '分享设置 - ' + data.name,
            area: isMobile ? ['90%', '80%'] : ['600px', 'auto'],
            maxHeight: isMobile ? '80vh' : '80vh',
            content: html,
            btn: ['保存设置', '取消'],
            btnAlign: isMobile ? 'c' : 'r',
            yes: function(index, layero) {
                var needPwd = parseInt($('#share_need_pwd').val()) || 0;
                var pwd = $('#share_pwd').val().trim();
                var notice = $('#share_notice').val();
                
                if(needPwd && pwd === '') {
                    layer.alert('已开启访问密码，请填写密码', {icon: 2});
                    return;
                }
                
                var saveIndex = layer.load(1);
                $.post('folder_api.php?act=set_share', {
                    folder_id: folderId,
                    share_need_pwd: needPwd,
                    share_pwd: pwd,
                    share_notice: notice
                }, function(saveRes) {
                    layer.close(saveIndex);
                    if(saveRes.code === 0) {
                        layer.alert('保存成功', {icon: 1}, function(i) {
                            layer.close(i);
                            layer.close(index);
                        });
                    } else {
                        layer.alert(saveRes.msg, {icon: 2});
                    }
                }, 'json');
            },
            success: function(layero, index) {
                $('#capsule_toggle').on('click', function() {
                    var $this = $(this);
                    var $hidden = $('#share_need_pwd');
                    var isActive = $this.hasClass('active');
                    
                    if(isActive) {
                        $this.removeClass('active');
                        $this.find('.capsule-label').text('未开启访问密码');
                        $hidden.val('0');
                        $('#pwd_input_group').slideUp(200);
                    } else {
                        $this.addClass('active');
                        $this.find('.capsule-label').text('已开启访问密码');
                        $hidden.val('1');
                        $('#pwd_input_group').slideDown(200);
                    }
                });
                
                $('#share_notice').on('input', function() {
                    var content = $(this).val();
                    if(content.trim() === '') {
                        $('#notice_preview').html('<span class="text-muted">暂无公告内容</span>');
                    } else {
                        $('#notice_preview').html(content);
                    }
                });
            }
        });
    }, 'json');
}

function copyShareUrl() {
    var input = document.getElementById('share_url_input');
    input.select();
    input.setSelectionRange(0, 99999);
    if(document.execCommand('copy')) {
        layer.msg('链接已复制到剪贴板', {icon: 1, time: 1500});
    } else {
        layer.msg('复制失败，请手动复制', {icon: 2, time: 1500});
    }
}

function escapeHtml(text) {
    var div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function togglePwdVisible() {
    var $input = $('#share_pwd');
    var $icon = $('#pwd_eye_icon');
    var currentType = $input.attr('type');
    
    if(currentType === 'password') {
        $input.attr('type', 'text');
        $icon.removeClass('fa-eye').addClass('fa-eye-slash');
    } else {
        $input.attr('type', 'password');
        $icon.removeClass('fa-eye-slash').addClass('fa-eye');
    }
}

function openTransferModal() {
    var isMobile = window.innerWidth <= 768;
    layer.open({
        type: 1,
        title: '转存文件/文件夹',
        area: isMobile ? ['90%', 'auto'] : ['500px', 'auto'],
        content: '<div class="transfer-modal-content">' +
            '<div class="transfer-input-group">' +
            '<label><i class="fa fa-link"></i> 请粘贴文件/文件夹直链或普通链接</label>' +
            '<input type="text" id="transfer_url" class="form-control transfer-url-input" placeholder="例如: https://example.com/file.php?hash=xxx 或 https://example.com/folder.php?key=xxx">' +
            '</div>' +
            '<div id="transfer_preview" class="transfer-preview"></div>' +
            '<div id="transfer_password_section" class="transfer-password-section">' +
            '<div class="transfer-password-header"><i class="fa fa-lock"></i> 该文件/文件夹已设置访问密码</div>' +
            '<input type="password" id="transfer_password" class="form-control" placeholder="请输入访问密码">' +
            '</div>' +
            '<div id="transfer_progress" class="transfer-progress">' +
            '<div class="transfer-progress-bar"><div id="transfer_progress_fill" class="transfer-progress-fill"></div></div>' +
            '<div id="transfer_progress_text" class="transfer-progress-text">准备中...</div>' +
            '</div>' +
            '</div>',
        btn: ['转存到网盘', '取消'],
        btnAlign: 'c',
        yes: function(index, layero) {
            var url = $('#transfer_url').val().trim();
            var password = $('#transfer_password').val().trim();
            
            if(!url) {
                layer.msg('请输入链接', {icon: 2});
                return;
            }
            
            performTransfer(url, password, index);
        },
        success: function(layero, index) {
            $('#transfer_url').on('input', function() {
                var url = $(this).val().trim();
                if(url.length > 10) {
                    previewTransfer(url);
                } else {
                    $('#transfer_preview').removeClass('show').html('');
                    $('#transfer_password_section').removeClass('show');
                }
            });
        }
    });
}

function previewTransfer(url) {
    var loadIndex = layer.load(1);
    
    $.post('folder_api.php?act=transfer_preview', {url: url}, function(res) {
        layer.close(loadIndex);
        
        if(res.code === 0) {
            var iconClass = res.type === 'folder' ? 'folder' : 'file';
            var icon = res.type === 'folder' ? 'fa-folder' : 'fa-file';
            var html = '<div class="transfer-preview-header"><i class="fa fa-info-circle"></i> 待转存内容</div>' +
                '<div class="transfer-item-info">' +
                '<div class="transfer-item-icon ' + iconClass + '"><i class="fa ' + icon + '"></i></div>' +
                '<div class="transfer-item-details">' +
                '<div class="transfer-item-name">' + escapeHtml(res.name) + '</div>' +
                '<div class="transfer-item-meta">';
            
            if(res.type === 'file') {
                html += formatSize(res.size);
            } else {
                html += '文件夹';
                if(res.folder_count) html += ' · ' + res.folder_count + ' 个子文件夹';
                if(res.file_count) html += ' · ' + res.file_count + ' 个文件';
            }
            
            html += '</div></div></div>';
            
            $('#transfer_preview').html(html).addClass('show');
            
            if(res.need_password) {
                $('#transfer_password_section').addClass('show');
            } else {
                $('#transfer_password_section').removeClass('show');
            }
        } else {
            layer.msg(res.msg, {icon: 2});
            $('#transfer_preview').removeClass('show').html('');
        }
    }, 'json').fail(function() {
        layer.close(loadIndex);
        layer.msg('预览失败，请检查链接是否正确', {icon: 2});
    });
}

function performTransfer(url, password, layerIndex) {
    var loadIndex = layer.load(1, {shade: [0.3, '#000']});
    $('#transfer_progress').addClass('show');
    $('#transfer_progress_fill').css('width', '10%');
    $('#transfer_progress_text').text('正在转存...');
    
    $.post('folder_api.php?act=transfer', {
        url: url,
        password: password,
        target_folder: currentFolderId,
        csrf_token: $('#csrf_token').val()
    }, function(res) {
        layer.close(loadIndex);
        $('#transfer_progress').removeClass('show');
        
        if(res.code === 0) {
            var successCount = res.success_count || 1;
            var failCount = res.fail_count || 0;
            var msg = successCount > 0 ? '成功转存 ' + successCount + ' 个项目' : '';
            if(failCount > 0) msg += (msg ? '，失败 ' + failCount + ' 个' : '失败 ' + failCount + ' 个');
            
            layer.alert(msg, {icon: 1}, function(i) {
                layer.close(i);
                layer.close(layerIndex);
                loadFolder(currentFolderId);
            });
        } else {
            layer.alert(res.msg, {icon: 2});
        }
    }, 'json').fail(function() {
        layer.close(loadIndex);
        $('#transfer_progress').removeClass('show');
        layer.alert('转存失败，请检查链接或密码是否正确', {icon: 2});
    });
}
</script>
<?php include SYSTEM_ROOT.'footer.php';?>
