
layui.define(['jquery'], function (exports) {
    var jQuery = layui.jquery,
        $ = layui.jquery;
    var utils = {
        //获取url的参数值
        getUrlParam: function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        },
        //把name/value的数组转为obj对象
        arrayToObj: function(array) {
            var result = {};
            for (var i = 0; i < array.length; i++) {
                var field = array[i];
                if (field.name in result) {
                    result[field.name] += ',' + field.value;
                } else {
                    result[field.name] = field.value;
                }
            }
            return result;
        },
        //更新url参数
        updateURIParamsForKey: function(url, key, value) {
            var r = url;
            if (r != null && r != 'undefined' && r != "") {
                value = encodeURIComponent(value);
                var reg = new RegExp("(^|)" + key + "=([^&]*)(|$)");
                var tmp = key + "=" + value;
                if (url.match(reg) != null) {
                    r = url.replace(eval(reg), tmp);
                } else {
                    if (url.match("[\?]")) {
                        r = url + "&" + tmp;
                    } else {
                        r = url + "?" + tmp;
                    }
                }
            }
            return r;
        },
        //更新url参数
        updateURIParamsForJson: function (url, data) {
            var r = url;
            var tempArr = [];
            for (var i in data) {
                var key = encodeURIComponent(i);
                var value = encodeURIComponent(data[i]);
                if (data[i] != null || data[i] != undefined)
                    tempArr.push(key + '=' + value);
            }
            r = tempArr.join('&');
            if (!r) return url;
            if (url.match("[\?]")) {
                r = url + "&" + r;
            } else {
                r = url + "?" + r;
            }
            return r;
        },
        /*
         * 获取url参数
         */
        getRequest: function() {
            var request = undefined;
            var strHref = location.href;
            var intPos = strHref.indexOf("?");
            if (intPos > -1) {
                var strRight = strHref.substr(intPos + 1);
                var arrTmp = strRight.split("&");
                request = {};
                for (var i = 0; i < arrTmp.length; i++) {
                    var arrTemp = arrTmp[i].split("=");
                    request[arrTemp[0]] = arrTemp[1];
                }
            }
            return request;
        },
        NewGuid: function() {
            var s4 = function() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); };
            return (s4() + s4() + "" + s4() + "" + s4() + "" + s4() + "" + s4() + s4() + s4()).toUpperCase();
        },
        /*
        *格式化JSON格式日期
        *格式"yyyy-MM-dd hh:mm:ss.S"
        */
        formatJsonDate: function(jsondate, format) {
            var datetime = "";
            if (!jsondate) {
                return "";
            }
            jsondate = jsondate + "";
            if (/^\/Date[(].+[)]\/$/.test(jsondate)) {
                // \/date(13456789098665)\/
                jsondate = jsondate.replace("/Date(", "").replace(")/", "");
                //UNIX时间戳加上时区
                if (jsondate.indexOf("+") > -1) {
                    jsondate = jsondate.substring(0, jsondate.indexOf("+"));
                } else if (jsondate.indexOf("-") > -1) {
                    jsondate = jsondate.substring(0, jsondate.indexOf("-"));
                }
                datetime = new Date(parseInt(jsondate, 10));
            } else {
                //常规时间
                //如果不存在毫秒
                ///////////////////////////////////////////////////////////////////
                if (jsondate.indexOf(".") < 0) {
                    jsondate += ".0";
                }
                jsondate = jsondate.replace(/\//g, "-");
                jsondate = jsondate.replace(" ", "T");
                jsondate += "+08:00";
                datetime = new Date(jsondate);
            }
            if (!format) format = "yyyy-MM-dd hh:mm:ss";
            return datetime.Format(format);
            ///////////////////////////////////////////////////////////////////
        },
        //获取JSON格式日期的时间戳
        getTimeStamp: function(jsondate) {
            var datetime = "";
            if (!jsondate) {
                return "";
            }
            jsondate = jsondate + "";
            if (/^\/Date[(].+[)]\/$/.test(jsondate)) {
                jsondate = jsondate.replace("/Date(", "").replace(")/", "");
                if (jsondate.indexOf("+") > -1) {
                    jsondate = jsondate.substring(0, jsondate.indexOf("+"));
                } else if (jsondate.indexOf("-") > -1) {
                    jsondate = jsondate.substring(0, jsondate.indexOf("-"));
                }
                datetime = new Date(parseInt(jsondate, 10));
            } else {
                //时间戳
                if (/^\d{13}$/.test(jsondate)) {
                    return jsondate;
                } else {
                    //常规时间
                    //如果不存在毫秒
                    if (jsondate.indexOf(".") < 0) {
                        jsondate += ".0";
                    }
                    jsondate = jsondate.replace(/\//g, "-");
                    jsondate = jsondate.replace(" ", "T");
                    jsondate += "+08:00";
                    datetime = new Date(jsondate);
                }
            }
            return datetime.getTime();
        },
        zip: function(jsonObj) {
            if (!jsonObj) return jsonObj;
            if (jsonObj instanceof String) {
                return encodeURIComponent(jsonObj);
            } else {
                return encodeURIComponent(JSON.stringify(jsonObj));
            }
        },
        unzip: function(jsonStr) {
            if (!jsonStr) return jsonStr;
            return eval("(" + decodeURIComponent(jsonStr) + ")");
        },
        formatImgUrl: function(url) {
            if (url && url.indexOf) {
                if (url.indexOf("data:image") == 0) { //以data开头为base64图片
                    return url;
                } else {
                    if (url.substring(0, 1) == "/") {
                        return gp.server.url.substring(0, gp.server.url.length - 1) + url;
                    } else {
                        return url;
                    }
                }
            }
        },
        /*
        * file转base编码，并压缩
        * file
        * 用法如下
            utils.FileToBase64(file, function(base64) {
                
            },0,0,1.0);
        */
        FileToBase64: function(file, fn, maxWidth, maxHeight, zipRatio) {
            if (!zipRatio) zipRatio = 0.5;
            //利用html5转base64
            if ("FileReader" in window) {
                var reader = new FileReader();
                var mask = new Maskwin();
                mask.show();
                reader.onload = function(e) {
                    mask.hide();
                    if (maxWidth || maxHeight) {
                        utils.AutoResizeImage(this.result, maxWidth | 0, maxHeight | 0, fn, zipRatio);
                    } else {
                        fn(this.result);
                    }
                };
                reader.readAsDataURL(file);
            } else {
                alert("没有:FileReader");
            }
        },
        /*
        * url图像压缩
        * url:文件路径
        * maxWidth:最大图像宽度，0为auto
        * maxHeight:最大图像高度，0为auto
        * fn(base64):压缩完成后回调，返回base64编码
        * 用法如下
        * 
            utils.ImageUrlToBase64(url, 0, 0, function (zipbase64) {
                
            });
        */
        ImageUrlToBase64: function (url, maxWidth, maxHeight, fn) {
            utils.AutoResizeImage(url, maxWidth, maxHeight, fn);
        },
        /*
        * base64图像压缩
        * base64:base64编码
        * maxWidth:最大图像宽度，0为auto
        * maxHeight:最大图像高度，0为auto
        * fn(base64):压缩完成后回调，返回base64编码
        * 压缩比率
        * 用法如下
            utils.AutoResizeImage(base64, 0, 0, function (zipbase64) {
                
            });
        */
        AutoResizeImage: function(base64, maxWidth, maxHeight, fn, zipRatio) {
            //开始压缩图片
            if (!zipRatio) zipRatio = 0.2;
            var img = new Image();
            var mask = new Maskwin();
            mask.show();
            img.crossOrigin = "Anonymous";
            img.onload = function() {
                mask.hide();
                //获取当前最合适的图像比率
                var hRatio;
                var wRatio;
                var Ratio = 1;
                var w = img.width;
                var h = img.height;
                var left = 0;
                var top = 0;
                wRatio = maxWidth / w;
                hRatio = maxHeight / h;

                /******按照比例缩放******/

                //计算缩放比例
                if (maxWidth == 0 && maxHeight == 0) {
                    Ratio = 1;
                } else if (maxWidth == 0) { //
                    if (hRatio < 1) Ratio = hRatio;
                } else if (maxHeight == 0) {
                    if (wRatio < 1) Ratio = wRatio;
                } else if (maxWidth > 0 && maxHeight > 0) {
                    //两者取最大值作为比例
                    if (maxWidth > maxHeight) {
                        if (wRatio < 1) Ratio = wRatio;
                    } else {
                        if (hRatio < 1) Ratio = hRatio;
                    }
                }

                //按照比例缩小图片
                if (Ratio > 0 && Ratio < 1) {
                    w = w * Ratio;
                    h = h * Ratio;
                }

                //canvas清屏
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext("2d");
                ctx.clearRect(0, 0, canvas.width, canvas.height);

                //重置canvans宽高
                canvas.width = w;
                canvas.height = h;

                img.width = w;
                img.height = h;

                //原图比例缩小
                ctx.drawImage(img, 0, 0, img.width, img.height); // 将图像绘制到canvas上
                var zipbase64 = canvas.toDataURL('image/jpeg', zipRatio); //输出base64

                /******按照比例缩放结束******/

                /******获取居中位置*******/

                if (maxWidth > 0 && maxHeight > 0) {

                    //canvas清屏
                    canvas = document.createElement('canvas');
                    ctx = canvas.getContext("2d");
                    ctx.clearRect(0, 0, canvas.width, canvas.height);

                    //计算宽度偏移量
                    if (maxWidth > 0 && maxWidth < w) {
                        left = (w - maxWidth) / 2;
                        //如果最大宽度小于实际宽度，重置canvans宽
                        canvas.width = maxWidth;
                    } else {
                        //否则不变
                        canvas.width = w;
                    }
                    //计算高度偏移量
                    if (maxHeight > 0 && maxHeight < h) {
                        top = (h - maxHeight) / 2;
                        //如果最大高度小于实际高度，，重置canvans高
                        canvas.height = maxHeight;
                    } else {
                        canvas.height = h;
                    }
                    img.width = w;
                    img.height = h;
                    ctx.drawImage(img, 0 - left, 0 - top, img.width, img.height); // 将图像绘制到canvas上
                    zipbase64 = canvas.toDataURL('image/jpeg'); //输出base64
                }

                /******获取居中位置结束*******/

                fn(zipbase64, img.width, img.height);
            };
            img.src = base64;
            if (img.complete || img.complete === undefined) {
                img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
                img.src = base64;
            }
        }
    }

    //加载菜单
    $.fn.extend({
        loadMenus: function (moduleid) {
            moduleid = layui.utils.getRequest().id;
            var dom = $(this);
            AjaxGet("/api/Auth/LoadAuthorizedMenus?id=" + moduleid,
                null,
                function(json) {
                    var obj = json.data;
                    var sb = '';
                    $.each(obj,
                        function() {
                            var element = this;
                            sb += ("<button " +
                                " data-type='" +
                                element.DomId +
                                "' " +
                                " class='layui-btn layui-btn-small " +
                                element.Class +
                                "' " +
                                element.Attr +
                                ">");
                            if (element.Icon != null && element.Icon != '') {
                                sb += ("<i class='layui-icon " + element.Icon + "'></i>");
                            }
                            sb += (element.Name + "</button>");
                        });
                    dom.html(sb);
                },
                true,
                false);
        }
    });
    exports('utils', utils);
});


/* 
* jQuery Ajax调用封装
* url:			调用地址
* data:			可选参数,表示Ajax调用参数
* onSuccess:	可选参数,成功回调函数,函数签名为  function(data), data参数为调用结果
* modal:		可选参数,是否作为模态对话框显示，默认为true
* async:		可选参数,是否异步调用，默认为true
* isAlert:      
* onError:		可选参数,失败回调函数,函数签名为  function (XMLHttpRequest, textStatus, errorThrown)
* onComplete:	可选参数,Ajax调用完成回调函数,函数签名为  function (XMLHttpRequest, textStatus)
*/
window.AjaxCore = function (url, data, onSuccess, modal, async, isAlert, type, onError) {
    var mask = null;
    modal = (modal === false ? false : true);
    if (modal) {
        layer.load(2, { time: 15 * 1000 }); //删除等待,最长30秒
    }
    type = type || "post";
    isAlert = isAlert === undefined ? true : false;
    //var headers = null;
    //if ($.cookie("clientToken")) {
    //    headers = {
    //        "Authorization": "Bearer " + $.cookie("clientToken") //此处放置请求到的用户token
    //    };
    //}
    //axios
    var ajaxHandler = $.ajax({
        type: type,
        url: url,
        cache: false,
        //headers: headers,
        contentType: "application/json",
        dataType: "json",
        xhrFields: { withCredentials: true },
        crossDomain: true,
        data: data,
        async: (async == false ? async : true),
        success: function (json) {
            layer.closeAll('loading');
            var result = json || null;
            if (result.iserror === true && isAlert === true) {
                if (layui)
                    layer.msg(result.message, { icon: 5, shift: 6 });
                else
                    alert(result.message);
            }
            onSuccess(result);
        },
        error: function(error) {
            console.log(error);
            if (onError)onError(error);
        },
        complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
            if (status == 'timeout') { //超时,status还有success,error等值的情况
                alert("访问超时");
                ajaxHandler.abort(); //终止请求
                mask.hide();
            }
        }
    });
};

/* 
* jQuery Ajax调用封装
* url:			调用地址
* data:			可选参数,表示Ajax调用参数
* onSuccess:	可选参数,成功回调函数,函数签名为  function(data), data参数为调用结果
* modal:		可选参数,是否作为模态对话框显示，默认为true
* async:		可选参数,是否异步调用，默认为true
* isAlert:      
* onError:		可选参数,失败回调函数,函数签名为  function (XMLHttpRequest, textStatus, errorThrown)
* onComplete:	可选参数,Ajax调用完成回调函数,函数签名为  function (XMLHttpRequest, textStatus)
*/
window.AjaxGet = function (url, data, onSuccess, modal, async, isAlert, onError, onComplete) {
    if (data) { url = layui.utils.updateURIParamsForJson(url, data); }
    return AjaxCore(url, null, onSuccess, modal, async, isAlert, "get", onError, onComplete);
};
/* 
* jQuery Ajax调用封装
* url:			调用地址
* data:			可选参数,表示Ajax调用参数
* onSuccess:	可选参数,成功回调函数,函数签名为  function(data), data参数为调用结果
* modal:		可选参数,是否作为模态对话框显示，默认为true
* async:		可选参数,是否异步调用，默认为true
* isAlert:      
* onError:		可选参数,失败回调函数,函数签名为  function (XMLHttpRequest, textStatus, errorThrown)
* onComplete:	可选参数,Ajax调用完成回调函数,函数签名为  function (XMLHttpRequest, textStatus)
*/
window.AjaxPost = function (url, data, onSuccess, modal, async, isAlert, onError, onComplete) {
    var jsonData = {
        timestamp: layui.utils.getTimeStamp(new Date().getTime()),
        data: data
    };
    jsonData.sign = "AAA";
    return AjaxCore(url, JSON.stringify(jsonData), onSuccess, modal, async, isAlert, "post", onError, onComplete);
};

window.GetFromData = function (id) {
        var data = {};
        var t = $('#' + id + ' [name]').serializeArray();
        $.each(t, function () {
            data[this.name] = this.value;
        });
        return {
            field: data
        };
};

// 对Date的扩展，将 Date 转化为指定格式的String 
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    for (var time in o) {
        if (isNaN(o[time])) {
            return "";
        }
    }
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

//遮罩层
Maskwin = function () {
    this.show = function (msg) {
        layer.load(2, { time: 15 * 1000 }); //删除等待,最长30秒
        //var h = $(document).height();
        //this.maskmsg = $('<div style="height:100%;width:100%;position:fixed;z-index:99999;background: rgba(0,0,0,0.3);left:0px;top:0px;"><div title="" style="position:absolute;left:45%;top:45%;margin-left:-62px;margin-top:-62px;height:230px;line-height:230px;width:230px;vertical-align:middle;overflow:hidden;color:white;"><div id="spinnerX" class="spinner"><i></i></div></div></div>');
        //if (msg) {
        //    this.maskmsg.find("div").text(msg);
        //}
        //this.maskmsg.appendTo("body");
    };
    this.hide = function () {
        layer.closeAll('loading');
        //this.maskmsg.remove();
    };
};