/**
 * 公共方法类
 *
 * 使用  变量名=function()定义函数时，如果在变量名前加var，则这个变量变成局部变量
 */

var elab_common = function () {

    var longConvertDateTime = function (longTypeDate) {
        if (longTypeDate == "" || longTypeDate == undefined) {
            return "";
        }
        var datetimeType = "";
        var date = new Date();
        date.setTime(longTypeDate);
        datetimeType += date.getFullYear();   //年
        datetimeType += "-" + getMonth(date); //月
        datetimeType += "-" + getDay(date);   //日
        datetimeType += " " + getHours(date);   //时
        datetimeType += ":" + getMinutes(date);      //分
        datetimeType += ":" + getSeconds(date);      //分
        return datetimeType;
    }

    //返回 01-12 的月份值
    function getMonth(date) {
        var month = "";
        month = date.getMonth() + 1; //getMonth()得到的月份是0-11
        if (month < 10) {
            month = "0" + month;
        }
        return month;
    }

    //返回01-30的日期
    function getDay(date) {
        var day = "";
        day = date.getDate();
        if (day < 10) {
            day = "0" + day;
        }
        return day;
    }

    //返回小时
    function getHours(date) {
        var hours = "";
        hours = date.getHours();
        if (hours < 10) {
            hours = "0" + hours;
        }
        return hours;
    }

    //返回分
    function getMinutes(date) {
        var minute = "";
        minute = date.getMinutes();
        if (minute < 10) {
            minute = "0" + minute;
        }
        return minute;
    }

    //返回秒
    function getSeconds(date) {
        var second = "";
        second = date.getSeconds();
        if (second < 10) {
            second = "0" + second;
        }
        return second;
    }

    var getQueryStr = function (sUrlParam, sArgName) {
        var retval = "";
        if (sUrlParam == null || sUrlParam.length == 0) {
            return retval;
        }
        var args = sUrlParam.split("&");
        for (var i = 0; i < args.length; i++) {
            sUrlParam = args[i];
            var arg = sUrlParam.split("=");
            if (arg.length <= 1)
                continue;
            if (arg[0] == sArgName)
                retval = arg[1];
        }
        return retval;
    }


    var getReq = function (url, param, fnCallback) {
        var target, options = {
            title: "异常信息",
            content: "",
            bodyType: "errorMessage"
        };

        $.ajax({
            url: url,
            type: "GET",
            timeout: 300000,
            headers: "Access-Control-Allow-Origin:*",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            data: param
        }).done(function (data, textStatus, jqXHR) {
            if (jqXHR.getResponseHeader('sessionStatus') == 'timeout') {
                options.content = '会话已经超时.';
                target.showModal(options, function () {
                    target.location.href = 'login.html';
                });
            } else if (!data) {
                options.content = '无返回信息.';
                target.showModal(options, function () {
                    // donothing
                });
            } else {
                fnCallback(data);
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 0) {
                options.content = '请求异常，网络连接失败！';
            } else if (jqXHR.status == 403) {
                options.content = jqXHR.responseJSON.message;
            } else {
                options.content = "请求异常，状态码：" + jqXHR.status;
            }
            target.showModal(options, function () {
                // donothing
            });
        });
    };
    /*
     * ajax发送post请求
     */
    var postReq = function (url, param, fnCallback, isIndex) {
        var target, options = {
            title: "异常信息",
            content: "",
            bodyType: "errorMessage"
        };

        if (isIndex) {
            target = window;
        } else {
            target = window.parent;
        }
        $.ajax({
            url: url,
            type: "POST",
            timeout: 300000,
            headers: "Access-Control-Allow-Origin:*",
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            dataType: "json",
            data: param
        }).done(function (data, textStatus, jqXHR) {
            if (jqXHR.getResponseHeader('sessionStatus') == 'timeout') {
                options.content = '会话已经超时.';
                target.showModal(options, function () {
                    target.location.href = 'login.html';
                });
            } else if (!data) {
                options.content = '无返回信息.';
                target.showModal(options, function () {
                    // donothing
                });
            } else {
                fnCallback(data);
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 0) {
                options.content = '请求异常，网络连接失败！';
            } else if (jqXHR.status == 403) {
                options.content = jqXHR.responseJSON.message;
            } else {
                options.content = "请求异常，状态码：" + jqXHR.status;
            }

            target.showModal(options, function () {
                // donothing
            });
        });
    };

    var postReq = function (url, param, fnCallback, isIndex) {
        var target, options = {
            title: "异常信息",
            content: "",
            bodyType: "errorMessage"
        };

        if (isIndex) {
            target = window;
        } else {
            target = window.parent;
        }

        $.ajax({
            url: url,
            type: "POST",
            timeout: 300000,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            data: JSON.stringify(param)
        }).done(function (data, textStatus, jqXHR) {
            if (jqXHR.getResponseHeader('sessionStatus') == 'timeout') {
                options.content = '会话已经超时.';
                target.showModal(options, function () {
                    target.location.href = 'login.html';
                });
            } else if (!data) {
                options.content = '无返回信息.';
                target.showModal(options, function () {
                    // donothing
                });
            } else {
                fnCallback(data);
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 0) {
                options.content = '请求异常，网络连接失败！';
            } else if (jqXHR.status == 403) {
                options.content = jqXHR.responseJSON.message;
            } else {
                options.content = "请求异常，状态码：" + jqXHR.status;
            }

            target.showModal(options, function () {
                // donothing
            });
        });
    };

    /**
     * 封装layui默认的table配置
     * @param title
     * @param url
     * @param method
     * @param dataColumn
     */
    var layUITable = function layUITable(layer, table, title, listUrl, method, dataColumn, updateUrl, delUrl) {
        table.render({
            elem: '#list_table'
            , id: 'tableList'
            , title: title
            , toolbar: '#toolbarDemo'
            , defaultToolbar: ['filter', 'print']
            , method: method
            , url: listUrl
            , cellMinWidth: 80
            , contentType: "application/json"
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'limit', 'pageSize', 'prev', 'page', 'next', 'first', 'last', 'skip'] //自定义分页布局
                , curr: 1 //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
            }, parseData: function (res) { //res 即为原始返回的数据
                debugger;
                return {
                    "code": res.success == true ? 0 : 500, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.pageModel.count, //解析数据长度
                    "data": res.pageModel.resultSet //解析数据列表
                };
            }, request: {
                pageName: 'pageNo' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [
                dataColumn
            ]
        });
    }

    /**
     * 表格的增删改查
     * @param layer 核心控件
     * @param table 表格控件
     * @param title 标题
     * @param listUrl   列表的服务请求地址
     * @param method    列表的服务请求方法
     * @param dataColumn    数据展现数组
     * @param updateUrl    修改的路由地址
     * @param delUrl        删除的路由地址
     */
    var layUITableDML = function layUITableDML(layer, table, title, listUrl, method, dataColumn, updateUrl, delUrl) {
        layUITable(layer, table, title, listUrl, method, dataColumn);
        table.on('tool(list_table)', function (obj) {
            var field = obj.data;
            if (obj.event === 'del') {
                layer.confirm('确定删除此行？', function (index) {
                    obj.del();
                    // 向服务端发送删除指令
                    var requestData = {id: field.id, status: -1, updated: new Date()};
                    elab_common.postReq(delUrl, requestData, function (data) {
                        if (!data.success) {
                            layer.alert(data.message);
                        }
                    });
                });
            } else if (obj.event === 'edit') {
                layer.open({
                    type: 2,
                    area: ['80%', '90%'],
                    fixed: false, //不固定
                    maxmin: true,
                    content: updateUrl + '?id=' + obj.data.id
                });
            }
        });

        //头工具栏事件
        table.on('toolbar(list_table)', function (obj) {
            var event = obj.event;
            if ("addData" == event) {
                layer.open({
                    type: 2,
                    area: ['80%', '90%'],
                    fixed: false, //不固定
                    maxmin: true,
                    content: '/project/add.html'
                });
            }
        });
    }

    /**
     * 从elab-config配置中获取对应的集合列表
     *
     * @param groupType
     * @param key
     * @returns {*}
     */
    var getConfigTypeConfigList = function getConfigByList(groupType) {
        var elabConfigElement = elabConfig[groupType];
        return elabConfigElement;
    };

    /**
     * 从elab-config配置中获取对应的文本值
     *
     * @param groupType
     * @param key
     * @returns {*}
     */
    var getConfigTypeText = function getConfigByList(groupType, key) {
        var elabConfigElement = elabConfig[groupType][key];
        return elabConfigElement;
    };

    var findSelectProductList = function findSelectProductList(fnCallback) {
        elab_common.postReq("/project/findProductNameList", {}, function (data) {
            $('#q_product').append(new Option("", ""));
            $.each(data.list, function (index, item) {
                $('#q_product').append(new Option(item.productName, item.productName));// 下拉菜单里添加元素
            });
            fnCallback(data);
        }, true)
    };

    var findBranchList = function findBranchList(projectId, defaultValue, fnCallback) {
        elab_common.getReq("/project/getBranchList?id=" + projectId, {}, function (data) {
            $('#q_branch').empty();
            $('#q_branch').append(new Option("", "", true));
            $.each(data.list, function (index, item) {
                if (item == defaultValue) {
                    $('#q_branch').append(new Option(item.projectName, item.id, true, true));// 下拉菜单里添加元素
                } else {
                    $('#q_branch').append(new Option(item, item));// 下拉菜单里添加元素

                }
            });
            fnCallback(data);
        }, true);
    };

    /**
     * 获取标签分类数据
     * @param level         级别
     * @param parentid      父类编号
     * @param defaultValue  默认值
     * @param fnCallback    回调方法
     */
    var findTagLevelSelect = function findTagLevelSelect(level, parentid, defaultValue, fnCallback) {
        elab_common.postReq("/tagtype/getObjectByList", {"level": level, "parentid": parentid}, function (data) {
            var id = '#q_TagLevel_' + level;
            // $(id).empty();
            // $(id).append(new Option("", "", true));
            cleanTagLevel(level);
            $.each(data.list, function (index, item) {
                if (item.id != null && item.id == defaultValue) {
                    $(id).append(new Option(item.name, item.id, true, true));
                } else {
                    $(id).append(new Option(item.name, item.id));// 下拉菜单里添加元素
                }
            });
            fnCallback(level);
        }, true);
    };


    function cleanTagLevel(level) {
        if (Number(level) <= 4) {
            var id = '#q_TagLevel_' + level;
            $(id).empty();
            $(id).append(new Option("", "", true));
            cleanTagLevel(Number(level + 1));
        }
    }


    /**
     * 根据elab-config中定义的配置文件获取数值并插入相应的select选项中
     * @param id
     * @param groupType
     * @param defaultValue
     */
    var getConfigTypeBySelect = function getConfigTypeBySelect(id, groupType, defaultValue) {
        var typeConfigList = elab_common.getConfigTypeConfigList(groupType);
        $(id).append(new Option("", ""));
        $.each(typeConfigList, function (key, value) {
            if (key == defaultValue) {
                $(id).append(new Option(value, key, true, true));// 下拉菜单里添加元素
            } else {
                $(id).append(new Option(value, key));// 下拉菜单里添加元素
            }

        })
    };

    var getConfigTypeByCheckBox = function getConfigTypeByCheckBox(id, groupType, fieldName, defaultValueArray) {
        var typeConfigList = elab_common.getConfigTypeConfigList(groupType);
        var html = "<input type=\"checkbox\" name=\"" + fieldName + "\" value='jsonKey' title=\"jsonValue\" jsonChecked />"
        // $(id).append(new Option("", ""));
        $.each(typeConfigList, function (key, value) {
            if (defaultValueArray.indexOf(key) > -1) {
                $(id).append(html.replace("jsonKey", key).replace("jsonValue", value).replace("jsonChecked", "checked='checked'"));// 下拉菜单里添加元素
            } else {
                $(id).append(html.replace("jsonKey", key).replace("jsonValue", value).replace("jsonChecked", ""));// 下拉菜单里添加元素
            }

        })
    };

    var getLayerUICheckValue = function getLayerUICheckValue(field) {
        var checkarray = [];
        $("input:checkbox[name='" + field + "']:checked").each(function (i) {
            checkarray[i] = $(this).val();
        });
        return checkarray;
    };


    var setCookie = function setCookie(c_name, value, expiredays) {
        var exdate = new Date()
        exdate.setDate(exdate.getDate() + expiredays)
        document.cookie = c_name + "=" + escape(value) +
            ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
    };

    var getCookie = function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=")
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1
                c_end = document.cookie.indexOf(";", c_start)
                if (c_end == -1) c_end = document.cookie.length
                return unescape(document.cookie.substring(c_start, c_end))
            }
        }
        return ""
    };

    return {
        getReq: getReq,
        getQueryStr: getQueryStr,
        postReq: postReq,
        findTagLevelSelect: findTagLevelSelect,
        findSelectProductList: findSelectProductList,
        getConfigTypeConfigList: getConfigTypeConfigList,
        getConfigTypeText: getConfigTypeText,
        getConfigTypeBySelect: getConfigTypeBySelect,
        getConfigTypeByCheckBox: getConfigTypeByCheckBox,
        getLayerUICheckValue: getLayerUICheckValue,
        findBranchList: findBranchList,
        longConvertDateTime: longConvertDateTime,
        setCookie: setCookie,
        getCookie: getCookie,
        layUITable: layUITable,
        layUITableDML: layUITableDML
    }
}();