layui.use(['upload', 'table', 'layer', 'form'], function(){
    var upload = layui.upload;
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var $ = layui.$;
    
    // 获取设备型号
    var deviceModel = decodeURIComponent(location.search.match(/model=([^&]+)/)[1]);
    
    // 初始化表格
    table.render({
        elem: '#file-table',
        url: '/api/uploads/device/' + deviceModel,
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        toolbar: '#tableToolbar',
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: [[
            {type: 'checkbox'},
            {field: 'file_name', title: '文件名', width: 200},
            {field: 'version', title: '版本', width: 100},
            {field: 'file_type', title: '类型', width: 100, templet: function(d){
                if(d.is_update) return '<span class="layui-badge layui-bg-blue">更新</span>';
                return '<span class="layui-badge layui-bg-gray">普通</span>';
            }},
            {field: 'file_size', title: '大小', width: 120, templet: function(d){
                return formatFileSize(d.file_size);
            }},
            {field: 'downloads', title: '下载次数', width: 100},
            {field: 'description', title: '描述'},
            {field: 'created_at', title: '上传时间', width: 160, templet: function(d){
                return new Date(d.created_at).toLocaleString();
            }},
            {fixed: 'right', title: '操作', toolbar: '#tableRowBar', width: 180}
        ]],
        page: true,
        parseData: function(res) {
            if (res.code === 401) {
                window.location.href = '/login';
                return;
            }
            return res;
        }
    });
    
    // 上传普通文件
    upload.render({
        elem: '#uploadFile',
        url: '/api/uploads',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        data: {
            device_model: deviceModel,
            is_update: false
        },
        accept: 'file',
        before: function(obj){
            layer.load();
        },
        done: function(res){
            layer.closeAll('loading');
            if(res.error){
                layer.msg(res.error);
                return;
            }
            layer.msg('上传成功');
            table.reload('file-table');
        },
        error: function(){
            layer.closeAll('loading');
            layer.msg('上传失败');
        }
    });
    
    // 上传更新文件
    upload.render({
        elem: '#uploadUpdate',
        url: '/api/uploads',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        data: {
            device_model: deviceModel,
            is_update: true
        },
        accept: 'file',
        before: function(obj){
            // 弹出版本信息输入框
            layer.prompt({
                formType: 0,
                title: '请输入版本号',
                area: ['300px', '150px']
            }, function(value, index, elem){
                this.field.version = value;
                layer.close(index);
                layer.load();
            });
        },
        done: function(res){
            layer.closeAll('loading');
            if(res.error){
                layer.msg(res.error);
                return;
            }
            layer.msg('上传成功');
            table.reload('file-table');
        },
        error: function(){
            layer.closeAll('loading');
            layer.msg('上传失败');
        }
    });
    
    // 表格工具栏事件
    table.on('toolbar(file-table)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        
        switch(obj.event){
            case 'refresh':
                table.reload('file-table');
                break;
            case 'batchDel':
                var data = checkStatus.data;
                if(data.length === 0){
                    layer.msg('请选择要删除的文件');
                    return;
                }
                layer.confirm('确定删除选中的文件吗？', function(index){
                    var ids = data.map(item => item.id);
                    Promise.all(ids.map(id => 
                        fetch('/api/uploads/' + id, {
                            method: 'DELETE',
                            headers: {
                                'Authorization': 'Bearer ' + localStorage.getItem('token')
                            }
                        }).then(response => response.json())
                    ))
                    .then(() => {
                        layer.msg('批量删除成功');
                        table.reload('file-table');
                    })
                    .catch(error => {
                        layer.msg('批量删除失败：' + error.message);
                    });
                    layer.close(index);
                });
                break;
        }
    });
    
    // 行工具栏事件
    table.on('tool(file-table)', function(obj){
        var data = obj.data;
        
        switch(obj.event){
            case 'download':
                window.location.href = '/api/uploads/' + data.id;
                break;
            case 'del':
                layer.confirm('确定删除该文件吗？', function(index){
                    fetch('/api/uploads/' + data.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('删除成功');
                        obj.del();
                    })
                    .catch(error => {
                        layer.msg('删除失败：' + error.message);
                    });
                    layer.close(index);
                });
                break;
        }
    });
    
    // 格式化文件大小
    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];
    }
}); 