layui.use(['upload', 'element', 'layer'], function(){
    var upload = layui.upload;
    var element = layui.element;
    var layer = layui.layer;
    var $ = layui.$;

    // 普通文件上传
    upload.render({
        elem: '#fileUpload',
        url: '/api/uploads',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        data: {
            device_uid: function() {
                return $('#deviceUID').val();
            },
            description: function() {
                return $('#description').val();
            }
        },
        accept: 'file',
        before: function(obj) {
            layer.load();
        },
        done: function(res) {
            layer.closeAll('loading');
            if (res.error) {
                layer.msg(res.error);
                return;
            }
            layer.msg('上传成功');
            // 刷新文件列表
            loadFileList();
        },
        error: function() {
            layer.closeAll('loading');
            layer.msg('上传失败');
        }
    });

    // 分片上传
    upload.render({
        elem: '#chunkUpload',
        url: '/api/uploads/chunk',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        data: {
            deviceUID: function() {
                return $('#deviceUID').val();
            }
        },
        accept: 'file',
        size: 1024 * 1024 * 2, // 每片2MB
        chunked: true,
        chunkSize: 1024 * 1024 * 2,
        before: function(obj) {
            layer.load();
        },
        progress: function(n) {
            var percent = n + '%';
            element.progress('uploadProgress', percent);
        },
        done: function(res) {
            layer.closeAll('loading');
            if (res.error) {
                layer.msg(res.error);
                return;
            }
            // 如果所有分片都上传完成，开始合并
            if (res.completed) {
                mergeChunks(res.fileHash);
            } else {
                layer.msg('分片上传成功');
            }
        },
        error: function() {
            layer.closeAll('loading');
            layer.msg('上传失败');
        }
    });

    // 合并分片
    function mergeChunks(fileHash) {
        fetch('/api/uploads/merge', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token'),
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'fileHash=' + fileHash
        })
        .then(response => response.json())
        .then(result => {
            if (result.error) {
                layer.msg(result.error);
                return;
            }
            layer.msg('文件合并成功');
            // 刷新文件列表
            loadFileList();
        })
        .catch(error => {
            layer.msg('文件合并失败：' + error.message);
        });
    }

    // 加载文件列表
    function loadFileList() {
        var deviceUID = $('#deviceUID').val();
        if (!deviceUID) return;

        fetch('/api/uploads/device/' + deviceUID, {
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        })
        .then(response => response.json())
        .then(result => {
            if (result.error) {
                layer.msg(result.error);
                return;
            }
            renderFileList(result);
        })
        .catch(error => {
            layer.msg('加载文件列表失败：' + error.message);
        });
    }

    // 渲染文件列表
    function renderFileList(files) {
        var html = '';
        files.forEach(file => {
            html += `
                <tr>
                    <td>${file.fileName}</td>
                    <td>${formatFileSize(file.fileSize)}</td>
                    <td>${file.fileType}</td>
                    <td>${formatTime(file.createdAt)}</td>
                    <td>
                        <a href="javascript:;" class="layui-btn layui-btn-xs" onclick="downloadFile(${file.id})">下载</a>
                        <a href="javascript:;" class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteFile(${file.id})">删除</a>
                    </td>
                </tr>
            `;
        });
        $('#fileList').html(html);
    }

    // 格式化文件大小
    function formatFileSize(size) {
        var units = ['B', 'KB', 'MB', 'GB', 'TB'];
        var index = 0;
        while (size >= 1024 && index < units.length - 1) {
            size /= 1024;
            index++;
        }
        return size.toFixed(2) + ' ' + units[index];
    }

    // 格式化时间
    function formatTime(time) {
        return new Date(time).toLocaleString();
    }

    // 下载文件
    window.downloadFile = function(id) {
        window.location.href = '/api/uploads/' + id;
    };

    // 删除文件
    window.deleteFile = function(id) {
        layer.confirm('确定删除该文件吗？', function(index) {
            fetch('/api/uploads/' + id, {
                method: 'DELETE',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            })
            .then(response => response.json())
            .then(result => {
                if (result.error) {
                    layer.msg(result.error);
                    return;
                }
                layer.msg('删除成功');
                loadFileList();
            })
            .catch(error => {
                layer.msg('删除失败：' + error.message);
            });
            layer.close(index);
        });
    };

    // 初始加载文件列表
    loadFileList();
}); 