layui.define(['jquery', 'layer', 'table', 'tableSelect','flow'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;
    var flow = layui.flow;
    var tableSelect = layui.tableSelect;
    var obj = {
        ajax: function (options) {
            var that = this;
            var defaults = {
                url: "",
                type: "get",
                dataType: "json",
                contentType:"application/json;charset=utf-8",
                beforeSend: function (request) {
                    index = layer.load(2);
                },
                success: function (res) {
                    if (res.succeeded) {
                        var newres = res.data;
                        if (newres.code === 0) {
                            that.info(newres.message, function () {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                                //window.parent.layui.admin.closeThisTabs();
                            });
                        } else {
                            that.alert(newres.message);
                        }
                    } else {
                        var msg = "状态码:" + res.statuscode + ",时间戳:" + res.timestamp + ",描述:" + res.errors;
                        that.alert(msg);
                    }
                },
                complete: function () {
                    layer.close(index);
                },
                fail: function (res) {

                }
            };
            options = $.extend(defaults, options);
            if (options.data) {
                options.data = JSON.stringify(options.data);
            }
            $.ajax(options);
        },
        uajax: function (options) {
            var that = this;
            var defaults = {
                url: "",
                type: "get",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                beforeSend: function (request) {
                    index = layer.load(2);
                },
                success: function (res) {
                    if (res.succeeded) {
                        var newres = res.data;
                        if (newres.code === 0) {
                            that.info(res.message, function () {
                                $(".js-search").trigger("click");
                            });
                        } else {
                            that.alert(newres.message);
                        }
                    } else {
                        var msg = "状态码:" + res.statuscode + ",时间戳:" + res.timestamp + ",描述:" + res.errors;
                        that.alert(msg);
                    }
                },
                complete: function () {
                    layer.close(index);
                },
                fail: function (res) {

                }
            };
            options = $.extend(defaults, options);
            if (options.data) {
                options.data = JSON.stringify(options.data);
            }
            $.ajax(options);
        },
        allbuss: function (options) {
            var that = this;
            var defaults = {
                elem: "#businessid",
                checkedKey: "Id",
                searchKey: "businessid",
                searchPlaceholder: '请输入姓名或联系方式',
                done: function (elem, data) {
                    var vals = "";
                    var texts = "";
                    $.each(data.data, function () {
                        vals += this.Id + ",";
                        texts += this.Name + ","
                    });
                    vals = vals.substring(0, vals.length - 1);
                    texts = texts.substring(0, texts.length - 1);
                    $(elem).val(texts);
                    $(elem).attr("ts-selected", vals);
                }
            };
            var tabledefaults = {
                elem: "#businessidlist",
                page: true,
                toolbar: false,
                defaultToolbar: false,
                limit: 10,
                loading: true,
                autoSort: false,
                method: 'post',
                contentType: 'application/json',
                even: true,
                id: 'businessidlist',
                skin: 'row',
                url: "/Business/GetList",
                where: {
                    queryParam: [{
                        "Name": "name",
                        "Type": QueryCond.Like,
                        "Value": $(defaults.elem).val()
                    }, {
                        "Name": "telphone",
                        "Type": QueryCond.Like,
                        "Value": $(defaults.elem).val()
                    }]
                },
                cols: [[
                    {type:'checkbox',field:'Id'},
                    {
                        field: 'Name', title: '客户'
                    },
                    {
                        field: 'TelPhone', title: '联系方式'
                    },
                ]],
                initSort: false,
                text: {
                    none: "暂无相关数据"
                },
                request: {
                    pageName: 'offset'
                },
                response: {
                    "statusName": "code",
                    "msgName": "message",
                    "countName": "totalnum",
                    "dataName": "data"
                },
                parseData: function (res) {
                    return {
                        "data": res.data.Items,
                        "totalnum": res.data.TotalNum,
                        "code": res.code,
                        "message": res.message,
                    };
                },
                //height: 'full-200'
            };
            if (typeof options != "undefined") {
                if (typeof options["url"] != "undefined") {
                    tabledefaults["url"] = options.url;
                }
                if (typeof options["cols"] != "undefined") {
                    tabledefaults["cols"] = options.cols;
                }
            }
            defaults["table"] = tabledefaults;
            options = $.extend(defaults, options);
            tableSelect.render(options);
        },
        allequ: function (options) {
            var that = this;
            var defaults = {
                elem: "#equid",
                checkedKey: "Id",
                searchKey: "equid",
                searchPlaceholder: '请输入设备名称或序列号',
                done: function (elem, data) {
                    var vals = "";
                    var texts = "";
                    $.each(data.data, function () {
                        vals += this.Id + ",";
                        texts += this.Name + ","
                    });
                    vals = vals.substring(0, vals.length - 1);
                    texts = texts.substring(0, texts.length - 1);
                    $(elem).val(texts);
                    $(elem).attr("ts-selected", vals);
                }
            };
            var tabledefaults = {
                elem: "#equidlist",
                page: true,
                toolbar: false,
                defaultToolbar: false,
                limit: 10,
                loading: true,
                autoSort: false,
                method: 'post',
                contentType: 'application/json',
                even: true,
                id: 'equidlist',
                skin: 'row',
                url: "/Device/GetList",
                where: {
                    queryParam: [{
                        "Name": "name",
                        "Type": QueryCond.Like,
                        "Value": $(defaults.elem).val()
                    }, {
                        "Name": "facecode",
                        "Type": QueryCond.Like,
                        "Value": $(defaults.elem).val()
                    }]
                },
                cols: [[
                    { type: 'checkbox', field: 'Id' },
                    {
                        field: 'Name', title: '设备名称'
                    },
                    {
                        field: 'FacEcode', title: '序列号'
                    },
                ]],
                initSort: false,
                text: {
                    none: "暂无相关数据"
                },
                request: {
                    pageName: 'offset'
                },
                response: {
                    "statusName": "code",
                    "msgName": "message",
                    "countName": "totalnum",
                    "dataName": "data"
                },
                parseData: function (res) {
                    return {
                        "data": res.data.Items,
                        "totalnum": res.data.TotalNum,
                        "code": res.code,
                        "message": res.message,
                    };
                },
                //height: 'full-200'
            };
            if (typeof options != "undefined") {
                if (typeof options["url"] != "undefined") {
                    tabledefaults["url"] = options.url;
                }
                if (typeof options["cols"] != "undefined") {
                    tabledefaults["cols"] = options.cols;
                }
            }
            defaults["table"] = tabledefaults;
            options = $.extend(defaults, options);
            tableSelect.render(options);
        },
        allorder: function (options) {
            var that = this;
            var defaults = {
                elem: "#orderid",
                checkedKey: "Id",
                searchKey: "orderid",
                searchPlaceholder: '请输入订单名称',
                done: function (elem, data) {
                    var vals = "";
                    var texts = "";
                    $.each(data.data, function () {
                        vals += this.Id + ",";
                        texts += this.Name + ","
                    });
                    vals = vals.substring(0, vals.length - 1);
                    texts = texts.substring(0, texts.length - 1);
                    $(elem).val(texts);
                    $(elem).attr("ts-selected", vals);
                }
            };
            var tabledefaults = {
                elem: "#orderidlist",
                page: true,
                toolbar: false,
                defaultToolbar: false,
                limit: 10,
                loading: true,
                autoSort: false,
                method: 'post',
                contentType: 'application/json',
                even: true,
                id: 'orderidlist',
                skin: 'row',
                url: "/Order/GetList",
                where: {
                    queryParam: [{
                        "Name": "name",
                        "Type": QueryCond.Like,
                        "Value": $(defaults.elem).val()
                    }]
                },
                cols: [[
                    { type: 'checkbox', field: 'Id' },
                    {
                        field: 'Name', title: '订单名称'
                    }
                ]],
                initSort: false,
                text: {
                    none: "暂无相关数据"
                },
                request: {
                    pageName: 'offset'
                },
                response: {
                    "statusName": "code",
                    "msgName": "message",
                    "countName": "totalnum",
                    "dataName": "data"
                },
                parseData: function (res) {
                    return {
                        "data": res.data.Items,
                        "totalnum": res.data.TotalNum,
                        "code": res.code,
                        "message": res.message,
                    };
                },
                //height: 'full-200'
            };
            if (typeof options != "undefined") {
                if (typeof options["url"] != "undefined") {
                    tabledefaults["url"] = options.url;
                }
                if (typeof options["cols"] != "undefined") {
                    tabledefaults["cols"] = options.cols;
                }
            }
            defaults["table"] = tabledefaults;
            options = $.extend(defaults, options);
            tableSelect.render(options);
        },
        alloff: function (options) {
            var that = this;
            var defaults = {
                elem: "#publicid",
                checkedKey: "Id",
                searchKey: "publicid",
                searchPlaceholder: '请输入公众号名称',
                done: function (elem, data) {
                    var vals = "";
                    var texts = "";
                    $.each(data.data, function () {
                        vals += this.user_name + ",";
                        texts += this.nick_name + ","
                    });
                    vals = vals.substring(0, vals.length - 1);
                    texts = texts.substring(0, texts.length - 1);
                    $(elem).val(texts);
                    $(elem).attr("ts-selected", vals);
                }
            };
            var tabledefaults = {
                elem: "#publicidlist",
                page: true,
                toolbar: false,
                defaultToolbar: false,
                limit: 10,
                loading: true,
                autoSort: false,
                method: 'post',
                contentType: 'application/json',
                even: true,
                id: 'publicidlist',
                skin: 'row',
                url: "/OfficialAccount/GetList",
                where: {
                    queryParam: [{
                        "Name": "nick_name",
                        "Type": QueryCond.Like,
                        "Value": $(defaults.elem).val()
                    }]
                },
                cols: [[
                    { type: 'checkbox', field: 'Id' },
                     {
                         field: 'head_img', title: '头像', templet: function (d) {
                             var img = '<a  href="' + d.head_img + '" data-lightbox="xb" data-title="' + d.nick_name + '"><img class="img-responsive" lay-src="' + d.head_img + '" style="max-height:50px;" /></a>';
                             return img;
                         }
                     },
                    {
                        field: 'nick_name', title: '昵称'
                    }
                ]],
                initSort: false,
                text: {
                    none: "暂无相关数据"
                },
                request: {
                    pageName: 'offset'
                },
                response: {
                    "statusName": "code",
                    "msgName": "message",
                    "countName": "totalnum",
                    "dataName": "data"
                },
                parseData: function (res) {
                    return {
                        "data": res.data.Items,
                        "totalnum": res.data.TotalNum,
                        "code": res.code,
                        "message": res.message,
                    };
                },
                 done: function () {
                    flow.lazyimg();
                }
                //height: 'full-200'
            };
            if (typeof options != "undefined") {
                if (typeof options["url"] != "undefined") {
                    tabledefaults["url"] = options.url;
                }
                if (typeof options["cols"] != "undefined") {
                    tabledefaults["cols"] = options.cols;
                }
            }
            defaults["table"] = tabledefaults;
            options = $.extend(defaults, options);
            tableSelect.render(options);
        },
        echarts: function (options) {
            var defaults = {
                id: "charts",
                tooltip: {                                  // 气泡提示配置
                    trigger: 'axis',                        // 触发类型，默认数据触发，可选为：'axis'
                },
                dataZoom: [ //滚轮缩放
                {
                    show: false,
                    realtime: true,
                    start: 0,
                    end: 100
                },
                {
                    type: 'inside',
                    realtime: true,
                    start: 0,
                    end: 100
                }
                ],
                title: {
                    text: '趋势图'
                },
                yAxis: {
                    type: 'value'
                },
                grid: {
                    left: '3%',
                    right: '3%',
                    containLabel: true
                },
                toolbox: {
                    show: true,
                    feature: {
                        restore: {},
                        magicType: { type: ['line', 'bar'] },
                        saveAsImage: { type: "jpeg" }
                    }
                }
            };
            options = $.extend(defaults, options);
            if (typeof options.series !== "undefined" && options.series.length > 0) {
                $.each(options.series, function (i, that) {
                    if (typeof this["itemStyle"] === "undefined") {
                        this["itemStyle"] = {
                            normal: {
                                label: {
                                    show: true
                                }
                            }
                        };
                    }
                    if (typeof this["type"] === "undefined") {
                        this["type"] = "line";
                    }
                    if (typeof this["smooth"] === "undefined") {
                        this["smooth"] = true;
                    }
                    if (typeof this["stack"] === "undefined") {
                        this["stack"] = "总量";
                    }
                });
            }
            if (typeof options.xAxis !== "undefined") {
                if (typeof options.xAxis["boundaryGap"] === "undefined") {
                    options.xAxis["boundaryGap"] = false;
                }
                if (typeof options.xAxis["type"] === "undefined") {
                    options.xAxis["type"] = "category";
                }
            }
            if (typeof options.legend !== "undefined") {
                if (typeof options.legend["bottom"] === "undefined") {
                    options.legend["bottom"] = 10;
                }
            }
            console.log(options);
            var mychart = echarts.init(document.getElementById(options.id), 'ybhdmob');
            mychart.setOption(options);
            window.onresize = mychart.resize
        },
        alert: function (options, callback) {
            var defaults = {
                content: '错误',
                icon: 2,
                offset: '50px',
                yes: function (index, layero) {
                    layer.close(index);
                    if (typeof callback !== "undefined") {
                        callback();
                    }
                }
            };
            if (typeof options === "string") {
                defaults.content = options;
                layer.alert(defaults.content, defaults, defaults.yes);
            } else {
                options = $.extend(defaults, options);
                layer.alert(options.content, options, options.yes)
            }
        },
        msg: function (options, callback) {
            var defaults = {
                offset: '50px'
            };
            layer.msg(options, defaults);
        },
        info: function (options, callback) {
            var defaults = {
                icon: 1,
                content: '成功',
                offset: '50px',
                yes: function (index, layero) {
                    layer.close(index);
                    if (typeof callback !== "undefined") {
                        callback();
                    }
                }
            };
            if (typeof options === "string") {
                defaults.content = options;
                layer.alert(options, defaults);
            } else {
                options = $.extend(defaults, options);
                layer.open(options)
            }
        },
        confirm: function (message, callback, options) {
            var defaults = {
                icon: 3,
                title: '提示',
                offset: '50px',
            };
            options = $.extend(defaults, options);
            layer.confirm(message, options, function (index) {
                layer.close(index);
                callback();
            })
        },
        prompt: function (options, callbakc) {
            var defaults = {
                fromType: 0,
                title: '请输入内容',
                offset: '50px',
                value: '请输入内容'
            };
            options = $.extend(defaults, options);
            layer.prompt(options, function (pass, index) {
                layer.close(index);
                callbakc(pass);
            });
        },
        initTable: function (options) {
            var defaults = {
                elem: "#list",
                page: true,
                toolbar: "#toolbar",
                defaultToolbar: [{
                    title: '刷新',
                    layEvent: 'LAYTABLE_REFRESH',
                    icon: 'layui-icon-refresh'
                }, "filter", "print", "exports"],
                limit: 10,
                loading: true,
                autoSort: false,
                contentType: 'application/json',
                even: true,
                id: 'list',
                skin: 'row',
                initSort: false,
                text: {
                    none: "暂无相关数据"
                },
                request: {
                    pageName: 'offset'
                },
                ontoolbarevent: function (obj) {
                    return obj;
                },
                response: {
                    "statusName": "statuscode",
                    "statusCode":200,
                    "msgName": "message",
                    "countName": "totalnum",
                    "dataName": "data"
                },
                parseData: function (res) {
                    return {
                        "data": res.data.items,
                        "totalnum": res.data.totalnum,
                        "statuscode": res.statuscode,
                        "message": res.message,
                    };
                },
                done: function (res,curr,count) {
                    flow.lazyimg();
                    if (options.ondone) {
                        options.ondone(res, curr, count);
                    }
                }
                //height: 'full-200'
            };
            options = $.extend(defaults, options);
            table.render(options);
            //监听排序事件 
            table.on('sort(' + options.id + ')', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                table.reload(options.id, {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                  , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                      sort: obj.field //排序字段
                    , order: obj.type //排序方式
                  }
                });
            });

            table.on('toolbar(' + options.id + ')', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                var event = obj.event;
                if (event == "LAYTABLE_REFRESH") {
                    table.reload(options.id, options);
                }
                options.ontoolbarevent(obj);
            });
        },
        reloadtable: function (id, options) {
            if (typeof id === "undefined") {
                id = 'list';
            }
            if (options) {
                options["page"] = {
                    curr: 1
                };
            }
            table.reload(id, options);
        },
        dialog: function (options) {
            var that = this;
            var defaults = {
                title: '添加',
                type: 2,
                content: '',
                success: function (layero, index) {
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回上一级', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500)
                },
                end: function () {
                    that.reloadtable();
                    if (typeof options.close !== "undefined") {
                        options.close();
                    }
                    window.sessionStorage.setItem("indexs", 0);
                }
            };
            options = $.extend(defaults, options);
            var index = layer.open(options);
            window.sessionStorage.setItem("indexs", index);
            layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            //$(window).on("resize", function () {
            //    if (window.sessionStorage.getItem("indexs") > 0) {
            //        layer.full(window.sessionStorage.getItem("indexs"));
            //    }
            //})
        },
        tabdialog: function (options) {
            var that = this;
            var defaults = {
                title: '添加',
                type: 2,
                content: '',
                success: function (layero, index) {
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回上一级', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500)
                },
                end: function () {
                    that.reloadtable();
                    if (typeof options.close !== "undefined") {
                        options.close();
                    }
                    window.sessionStorage.setItem("indexs", 0);
                }
            };
            options = $.extend(defaults, options);
            window.parent.layui.index.openTabsPage(options.content, options.title)
        },
        normaldialog: function (options) {
            var defaults = {
                title: '添加',
                type: 2,
                content: '',
                area: ['50%', '50%'],
                offset: '50px',
                end: function () {
                    $(".js-search").trigger("click");
                    if (typeof options.close !== "undefined") {
                        options.close();
                    }
                }
            };
            options = $.extend(defaults, options);
            layer.open(options);
        },
        closedialog: function (index) {
            if (typeof index === "undefined") {
                index = window.sessionStorage.getItem("index");
            }
            layer.close(index);
        },
        clientsInit: function (callback, isrefresh) {
            var that = this;
            if (!isrefresh && typeof sessionStorage.getItem("clientdata") !== "undefined" && sessionStorage.getItem("clientdata") !== null) {
                var data = sessionStorage.getItem("clientdata");
                data = JSON.parse(data);
                callback(data);
                return;
            }
            that.ajax({
                url: "/ClientsData",
                async: false,
                success: function (data) {
                    sessionStorage.setItem("clientdata", JSON.stringify(data.data));
                    callback(data.data);
                }
            });
        },
        datetime: function (time) {
            if (typeof time === "undefined" || time === null) {
                time = moment();
            }
            time = new Date(time * 1000)
            return moment(time).format("YYYY-MM-DD HH:mm:ss");
        },
        cdatetime: function (time) {
            if (typeof time === "undefined" || time === null) {
                time = moment();
            }
            return moment(time).format("YYYY-MM-DD HH:mm:ss");
        },
        preview:function(options) {
            var defaults = {
                photos: {
                    "title": "图片预览",
                    "id": 1,
                    "start": 0,
                    "data": [
                        {
                            "alt": "",
                            "pid": 1,
                            "src": "",
                            "thumb": ""
                        }
                    ]
                }
            };
            options = $.extend(defaults, options);
            layer.photos(options);
        },
        previewimg: function (src) {
            var defaults = {
                photos: {
                    "title": "图片预览",
                    "id": 1,
                    "start": 0,
                    "data": [
                        {
                            "alt": "",
                            "pid": 1,
                            "src": src,
                            "thumb": ""
                        }
                    ]
                }
            };
            layer.photos(defaults);
        }
    };
    //输出接口
    exports('common', obj);
});