layui.define(['layer', 'gtable', 'upload'], function (exports) {
    const layer = layui.layer,
        table = layui.gtable;
    let driverTable;
    const mainTemplate = `
        <div class="flex-column conn-manager">
            <div class="flex-row tool-bar layui-form" style="justify-content: end;">
                <div class="flex-row layui-form-item" style="margin-bottom: 0;margin-top: 10px">
                    <div class="layui-input-inline" style="width: auto;">
                        <a class="layui-btn layui-btn-primary layui-border-blue" id="uploadDriver"
                         title="从本地上传数据库驱动" 
                         style="border: 0; height: 20px; line-height: unset; text-decoration-line: underline;">上传本地驱动</a>
                    </div>
                </div>
            </div>
            <div class="conn-content">
                <table class="layui-hide" id="driver-table" lay-filter="driver-table"></table>
            </div>
        </div>
        <script type="text/html" id="toolbar-driver">
            {{# var disabled = d.inner ? 'layui-disabled' : '' }}
            <a class="layui-btn layui-btn-danger layui-btn-xs {{disabled}}" lay-event="del{{disabled}}">删除</a>
        </script>
    `;

    // 默认配置
    const config = {
        elem: '',
        connType: 'JDBC',
        area:['600px', '600px'],
        yes: () => {
        },
        done: () => {
        }
    }

    const Driver = function () {
        this.config = $.extend(true, {}, config);
    }

    /**
     * 初始化组件
     * @param opt
     */
    Driver.prototype.init = function (opt) {
        this.config = $.extend({}, config, opt);
        let _this = this;
        const _config = this.config;
        $(_config.elem).on('click', function () {
            layer.open({
                title: '数据库驱动',
                type: 1,
                area: _config.area,
                btn: ['确定', '取消'],
                shadeClose: true,
                content: mainTemplate,
                success: function (layerObj, index) {
                    renderTable();
                    uploadEventListener(_this);
                },
                yes: function (index) {
                    let {data} = table.checkStatus('driver-table')
                    _config.yes && _config.yes(data[0]);
                    layer.close(index);
                }
            });
        })

        _config.done && _config.done();
    }

    Driver.prototype.getDriverById = async function (id) {
        let result;
        await Util.get(`/business/drivers/${id}`).then(res => {
            if (res.flag) {
                result = res.data;
            }
        }).catch(() => layer.msg('驱动信息获取失败', {icon: 5}));
        return result;
    };

    /**
     * 渲染表格
     */
    function renderTable() {
        driverTable = table.init({
            id: 'driver-table',
            url: `${ctx}/business/drivers`,
            height: 'full-495',
            toolbar: false,
            page: false,
            method: 'get',
            cols: [[
                {type: 'radio', field: '', title: '', width: ''},
                {field: 'id', title: '主键', hide: true},
                {field: 'name', title: '驱动名', width: 300},
                {field: 'version', title: '驱动版本'},
                {title: '操作', width: 70, align: 'right', toolbar: '#toolbar-driver'}
            ]],
            done: res=>{}
        })
        table.on('tool(driver-table)', function ({event, data}) {
            if (event === 'del') {
                const c_index = layer.confirm('是否删除该驱动程序', {title: '确认删除'}, function () {
                    Util.send(`/business/drivers/${data.id}`, {}, 'delete').then(res => {
                        if (res.flag) {
                            driverTable.reload();
                        } else {
                            layer.alert(res.msg, {icon: 5});
                        }
                    }).finally(() => layer.close(c_index))
                })
            }
        });
        return driverTable;
    }

    /**
     * 上传事件监听
     */
    function uploadEventListener() {
        let load_index;
        layui.upload.render({
            elem: '#uploadDriver', //绑定元素
            url: `${ctx}/business/drivers/upload`, //上传接口
            accept: 'file',
            acceptMime: '.jar',
            exts: 'jar',
            before: function () {
                load_index = layer.load();
            },
            done: function (res) {
                layer.close(load_index);
                //上传完毕回调
                if (res.flag) {
                    driverTable.reload();
                } else {
                    showErrorMsg(res.msg)
                }
            },
            error: function () {
                layer.close(load_index);
                //请求异常回调
                layer.alert('上传失败', {icon: 5})
            }
        })
    }

    exports('driver', new Driver())
});