layui.use(['table', 'form', 'layer', 'laytpl'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var laytpl = layui.laytpl;
    var $ = layui.$;
    
    // 初始化表格
    table.render({
        elem: '#device-table',
        url: '/api/devices/registered',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        toolbar: '#tableToolbar',
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: [[
            {type: 'checkbox'},
            {field: 'uid', title: '设备UID', width: 180},
            {field: 'device_model', title: '设备型号', width: 120},
            {field: 'device_type', title: '设备类型', width: 120},
            {field: 'license_code', title: '授权码', width: 180},
            {field: 'license_type', title: '授权类型', width: 100, templet: function(d){
                var types = {
                    'time': '时间授权',
                    'count': '次数授权',
                    'permanent': '永久授权'
                };
                return types[d.license_type] || '-';
            }},
            {field: 'status', title: '状态', width: 100, templet: function(d){
                if(d.status === 'active') return '<span class="layui-badge layui-bg-green">正常</span>';
                if(d.status === 'expired') return '<span class="layui-badge layui-bg-orange">已过期</span>';
                return '<span class="layui-badge layui-bg-gray">未激活</span>';
            }},
            {field: 'start_count', title: '启动次数', width: 100, templet: function(d){
                if(d.license_type === 'count') {
                    return d.start_count + ' / ' + d.max_uses;
                }
                return d.start_count || 0;
            }},
            {field: 'last_active_at', title: '最后活跃', width: 160, templet: function(d){
                return d.last_active_at ? new Date(d.last_active_at).toLocaleString() : '-';
            }},
            {fixed: 'right', title: '操作', toolbar: '#tableRowBar', width: 250}
        ]],
        page: true,
        parseData: function(res) {
            if (res.code === 401) {
                window.location.href = '/login';
                return;
            }
            return res;
        }
    });
    
    // 表格工具栏事件
    table.on('toolbar(device-table)', function(obj){
        switch(obj.event){
            case 'refresh':
                table.reload('device-table');
                break;
        }
    });
    
    // 行工具栏事件
    table.on('tool(device-table)', function(obj){
        var data = obj.data;
        
        switch(obj.event){
            case 'view':
                // 使用laytpl渲染设备详情
                laytpl(document.getElementById('deviceDetailTpl').innerHTML).render(data, function(html){
                    layer.open({
                        type: 1,
                        title: '设备详情',
                        area: ['600px', '600px'],
                        content: html
                    });
                });
                break;
            case 'bind':
                layer.prompt({
                    formType: 0,
                    value: '',
                    title: '请输入授权码',
                    area: ['300px', '150px']
                }, function(value, index, elem){
                    // 绑定授权码
                    fetch('/api/devices/' + data.uid + '/license', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        credentials: 'include',
                        body: JSON.stringify({
                            license_code: value
                        })
                    })
                    .then(response => response.json())
                    .then(result => {
                        if(result.error) {
                            layer.msg(result.error);
                            return;
                        }
                        layer.msg('绑定成功');
                        table.reload('device-table');
                        layer.close(index);
                    })
                    .catch(error => {
                        layer.msg('绑定失败：' + error.message);
                    });
                });
                break;
            case 'logs':
                layer.open({
                    type: 2,
                    title: '设备日志',
                    area: ['800px', '600px'],
                    content: '/admin/device-logs?uid=' + data.uid
                });
                break;
            case 'revoke':
                layer.confirm('确定要撤销该设备的授权吗？', function(index){
                    fetch('/api/devices/' + data.uid + '/license', {
                        method: 'DELETE',
                        credentials: 'include'
                    })
                    .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;
        }
    });
    
    // 搜索表单提交
    form.on('submit(search)', function(data){
        table.reload('device-table', {
            where: data.field,
            page: {
                curr: 1
            }
        });
        return false;
    });
}); 