layui.use(['table', 'form', 'layer'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.$;
    
    // 初始化表格
    table.render({
        elem: '#device-table',
        url: '/api/devices/models',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        toolbar: '#tableToolbar',
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: [[
            {type: 'checkbox'},
            {field: 'ID', hide: true},
            {field: 'model_name', title: '设备型号', width: 180},
            {field: 'device_type', title: '设备类型', width: 120},
            {field: 'company', title: '所属公司', width: 150},
            {field: 'remark', title: '备注说明'},
            {field: 'device_count', title: '设备数量', width: 100},
            {field: 'status', title: '状态', width: 100, templet: function(d){
                if(d.status === 'active') return '<span class="layui-badge layui-bg-green">启用</span>';
                return '<span class="layui-badge layui-bg-gray">禁用</span>';
            }},
            {fixed: 'right', title: '操作', toolbar: '#tableRowBar', width: 180}
        ]],
        page: true,
        parseData: function(res) {
            if (res.code === 401) {
                window.location.href = '/login';
                return;
            }
            return res;
        }
    });
    
    // 表格工具栏事件
    table.on('toolbar(device-table)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        
        switch(obj.event){
            case 'refresh':
                table.reload('device-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);
                    fetch('/api/devices/models/batch', {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + localStorage.getItem('token')
                        },
                        body: JSON.stringify({ids: ids})
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.error) {
                            layer.msg(result.error);
                            return;
                        }
                        layer.msg('批量删除成功');
                        table.reload('device-table');
                    })
                    .catch(error => {
                        layer.msg('批量删除失败：' + error.message);
                    });
                    layer.close(index);
                });
                break;
        }
    });
    
    // 行工具栏事件
    table.on('tool(device-table)', function(obj){
        var data = obj.data;
        
        switch(obj.event){
            case 'edit':
                layer.open({
                    type: 1,
                    title: '编辑设备型号',
                    area: ['500px', '400px'],
                    content: $('#deviceFormTpl').html(),
                    success: function(){
                        form.val('deviceForm', {
                            id: data.ID,
                            model_name: data.model_name,
                            device_type: data.device_type,
                            company: data.company,
                            status: data.status || 'active',
                            remark: data.remark
                        });
                        form.render();
                    }
                });
                break;
            case 'del':
                layer.confirm('确定删除该设备型号吗？', function(index){
                    fetch('/api/devices/models/' + 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;
        }
    });
    
    // 搜索表单提交
    form.on('submit(search)', function(data){
        table.reload('device-table', {
            where: data.field,
            page: {
                curr: 1
            }
        });
        return false;
    });
    
    // 添加设备型号按钮点击事件
    $('#add-device').on('click', function(){
        layer.open({
            type: 1,
            title: '添加设备型号',
            area: ['500px', '400px'],
            content: $('#deviceFormTpl').html(),
            success: function(){
                form.render();
            }
        });
    });
    
    // 设备型号表单提交
    form.on('submit(deviceSubmit)', function(data){
        // 构造请求数据
        const submitData = {
            model_name: data.field.model_name,
            device_type: data.field.device_type,
            company: data.field.company,
            status: data.field.status,
            remark: data.field.remark
        };

        // 确定请求URL和方法
        const url = data.field.id ? 
            `/api/devices/models/${data.field.id}` : 
            '/api/devices/models';
        const method = data.field.id ? 'PUT' : 'POST';
        
        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            body: JSON.stringify(submitData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.error) {
                layer.msg(result.error);
                return;
            }
            layer.closeAll('page');
            layer.msg(data.field.id ? '更新成功' : '添加成功');
            table.reload('device-table');
        })
        .catch(error => {
            layer.msg((data.field.id ? '更新' : '添加') + '失败：' + error.message);
        });
        
        return false;
    });
});
