<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>查看数据 - {{ $table }}</title>
    <link rel="stylesheet" href="{{ asset('CmsProUi/component/pear/css/pear.css') }}">
    <link rel="stylesheet" href="{{ asset('CmsProUi/font-awesome/4.7.0/css/font-awesome.min.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/admin.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/variables.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/reset.css') }}">
    <style>
        .layui-btn+.layui-btn { margin-left: 0; }
    </style>
</head>
<body class="pear-container">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" action="">
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="field" lay-filter="SearchField">
                            <option value="">选择字段</option>
                            @foreach($columns as $col)
                            <option value="{{ $col['Field'] }}">{{ $col['Field'] }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <input type="text" name="keyword" placeholder="搜索内容" class="layui-input">
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn layui-btn-md" lay-submit lay-filter="table-query">
                            <i class="layui-icon layui-icon-search"></i> 搜索
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <div class="layui-card">
        <div class="layui-card-body">
            <table id="dataTable" lay-filter="dataTable"></table>
        </div>
    </div>

    @verbatim
    <script type="text/html" id="data-toolbar">
        <button class="layui-btn layui-btn-sm" lay-event="Add">
            <i class="layui-icon layui-icon-add-1"></i> 添加
        </button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="batchRemove">
            <i class="layui-icon layui-icon-delete"></i> 删除
        </button>
    </script>

    <script type="text/html" id="data-operate">
        <button class="layui-btn layui-btn-xs" lay-event="copy"><i class="fa fa-copy"></i></button>
        <button class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i></button>
        <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="remove"><i class="layui-icon layui-icon-delete"></i></button>
    </script>
    @endverbatim

    <script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
    <script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
    <script>
        layui.use(['table', 'form', 'jquery'], function() {
            var table = layui.table;
            var form = layui.form;
            var $ = layui.jquery;

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                statusCode: {
                    401: function() {
                        layer.msg('登录已过期，请重新登录', {icon: 2, time: 1500}, function() {
                            window.location.href = '/admin/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                        });
                    }
                }
            });

            var tableName = '{{ $table }}';
            var API = '/api/admin/database/' + tableName;

            var cols = [[
                { type: 'checkbox' },
                @foreach($columns as $col)
                @php
                    $fieldName = $col['Field'];
                    $isShort = in_array($fieldName, ['id', 'status', 'sort', 'type', 'visible', 'parent_id']);
                    $isTime = in_array($fieldName, ['create_time', 'update_time', 'created_at', 'updated_at', 'deleted_at', 'last_login_at']);
                    if ($isShort) {
                        $width = 80;
                        $align = 'center';
                    } elseif ($isTime) {
                        $width = 170;
                        $align = 'center';
                    } else {
                        $width = 0;
                        $align = 'left';
                    }
                @endphp
                @if($width > 0)
                { field: '{{ $fieldName }}', title: '{{ $col["Comment"] ?: $fieldName }}', width: {{ $width }}, align: '{{ $align }}' },
                @else
                { field: '{{ $fieldName }}', title: '{{ $col["Comment"] ?: $fieldName }}', minWidth: 120, align: '{{ $align }}' },
                @endif
                @endforeach
                { title: '操作', toolbar: '#data-operate', align: 'center', width: 120, fixed: 'right' }
            ]];

            table.render({
                elem: '#dataTable',
                url: API + '/check',
                page: { layout: ['prev', 'page', 'next', 'skip', 'count', 'limit'], limit: 20, limits: [20, 50, 100, 300, 500] },
                cols: cols,
                toolbar: '#data-toolbar',
                defaultToolbar: [{ title: '刷新', layEvent: 'refresh', icon: 'layui-icon-refresh' }, 'filter', 'print', 'exports'],
                parseData: function(res) {
                    var data = res.data || {};
                    return {
                        "code": res.code,
                        "msg": res.message,
                        "count": data.pagination ? data.pagination.total : 0,
                        "data": data.items || []
                    };
                }
            });

            form.on('submit(table-query)', function(data) {
                table.reload('dataTable', { where: data.field, page: { curr: 1 } });
                return false;
            });

            table.on('toolbar(dataTable)', function(obj) {
                if (obj.event === 'Add') { addRow(); }
                else if (obj.event === 'refresh') { table.reload('dataTable'); }
                else if (obj.event === 'batchRemove') { batchRemove(obj); }
            });

            table.on('tool(dataTable)', function(obj) {
                if (obj.event === 'remove') { removeRow(obj); }
                else if (obj.event === 'copy') { copyRow(obj); }
                else if (obj.event === 'edit') { editRow(obj); }
            });

            function addRow() {
                layer.open({
                    type: 2, maxmin: true,
                    title: '添加数据 - ' + tableName,
                    shade: 0.1, area: ['90%', '90%'],
                    content: '/admin/database/table-add/' + tableName,
                    end: function() { table.reload('dataTable'); }
                });
            }

            function editRow(obj) {
                layer.open({
                    type: 2, maxmin: true,
                    title: '编辑数据 - ID:' + obj.data.id,
                    shade: 0.1, area: ['90%', '90%'],
                    content: '/admin/database/table-edit/' + tableName,
                    success: function(layero, index) {
                        var iframe = layero.find('iframe').contents();
                        @foreach($columns as $col)
                        iframe.find('#{{ $col["Field"] }}').val(obj.data['{{ $col["Field"] }}']);
                        @endforeach
                    },
                    end: function() { table.reload('dataTable'); }
                });
            }

            function copyRow(obj) {
                layer.open({
                    type: 2, maxmin: true,
                    title: '复制数据 - ID:' + obj.data.id,
                    shade: 0.1, area: ['90%', '90%'],
                    content: '/admin/database/table-copy/' + tableName,
                    success: function(layero, index) {
                        var iframe = layero.find('iframe').contents();
                        @foreach($columns as $col)
                        @if($col['Field'] !== 'id')
                        iframe.find('#{{ $col["Field"] }}').val(obj.data['{{ $col["Field"] }}']);
                        @endif
                        @endforeach
                    },
                    end: function() { table.reload('dataTable'); }
                });
            }

            function removeRow(obj) {
                layer.confirm('确定要删除这条数据吗？', {
                    icon: 3, title: '操作提示', btn: ['确定', '取消']
                }, function(index) {
                    layer.close(index);
                    $.post(API + '/table-delete', { id: obj.data.id, _token: '{{ csrf_token() }}' }, function(res) {
                        if (res.code === 0) { layer.msg(res.message, {icon:1}); obj.del(); }
                        else { layer.msg(res.message, {icon:2}); }
                    });
                });
            }

            function batchRemove(obj) {
                var checkData = table.checkStatus('dataTable').data;
                if (checkData.length === 0) { layer.msg('请选择要删除的数据', {icon:3}); return; }
                var ids = checkData.map(function(d) { return d.id; });
                layer.confirm('确定要删除选中的 <b>' + ids.length + '</b> 条数据吗？', {
                    icon: 3, title: '操作提示', btn: ['确定', '取消']
                }, function(index) {
                    layer.close(index);
                    $.ajax({
                        url: API + '/table-delete',
                        type: 'POST',
                        data: JSON.stringify({ ids: ids, _token: '{{ csrf_token() }}' }),
                        contentType: 'application/json',
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                        success: function(res) {
                            if (res.code === 0) { layer.msg(res.message, {icon:1}); table.reload('dataTable'); }
                            else { layer.msg(res.message, {icon:2}); }
                        }
                    });
                });
            }
        });
    </script>
</body>
</html>
