<!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">
            <div class="layui-form">
                <div class="layui-inline">
                    <div class="layui-input-inline" style="width:80px;line-height:38px;">插入位置</div>
                    <div class="layui-input-inline">
                        <select name="after_field" lay-filter="AfterField">
                            <option value="">表头</option>
                            @foreach($columns as $col)
                            <option value="{{ $col['Field'] }}">{{ $col['Field'] }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <button class="layui-btn layui-btn-sm" id="submitFields">
                            <i class="layui-icon layui-icon-add-1"></i> 提交
                        </button>
                    </div>
                </div>
            </div>
            <div class="layui-form">
                <table class="layui-table" id="fieldsTable">
                    <thead>
                        <tr>
                            <th width="200">字段名</th>
                            <th width="150">类型</th>
                            <th width="100">长度/值</th>
                            <th>默认值</th>
                            <th>备注</th>
                            <th width="200">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="text" name="name[]" class="layui-input field-name"></td>
                            <td>
                                <select name="type[]" lay-filter="FieldType">
                                    <option value="int">INT</option>
                                    <option value="varchar">VARCHAR</option>
                                    <option value="text">TEXT</option>
                                    <option value="longtext">LONGTEXT</option>
                                    <option value="date">DATE</option>
                                    <option value="datetime">DATETIME</option>
                                    <option value="timestamp">TIMESTAMP</option>
                                    <option value="decimal">DECIMAL</option>
                                    <option value="json">JSON</option>
                                    <option value="bigint">BIGINT</option>
                                    <option value="tinyint">TINYINT</option>
                                </select>
                            </td>
                            <td><input type="text" name="length[]" class="layui-input field-length"></td>
                            <td>
                                <div class="layui-input-inline" style="width:120px;">
                                    <select name="default[]" lay-filter="DefaultValue">
                                        <option value="NONE">无</option>
                                        <option value="USER_DEFINED">自定义：</option>
                                        <option value="NULL">NULL</option>
                                    </select>
                                </div>
                            </td>
                            <td><input type="text" name="remark[]" class="layui-input field-remark"></td>
                            <td>
                                <button class="layui-btn layui-btn-xs add-row" data-type="down"><i class="fa fa-level-down"></i> 添加</button>
                                <button class="layui-btn layui-btn-xs move-row" data-type="up"><i class="fa fa-long-arrow-up"></i></button>
                                <button class="layui-btn layui-btn-xs move-row" data-type="down"><i class="fa fa-long-arrow-down"></i></button>
                                <button class="layui-btn layui-btn-danger layui-btn-xs del-row"><i class="fa fa-close"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <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 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;

            $('#submitFields').on('click', function() {
                var fields = [];
                var defaultValIndex = 0;
                $('#fieldsTable tbody tr').each(function() {
                    var $tr = $(this);
                    var name = $tr.find('.field-name').val();
                    var type = $tr.find('select[name="type[]"]').val();
                    var length = $tr.find('.field-length').val();
                    var defaultType = $tr.find('select[name="default[]"]').val();
                    var remark = $tr.find('.field-remark').val();
                    var defaultVal = '';

                    if (defaultType === 'USER_DEFINED') {
                        defaultVal = $tr.find('.default-val-input').val() || '';
                    }

                    if (name && type) {
                        fields.push({
                            name: name,
                            type: type,
                            length: length,
                            default: defaultType,
                            default_val: defaultVal,
                            remark: remark || ''
                        });
                    }
                });

                if (fields.length === 0) {
                    layer.msg('请至少添加一个字段', {icon:2});
                    return;
                }

                var afterField = $('select[name="after_field"]').val();

                $.ajax({
                    url: API + '/add-fields',
                    type: 'POST',
                    data: JSON.stringify({ fields: fields, after_field: afterField, _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});
                            setTimeout(function() {
                                var idx = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(idx);
                            }, 500);
                        } else {
                            layer.alert(res.message, {title: '操作提示', icon: 2});
                        }
                    }
                });
            });

            $(document).on('click', '.add-row', function() {
                var $tr = $(this).closest('tr');
                var $newTr = $tr.clone(true);
                $newTr.find('input').val('');
                $newTr.find('select').prop('selectedIndex', 0);
                $newTr.find('.default-val-input').remove();
                if ($(this).data('type') === 'up') { $tr.before($newTr); }
                else { $tr.after($newTr); }
                form.render('select');
            });

            $(document).on('click', '.move-row', function() {
                var $tr = $(this).closest('tr');
                if ($(this).data('type') === 'up') {
                    var $prev = $tr.prev('tr');
                    if ($prev.length) $tr.insertBefore($prev);
                } else {
                    var $next = $tr.next('tr');
                    if ($next.length) $tr.insertAfter($next);
                }
            });

            $(document).on('click', '.del-row', function() {
                var $tbody = $(this).closest('tbody');
                if ($tbody.find('tr').length <= 1) {
                    layer.msg('至少保留一行', {icon:5});
                    return;
                }
                $(this).closest('tr').remove();
            });

            form.on('select(DefaultValue)', function(data) {
                var $tr = $(data.elem).closest('tr');
                $tr.find('.default-val-input').remove();
                if (data.value === 'USER_DEFINED') {
                    var $input = $('<input type="text" class="layui-input default-val-input" name="default_val[]" placeholder="默认值" style="width:100px;display:inline-block;">');
                    $(data.elem).closest('.layui-input-inline').after($input);
                }
            });
        });
    </script>
</body>
</html>
