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

    var MOD_NAME = 'request';
    var $ = layui.jquery;
    var table = layui.table;
    var popup = layui.popup;
    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']}) : '';
            //o.headers.array1=["Content-Type", o.contentType];
            o.headers["Content-Type"] = o.contentType;
            $.ajax({
                url: this.getAdminServerUrl() + o.url,
                type: o.type,
                headers: o.headers,
                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.tableRender1 = function (options) {
            var load = layer.load();
            var defaults = {
                elem: '#table1',
                page: true,
                skin: 'line',
                where: null,
                height: 'full-50',
                toolbar: '#toolbar',
                totalRow: false,
                limit : 10,
                limits : [10, 20, 30, 40, 50],
                text: {none: '<img style="width:260px;border:0;max-width:100%;vertical-align:middle;" src="/clfzjtg/admin/images/table-none.png"><div style="color:#7f8997;line-height:20px;padding-top:8px;">暂无数据</div>'},
                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, // 表格样式
                limit: o.limit,
                limits: o.limits,
                toolbar: o.toolbar, // 表格头部工具栏 可定义左上角和右上角工具栏,一般用于左上角配置
                text: o.text,
                defaultToolbar: o.defaultToolbar, // 自由配置头部工具栏右侧的图标按钮
                totalRow: o.totalRow,
                done: function(row, curr, count) {
                    o.done && o.done(row, curr, count);
                    request.checkPermission();
                }
            });
            layer.close(load);
        };

        this.tableRender = function (options) {
            var load = layer.load();
            var defaults = {
                elem: '#table',
                page: true,
                skin: 'line',
                where: null,
                height: 'full-50',
                toolbar: '#toolbar',
                totalRow: false,
                limit : 10,
                limits : [10, 20, 30, 40, 50],
                text: {none: '<img style="width:260px;border:0;max-width:100%;vertical-align:middle;" src="/clfzjtg/admin/images/table-none.png"><div style="color:#7f8997;line-height:20px;padding-top:8px;">暂无数据</div>'},
                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, // 表格样式
                limit: o.limit,
                limits: o.limits,
                toolbar: o.toolbar, // 表格头部工具栏 可定义左上角和右上角工具栏,一般用于左上角配置
                text: o.text,
                defaultToolbar: o.defaultToolbar, // 自由配置头部工具栏右侧的图标按钮
                totalRow: o.totalRow,
                done: function(row, curr, count) {
                    o.done && o.done(row, curr, count);
                    request.checkPermission();
                }
            });
            layer.close(load);
        };

        // 初始化审批
        this.initApproval = function(list) {
            var html = '';
            $.each(list, function(index, item) {
                html += '<tr>' +
                    '<td colspan="4">'+ (item.nodeName!=null?item.nodeName:'-') +'</td>' +
                    '<td colspan="6">'+ (item.approver!=null?item.approver:'-') +'</td>' +
                    '<td colspan="5">'+ (item.approvalRemark!=null?item.approvalRemark:'-') +'</td>' +
                    '<td colspan="4">'+ (item.approvalStatus!=null?(parseInt(item.approvalStatus) === 1?
                        '<span class="layui-badge-dot success"></span>通过':
                        '<span class="layui-badge-dot failure"></span>驳回'):'-') +'</td>' +
                    '<td colspan="5">'+ (item.approvalTime!=null?item.approvalTime:'-') +'</td>' +
                    '</tr>';
            });
            $('#approvalHistory').append(html);
        };


        // 初始化审批
        this.initApproval1 = function(list) {
            var html = '';
            $.each(list, function(index, item) {
                html += '<tr>' +
                    '<td colspan="4">'+ (item.nodeName!=null?item.nodeName:'-') +'</td>' +
                    '<td colspan="6">'+ (item.approver!=null?item.approver:'-') +'</td>' +
                    '<td colspan="5">'+ (item.approvalRemark!=null?item.approvalRemark:'-') +'</td>' +
                    '<td colspan="4">'+ (item.approvalStatus!=null?(parseInt(item.approvalStatus) === 1?
                        '<span class="layui-badge-dot success"></span>通过':
                        '<span class="layui-badge-dot failure"></span>驳回'):'-') +'</td>' +
                    '<td colspan="5">'+ (item.approvalTime!=null?item.approvalTime:'-') +'</td>' +
                    '</tr>';
            });
            $('#approvalHistory1').append(html);
        };

        // 初始化状态
        this.initStatus = function(status) {
            status = parseInt(status);
            if (status === 0) {
                $('#ywzt').html('<span class="cool-txt-failure">暂存</span>');
            } else if (status === 1) {
                $('#ywzt').html('<span class="cool-txt-warning">已申请</span>');
            } else if (status === 2) {
                $('#ywzt').html('<span class="cool-txt-warning">审核中</span>');
            } else if (status === 3) {
                $('#ywzt').html('<span class="cool-txt-success">已完成</span>');
            } else if (status === 4) {
                $('#ywzt').html('<span class="cool-txt-failure">已退回</span>');
            }
        };

        // PDF查看
        this.look = function(level, path) {
            if (!path) {
                popup.failure('暂未生成文件');
                return false;
            }
            if (isNaN(level)) {
                popup.failure('参数异常，请填写数字');
                return false;
            }
            var relativePath = '';
            for (var i = 0; i < level; i++) {
                relativePath += "../";
            }
            var index = layer.open({
                type: 1,
                title: "pdf查看",
                maxmin: true,
                content: "<iframe src='"+ relativePath +"component/pdf/web/viewer.html?file="+request.getAdminServerUrl() +'/upload/'+ path
                    + "' style='width:100%;height:99%'></iframe>"
            });
            layer.full(index);
        };

        // 文件下载
        this.download = function(path) {
            if (!path) {
                popup.failure('暂未生成文件');
                return false;
            }
            var a = document.createElement('a');
            a.href = request.getAdminServerUrl() +'/upload/'+ path;
            document.body.appendChild(a);
            a.download = new Date().getTime().toString();
            a.click();
            document.body.removeChild(a);
        };

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

        //格式化金额，s:金额； n:保留位数
        this.formatAmount = function(s, n) {
            n = n > 0 && n <= 20 ? n : 2;
            s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
            var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
            var t = "";
            for (var i = 0; i < l.length; i++) {
                t += l[i];
            }
            return t.split("").reverse().join("") + "." + r;
        };

        this.convertAmount = function (Num) {
            // 判断如果传递进来的不是字符的话转换为字符
            if (typeof Num == "number") {
                Num = new String(Num)
            }
            Num = Num.replace(/,/g, "") //替换tomoney()中的“,”
            Num = Num.replace(/ /g, "") //替换tomoney()中的空格
            Num = Num.replace(/￥/g, "") //替换掉可能出现的￥字符
            if (isNaN(Num)) { //验证输入的字符是否为数字
                return "请检查金额";
            }
            //字符处理完毕后开始转换，采用前后两部分分别转换
            var part = String(Num).split(".");
            var newchar = "";
            //小数点前进行转化
            for (var i = part[0].length - 1; i >= 0; i--) {
                if (part[0].length > 10) {
                    return "金额超过拾亿";
                }
                var tmpnewchar = "";
                var perchar = part[0].charAt(i);
                switch (perchar) {
                    case "0":
                        tmpnewchar = "零" + tmpnewchar;
                        break;
                    case "1":
                        tmpnewchar = "壹" + tmpnewchar;
                        break;
                    case "2":
                        tmpnewchar = "贰" + tmpnewchar;
                        break;
                    case "3":
                        tmpnewchar = "叁" + tmpnewchar;
                        break;
                    case "4":
                        tmpnewchar = "肆" + tmpnewchar;
                        break;
                    case "5":
                        tmpnewchar = "伍" + tmpnewchar;
                        break;
                    case "6":
                        tmpnewchar = "陆" + tmpnewchar;
                        break;
                    case "7":
                        tmpnewchar = "柒" + tmpnewchar;
                        break;
                    case "8":
                        tmpnewchar = "捌" + tmpnewchar;
                        break;
                    case "9":
                        tmpnewchar = "玖" + tmpnewchar;
                        break;
                }
                switch (part[0].length - i - 1) {
                    case 0:
                        tmpnewchar = tmpnewchar + "元";
                        break;
                    case 1:
                        if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
                        break;
                    case 2:
                        if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
                        break;
                    case 3:
                        if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
                        break;
                    case 4:
                        tmpnewchar = tmpnewchar + "万";
                        break;
                    case 5:
                        if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
                        break;
                    case 6:
                        if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
                        break;
                    case 7:
                        if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
                        break;
                    case 8:
                        tmpnewchar = tmpnewchar + "亿";
                        break;
                    case 9:
                        tmpnewchar = tmpnewchar + "拾";
                        break;
                }
                var newchar = tmpnewchar + newchar;
            }
            //小数点之后进行转化
            if (Num.indexOf(".") != -1) {
                if (part[1].length > 2) {
                    // alert("小数点之后只能保留两位,系统将自动截断");
                    part[1] = part[1].substr(0, 2)
                }
                for (i = 0; i < part[1].length; i++) {
                    tmpnewchar = ""
                    perchar = part[1].charAt(i)
                    switch (perchar) {
                        case "0":
                            tmpnewchar = "零" + tmpnewchar;
                            break;
                        case "1":
                            tmpnewchar = "壹" + tmpnewchar;
                            break;
                        case "2":
                            tmpnewchar = "贰" + tmpnewchar;
                            break;
                        case "3":
                            tmpnewchar = "叁" + tmpnewchar;
                            break;
                        case "4":
                            tmpnewchar = "肆" + tmpnewchar;
                            break;
                        case "5":
                            tmpnewchar = "伍" + tmpnewchar;
                            break;
                        case "6":
                            tmpnewchar = "陆" + tmpnewchar;
                            break;
                        case "7":
                            tmpnewchar = "柒" + tmpnewchar;
                            break;
                        case "8":
                            tmpnewchar = "捌" + tmpnewchar;
                            break;
                        case "9":
                            tmpnewchar = "玖" + tmpnewchar;
                            break;
                    }
                    if (i == 0) tmpnewchar = tmpnewchar + "角";
                    if (i == 1) tmpnewchar = tmpnewchar + "分";
                    newchar = newchar + tmpnewchar;
                }
            }
            //替换所有无用汉字
            while (newchar.search("零零") != -1)
                newchar = newchar.replace("零零", "零");
            newchar = newchar.replace("零亿", "亿");
            newchar = newchar.replace("亿万", "亿");
            newchar = newchar.replace("零万", "万");
            newchar = newchar.replace("零元", "元");
            newchar = newchar.replace("零角", "");
            newchar = newchar.replace("零分", "");
            if (newchar.charAt(newchar.length - 1) == "元") {
                newchar = newchar + "整"
            }
            return newchar;
        };

        // 表单数据回显
        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 decodeURI(r[2]);
            }
            return "";
        };

        /**
         * 根据抵押状态返回main
         * @param name
         * @returns {string}
         */
        this.getDyztMain = function (dyzt) {
            if (dyzt == 1) {
                window.location.href = 'main.html';
            }else{
                window.location.href = 'ybmain.html';
            }
        };

        /**
         * 根据抵押状态返回main
         * @param name
         * @returns {string}
         */
        this.getSpDyztMain = function () {
          parent.window.location.href = 'main.html';
        };

        /**
         * 获取当前表格选中字段
         * @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 (var 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);
});
