layui.define(['jquery', 'layer'], function (exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        /** war包 如果有项目名后面填写项目名 没有项目名就去除（没有项目名需要保留斜杠）*/
            // requestUrl = window.location.origin + '/archives/';
        host = window.location.host,
        // host = '192.168.0.114:9091',
        requestUrl = 'http://' + host + '/';

    let ajax = function (method, type, data, async, callback) {
        var loading = layer.load(0, {shade: [0.3, '#000']});
        let headers = {
            accessToken: (layui.data('auth').data ? layui.data('auth').data.accessToken : '') || ''
        }
        let dataObj = data
        // post请求 传参不是fromdata 则使用Json传值

        let processData = true // 告诉jquery不要处理发送的数据
        let contentType = false
        switch (type) {
            case "GET":
                headers['Content-Type'] = 'application/json;charset=utf-8;'
                break;
            case "POST":
                if (data instanceof FormData) {
                    // headers['Content-Type'] = 'application/x-www-form-urlencoded'
                    processData = false
                    contentType = false
                } else {
                    data = JSON.stringify(data)
                    headers['Content-Type'] = 'application/json;charset=utf-8;'
                }
                break;
            case "DELETE":
                headers['Content-Type'] = 'application/x-www-form-urlencoded'
                break;
        }
        // if (type == 'POST' && !(data instanceof FormData)) {
        //     data = JSON.stringify(data)
        // }
        // // 非delete设置请求头为json
        // if (type != 'DELETE' && !(data instanceof FormData)) {
        //     headers['Content-Type'] = 'application/json;charset=utf-8;'
        // }
        //
        // if (type == 'POST' && data instanceof FormData){
        //     headers['Content-Type'] = 'application/x-www-form-urlencoded'
        // }

        $.ajax({
            url: requestUrl + method,
            type: type,
            processData: processData,
            contentType: contentType,
            dataType: 'json',
            //async:false 同步 true异步
            async: async,
            headers: headers,
            data: data,
            success: function (res) {
                layer.close(loading);
                if (res.code === 200) {
                    callback(res)
                } else if (res.code == 303) {
                    // 过期需要刷新Token
                    refreshToken(method, type, dataObj, async, callback)
                } else if (res.code == 1200) {
                    callback(res)
                } else {
                    layer.msg(res.msg, {
                        icon: 2,
                    }, function () {
                        if (res.code === 302) {
                            // 非法Token 跳转到登录页面
                            window.location.href = 'login.html'
                        } else if (res.code == 1002) {
                            // refreshToken已经过期
                            // 删除过期的token
                            layui.data('auth', null);
                            window.location.href = 'login.html'
                        }
                    });
                    callback(res)
                }
            },
            error: function (e) {
                layer.msg('请求出错' + e, {
                    icon: 2
                })
            }
        });
    }

    let login = function (data) {
        ajax('system/auth/login', 'POST', data, true, res => {
            if (res.code == 200) {
                layui.data('auth', {
                    key: 'data',
                    value: res.data
                })
                layer.msg('登录成功', {
                    icon: 1
                }, function () {
                    window.location = 'index.html';
                });
            }
        })
    }


    let loginByBase64 = function (base64) {
        ajax('system/auth/loginByBase64', 'GET', {
            base64: base64
        }, true, res => {
            if (res.code == 200) {
                layui.data('auth', {
                    key: 'data',
                    value: res.data
                })
                window.location = 'index.html'
                // layer.msg('登录成功', {
                //     icon: 1
                // }, function () {
                //     window.location = 'index.html';
                // });
            }
        })
    }

    let refreshToken = function (method, type, data, async, callback) {
        ajax('system/auth/refreshToken', 'GET', {
            refreshToken: (layui.data('auth').data ? layui.data('auth').data.refreshToken : null) || null
        }, false, res => {
            if (res.code == 200) {
                layui.data('auth', {
                    key: 'data',
                    value: res.data
                })
                // 重新获取token后 再次发送请求
                ajax(method, type, data, async, callback)
            }
        })
    }

    var http = {
        get: function (method, data, async, callback) {
            ajax(method, 'GET', data, async, callback);
        },
        post: function (method, data, async, callback) {
            ajax(method, 'POST', data, async, callback);
        },
        delete: function (method, data, async, callback) {
            ajax(method, 'DELETE', data, async, callback)
        },
        getRoleButton: function (menuId) {
            // 显示在头部的按钮
            let header = ['add', 'download', 'import', 'batchDel', 'foldAll', 'unfoldAll', 'clearThirtyOut', 'clearAll', 'expostA', 'a', 'advancedSearch']
            // 显示在行里的按钮
            let row = ['show', 'update', 'delete', 'export', 'up', 'down', 'setRole', 'resetPassword', 'files', 'borrowing', 'enclosure', 'secondary', 'register']
            http.get('system/auth/getLoginButtons', {menuId: menuId}, false, function (res) {
                let headerHtml = '<div class="layui-btn-container">'
                let rowHtml = ''
                res.data.forEach(function (item) {
                    if (header.includes(item.href)) {
                        headerHtml += '<button class="layui-btn layui-btn-sm" lay-event="' + item.href + '">' + item.title + '</button>'
                    }
                    if (row.includes(item.href)) {
                        if (item.href == 'delete') {
                            rowHtml += '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="' + item.href + '">' + item.title + '</a>'
                        } else {
                            rowHtml += '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="' + item.href + '">' + item.title + '</a>'
                        }
                    }
                })
                headerHtml += '</div>'
                $("#toolbar").append(headerHtml)
                $("#operating").append(rowHtml)
            })
        },
        login: function (data) {
            login(data)
        },
        loginByBase64: function (base64){
            loginByBase64(base64)
        },
        host: host,
        requestUrl: requestUrl
    };
    //输出接口
    exports('http', http);
});
