layui.define(['jquery', 'element', 'form', 'table', 'yaml', 'common'], function (exports) {
    "use strict";

    var MOD_NAME = 'request';
    var $ = layui.jquery;
    var table = layui.table;
    var element = layui.element;
    var common = layui.common;
    var form = layui.form;
    var request = new function () {

        this.getAdminServerUrl = function () {
            return layui.data('server').url;
        };

        this.getTokenQueryString = function () {
            var server = layui.data('server');
            if (server.accessToken == null) {
                location.href = server.login == null ? "login.html" : server.login;
            }
            return server.accessToken;
        };

        this.http = function (options) {
            var defaults = {
                type: 'get',
                headers: {},
                data: {},
                dataType: null,
                async: true,
                cache: false,
                sendToken: true, // 是否发送accessToken，默认发送。
                beforeSend: null,
                success: null,
                complete: null,
                loading: false
            };

            var o = $.extend({}, defaults, options);
            var loading = o.loading ? layer.load(2, {shade: [0.3, '#333']}): '';
            $.ajax({
                url: this.getAdminServerUrl() + o.url,
                type: o.type,
                headers: {'Content-Type': o.contentType},
                data: o.data,
                dataType: o.dataType,
                async: o.async,
                beforeSend: function (request) {
                    if (o.sendToken) {
                        o.beforeSend && o.beforeSend();
                        var server = layui.data('server');
                        if (server.accessToken == null) {
                            location.href = (server.login == null ? "login.html" : server.login);
                        }
                        request.setRequestHeader(server.accessToken.name, server.accessToken.value);
                    }
                },
                success: function (res) {
                    o.loading? layer.close(loading): '';
                    o.success && o.success(res);
                },
                complete: function () {
                    o.complete && o.complete();
                },
                error: function (error) {
                    o.error && o.error(error);
                    request.redirectToLogin(error.responseJSON);
                }
            });
        };

        this.httpGet = function (uri, success, sendToken, async) {
            this.http({
                url: uri,
                success: success,
                sendToken: sendToken,
                async: async
            })
        };

        this.redirectToLogin = function (error) {
            if (parseInt(error.code) === 401 && !error.success) {
                layer.open({
                    time: 1500, // 自动关闭所需毫秒
                    content: error.msg,
                    end: function () {
                        layui.data('user', null); // 清空本地存储
                        var server = layui.data('server');
                        top.location.href = (server.login == null ? "login.html" : server.login);
                    }
                });
            }
        };

        this.tableRender = function (options) {
            var load = layer.load();
            var defaults = {
                elem: '#table',
                page: true,
                skin: 'line',
                where: null,
                height: 'full-148',
                toolbar: '#toolbar',
                text: {none: '暂无数据'},
                defaultToolbar: [{
                    title: '刷新',
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                },'filter', 'print', 'exports'],
                sendToken: true
            };
            var o = $.extend({}, defaults, options);
            var accessToken;
            if (o.sendToken) {
                accessToken = this.getTokenQueryString();
            }
            var token_name = accessToken.name;
            var token_value = accessToken.value;
            var headers = {};
            headers[token_name] = token_value;
            table.render({
                elem: o.elem, // 对应table的id
                headers: headers,
                error: function (error) {
                    request.redirectToLogin(error.responseJSON);
                },
                url: this.getAdminServerUrl() + o.url,
                where: o.where,
                page: o.page, // 分页参数可以自定义
                cols: o.cols, // 列表示
                skin: o.skin, // 表格样式
                toolbar: o.toolbar, // 表格头部工具栏 可定义左上角和右上角工具栏,一般用于左上角配置
                text: o.text,
                defaultToolbar: o.defaultToolbar, // 自由配置头部工具栏右侧的图标按钮
                done: function() {
                    o.done;
                    var permissions = layui.data('server').permissions;
                    $("[permission]").each(function() {
                        var permission = $(this).attr("permission");
                        if ($.inArray(permission, permissions) >= 0) {
                            $(this).show();
                        }
                    });
                }
            });
            //this.checkPermission();
            layer.close(load);
        };

        this.tableRefresh = function (param, deep) {
            table.reload('table', param, deep);
        };

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

        this.dictSelect = function(id, dict_type, dict_val, is_select) {
            var select = $("#" + id);
            select.empty();
            this.httpGet('/system/dictItem/v1/type/' + dict_type, function(result) {
                if (result.success) {
                    is_select = is_select == null ? true : is_select;
                    if (is_select) {
                        select.append("<option value =''>请选择</option>");
                        $.each(result.data, function(k, v) {
                            var selected = v.value === dict_val ? "selected" : '';
                            select.append("<option value ='" + v.value + "' "+ selected +">" + v.label + "</option>");
                        });
                    } else {
                        $.each(result.data, function(k, v) {
                            if (v.value === dict_val) {
                                select.text(v.label);
                                return false;
                            }
                        });
                    }
                }
                form.render();
            });
        };

        this.regionalSelect = function(id, regional_id, is_select) {
            var select = $("#" + id);
            select.empty();
            this.httpGet('/system/regional/v1/' + regional_id, function(result) {
                if (result.success) {
                    is_select = is_select == null ? true : is_select;
                    if (is_select) {
                        select.append("<option value =''>请选择</option>");
                        var selected = result.data.id === regional_id ? "selected" : '';
                        select.append("<option value ='" + result.data.id + "' "+ selected +">" + result.data.name + "</option>");
                    } else {
                        if (result.data.id === regional_id) {
                            select.text(result.data.name);
                            return false;
                        }
                    }
                }
                form.render();
            });
        }
        this.regionalChildSelect = function(id, parent_id, regional_val,is_select) {
            var select = $("#" + id);
            select.empty();
            this.httpGet('/system/regional/v1/parentId/' + parent_id, function(result) {
                if (result.success) {
                    is_select = is_select == null ? true : is_select;
                    if (is_select) {
                        select.append("<option value =''>请选择</option>");
                        $.each(result.data, function(k, v) {
                            var selected = v.id === regional_val ? "selected" : '';
                            select.append("<option value ='" + v.id + "' "+ selected +">" + v.name + "</option>");
                        });
                    } else {
                        $.each(result.data, function(k, v) {
                            if (v.id === regional_val) {
                                select.text(v.name);
                                return false;
                            }
                        });
                    }
                }
                form.render();
            });
        }

        this.checkPermission = function() {
            var permissions = layui.data('server').permissions;
            $("[permission]").each(function() {
                var permission = $(this).attr("permission");
                if ($.inArray(permission, permissions) >= 0) {
                    $(this).show();
                }
            });
        };

        // 表单数据回显
        this.formVal = function (uri) {
            var id = this.getQueryString("id");
            this.http({
                url: uri + "/" + id,
                dataType: 'json',
                contentType: 'application/json',
                type: 'get',
                success: function (result) {
                    if (result.success) {
                        form.val("edit", result.data);
                    } else {
                        layer.msg(result.msg, {icon: 2, time: 1000});
                    }
                }
            })
        };

        this.formSave = function (url) {
            form.on('submit(save)', function (data) {
                // 转换
                data.field.enable = data.field.enable == '1' ? true : false;
                request.http({
                    url: url,
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'post',
                    success: function (result) {
                        if (result.success) {
                            layer.msg(result.msg, {
                                    icon: 1,
                                    time: 1000,
                                    area: ['100px', '65px'],
                                    content: "保存成功"
                                }, function () {
                                    parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页
                                    parent.layui.table.reload("table");
                                });
                        } else {
                            layer.msg(result.msg,
                                {
                                    icon: 2,
                                    time: 1000,
                                    area: ['220px', '70px']
                                }
                            );
                        }
                    }
                });
                return false;
            });
        };

        /**
         * 获取URL路径参数
         * @param name
         * @returns {string}
         */
        this.getQueryString = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r !== null)
                return unescape(r[2]);
            return "";
        };

        /**
         * 获取当前表格选中字段
         * @param obj 表格回调参数
         * @param field 要获取的字段
         * */
        this.checkField = function (obj, field) {
            var data = table.checkStatus(obj.config.id).data;
            if (data.length === 0) {
                return "";
            }
            var ids = "";
            for (let i = 0; i < data.length; i++) {
                ids += data[i][field] + ",";
            }
            ids = ids.substr(0, ids.length - 1);
            return ids;
        };

        /**
         * 提交 json 数据
         * @param data 提交数据
         * @param href 提交接口
         * @param table 刷新父级表
         *
         * */
        this.submit = function (data, href, table, callback) {
            $.ajax({
                url: href,
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: callback != null ? callback(result) : function (result) {
                    if (result.success) {
                        layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页
                            parent.layui.table.reload(table);
                        });
                    } else {
                        layer.msg(result.msg, {icon: 2, time: 1000});
                    }
                }
            })
        }
    };
    exports(MOD_NAME, request);
});
